commit stringlengths 40 40 | old_file stringlengths 4 150 | new_file stringlengths 4 150 | old_contents stringlengths 0 3.26k | new_contents stringlengths 1 4.43k | subject stringlengths 15 501 | message stringlengths 15 4.06k | lang stringclasses 4 values | license stringclasses 13 values | repos stringlengths 5 91.5k | diff stringlengths 0 4.35k |
|---|---|---|---|---|---|---|---|---|---|---|
4af5e3c9e48ff997084d5316f384b3c6411edaa3 | test/dump.py | test/dump.py | import subprocess
from tempfile import NamedTemporaryFile
def dump_table(table):
def handle_record(record, fields):
def handle_field(column, field):
return '%d:%d:%d %s' % (record, column, len(field), field)
return '\n'.join(handle_field(column, field) for (column, field) in
enumerate(fields))
dump = '\n'.join(handle_record(record, fields) for (record, fields) in
enumerate(table))
return '\n'.join(filter(lambda s: s != '', dump.splitlines()))
def dump_text(text, b=False, d=None, e=None, q=None):
with NamedTemporaryFile() as outfile:
outfile.write(text)
outfile.flush()
return _dump(outfile.name, b, d, e, q).strip('\n')
def _dump(filename, b=False, d=None, e=None, q=None):
args = ['./dump']
if b:
args.append('-b')
if d:
args.append('-d%s' % d)
if e:
args.append('-e%s' % e)
if q:
args.append('-q%s' % q)
args.append(filename)
return _popen(args)
def _popen(args):
pipe = subprocess.PIPE
process = subprocess.Popen(args, stdout=pipe, stderr=pipe)
stdout, stderr = process.communicate()
return stderr if len(stderr) > 0 else stdout
| import subprocess
import tempfile
def dump_table(table):
def handle_record(record, fields):
def handle_field(column, field):
return '%d:%d:%d %s' % (record, column, len(field), field)
return '\n'.join(handle_field(column, field) for (column, field) in
enumerate(fields))
dump = '\n'.join(handle_record(record, fields) for (record, fields) in
enumerate(table))
return '\n'.join(filter(lambda s: s != '', dump.splitlines()))
def dump_text(text, b=False, d=None, e=None, q=None):
with tempfile.NamedTemporaryFile() as outfile:
outfile.write(text)
outfile.flush()
return _dump(outfile.name, b, d, e, q).strip('\n')
def _dump(filename, b=False, d=None, e=None, q=None):
args = ['./dump']
if b:
args.append('-b')
if d:
args.append('-d%s' % d)
if e:
args.append('-e%s' % e)
if q:
args.append('-q%s' % q)
args.append(filename)
return _popen(args)
def _popen(args):
pipe = subprocess.PIPE
process = subprocess.Popen(args, stdout=pipe, stderr=pipe)
stdout, stderr = process.communicate()
return stderr if len(stderr) > 0 else stdout
| Use 'import' for 'tempfile' module | Use 'import' for 'tempfile' module
| Python | mit | jvirtanen/fields,jvirtanen/fields | ---
+++
@@ -1,6 +1,5 @@
import subprocess
-
-from tempfile import NamedTemporaryFile
+import tempfile
def dump_table(table):
@@ -14,7 +13,7 @@
return '\n'.join(filter(lambda s: s != '', dump.splitlines()))
def dump_text(text, b=False, d=None, e=None, q=None):
- with NamedTemporaryFile() as outfile:
+ with tempfile.NamedTemporaryFile() as outfile:
outfile.write(text)
outfile.flush()
return _dump(outfile.name, b, d, e, q).strip('\n') |
5b10184e132004e2b9bd6424fc56cf7f4fc24716 | imagersite/imager_profile/models.py | imagersite/imager_profile/models.py | """Models."""
from django.db import models
# Create your models here.
class ImagerProfile(models.Model):
"""Imager Profile Model."""
camera_model = models.CharField(max_length=200)
photography_type = models.TextField()
friends = models.ManyToManyField('self')
region = models.CharField(max_length=200)
| """Models."""
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class ImagerProfile(models.Model):
"""Imager Profile Model."""
camera_model = models.CharField(max_length=200)
photography_type = models.TextField()
# friends = models.ManyToManyField('self')
region = models.CharField(max_length=200)
user = models.OneToOneField(User, unique=True, null=False)
def is_active(self):
"""Return if the user can log in."""
return self.user.is_active
class ActiveUserManager(models.Manager):
"""Manager to grab active users."""
def get_query_set(self):
"""Return only active users."""
return super(ActiveUserManager, self).get_query_set().filter(user.is_active())
| Add model manager, still needs work | Add model manager, still needs work
| Python | mit | DZwell/django-imager | ---
+++
@@ -1,5 +1,6 @@
"""Models."""
from django.db import models
+from django.contrib.auth.models import User
# Create your models here.
@@ -10,8 +11,24 @@
camera_model = models.CharField(max_length=200)
photography_type = models.TextField()
- friends = models.ManyToManyField('self')
+ # friends = models.ManyToManyField('self')
region = models.CharField(max_length=200)
+ user = models.OneToOneField(User, unique=True, null=False)
+
+ def is_active(self):
+ """Return if the user can log in."""
+ return self.user.is_active
+
+
+class ActiveUserManager(models.Manager):
+ """Manager to grab active users."""
+
+ def get_query_set(self):
+ """Return only active users."""
+ return super(ActiveUserManager, self).get_query_set().filter(user.is_active())
+
+
+ |
27d7ab7ecca0d2e6307dbcb1317b486fe77a97d7 | cyder/core/system/models.py | cyder/core/system/models.py | from django.db import models
from cyder.base.mixins import ObjectUrlMixin
from cyder.base.models import BaseModel
from cyder.cydhcp.keyvalue.models import KeyValue
class System(BaseModel, ObjectUrlMixin):
name = models.CharField(max_length=255, unique=False)
search_fields = ('name',)
display_fields = ('name', 'pk')
def __str__(self):
return "{0} : {1}".format(*(str(getattr(self, f))
for f in self.display_fields))
class Meta:
db_table = 'system'
def details(self):
"""For tables."""
data = super(System, self).details()
data['data'] = [
('Name', 'name', self),
]
return data
@staticmethod
def eg_metadata():
"""EditableGrid metadata."""
return {'metadata': [
{'name': 'name', 'datatype': 'string', 'editable': True},
]}
class SystemKeyValue(KeyValue):
system = models.ForeignKey(System, null=False)
class Meta:
db_table = 'system_key_value'
unique_together = ('key', 'value', 'system')
| from django.db import models
from cyder.base.mixins import ObjectUrlMixin
from cyder.base.models import BaseModel
from cyder.base.helpers import get_display
from cyder.cydhcp.keyvalue.models import KeyValue
class System(BaseModel, ObjectUrlMixin):
name = models.CharField(max_length=255, unique=False)
search_fields = ('name',)
display_fields = ('name',)
def __str__(self):
return get_display(self)
class Meta:
db_table = 'system'
def details(self):
"""For tables."""
data = super(System, self).details()
data['data'] = [
('Name', 'name', self),
]
return data
@staticmethod
def eg_metadata():
"""EditableGrid metadata."""
return {'metadata': [
{'name': 'name', 'datatype': 'string', 'editable': True},
]}
class SystemKeyValue(KeyValue):
system = models.ForeignKey(System, null=False)
class Meta:
db_table = 'system_key_value'
unique_together = ('key', 'value', 'system')
| Revert system names to normal | Revert system names to normal
| Python | bsd-3-clause | drkitty/cyder,OSU-Net/cyder,drkitty/cyder,murrown/cyder,zeeman/cyder,OSU-Net/cyder,zeeman/cyder,murrown/cyder,akeym/cyder,akeym/cyder,akeym/cyder,zeeman/cyder,drkitty/cyder,OSU-Net/cyder,zeeman/cyder,murrown/cyder,akeym/cyder,murrown/cyder,drkitty/cyder,OSU-Net/cyder | ---
+++
@@ -2,6 +2,7 @@
from cyder.base.mixins import ObjectUrlMixin
from cyder.base.models import BaseModel
+from cyder.base.helpers import get_display
from cyder.cydhcp.keyvalue.models import KeyValue
@@ -9,11 +10,10 @@
name = models.CharField(max_length=255, unique=False)
search_fields = ('name',)
- display_fields = ('name', 'pk')
+ display_fields = ('name',)
def __str__(self):
- return "{0} : {1}".format(*(str(getattr(self, f))
- for f in self.display_fields))
+ return get_display(self)
class Meta:
db_table = 'system' |
78f6bda69c7cdcb52057971edc0853b0045aa31a | gitfs/views/history.py | gitfs/views/history.py | from datetime import datetime
from errno import ENOENT
from stat import S_IFDIR
from pygit2 import GIT_SORT_TIME
from gitfs import FuseOSError
from log import log
from .view import View
class HistoryView(View):
def getattr(self, path, fh=None):
'''
Returns a dictionary with keys identical to the stat C structure of
stat(2).
st_atime, st_mtime and st_ctime should be floats.
NOTE: There is an incombatibility between Linux and Mac OS X
concerning st_nlink of directories. Mac OS X counts all files inside
the directory, while Linux counts only the subdirectories.
'''
return dict(st_mode=(S_IFDIR | 0755), st_nlink=2)
def opendir(self, path):
return 0
def releasedir(self, path, fi):
pass
def access(self, path, amode):
log.info('%s %s', path, amode)
return 0
def readdir(self, path, fh):
return ['.', '..', 'gigi are mere']
| import os
from stat import S_IFDIR
from pygit2 import GIT_FILEMODE_TREE
from log import log
from .view import View
class HistoryView(View):
def getattr(self, path, fh=None):
'''
Returns a dictionary with keys identical to the stat C structure of
stat(2).
st_atime, st_mtime and st_ctime should be floats.
NOTE: There is an incombatibility between Linux and Mac OS X
concerning st_nlink of directories. Mac OS X counts all files inside
the directory, while Linux counts only the subdirectories.
'''
return dict(st_mode=(S_IFDIR | 0755), st_nlink=2)
def opendir(self, path):
return 0
def releasedir(self, path, fi):
pass
def access(self, path, amode):
log.info('%s %s', path, amode)
return 0
def _get_commit_subtree(self, tree, subtree_name):
for e in tree:
if e.filemode == GIT_FILEMODE_TREE:
if e.name == subtree_name:
return self.repo[e.id]
else:
return self._get_commit_subtree(self.repo[e.id],
subtree_name)
def readdir(self, path, fh):
dir_entries = ['.', '..']
commit = self.repo.revparse_single(self.commit_sha1)
if getattr(self, 'relative_path'):
tree_name = os.path.split(self.relative_path)[1]
subtree = self._get_commit_subtree(commit.tree, tree_name)
[dir_entries.append(entry.name) for entry in subtree]
else:
[dir_entries.append(entry.name) for entry in commit.tree]
return dir_entries
| Add the possibility of browsing the tree of a particular commit. | Add the possibility of browsing the tree of a particular commit.
| Python | apache-2.0 | PressLabs/gitfs,rowhit/gitfs,bussiere/gitfs,ksmaheshkumar/gitfs,PressLabs/gitfs | ---
+++
@@ -1,9 +1,7 @@
-from datetime import datetime
-from errno import ENOENT
+import os
from stat import S_IFDIR
-from pygit2 import GIT_SORT_TIME
+from pygit2 import GIT_FILEMODE_TREE
-from gitfs import FuseOSError
from log import log
from .view import View
@@ -34,6 +32,22 @@
log.info('%s %s', path, amode)
return 0
+ def _get_commit_subtree(self, tree, subtree_name):
+ for e in tree:
+ if e.filemode == GIT_FILEMODE_TREE:
+ if e.name == subtree_name:
+ return self.repo[e.id]
+ else:
+ return self._get_commit_subtree(self.repo[e.id],
+ subtree_name)
+
def readdir(self, path, fh):
- return ['.', '..', 'gigi are mere']
-
+ dir_entries = ['.', '..']
+ commit = self.repo.revparse_single(self.commit_sha1)
+ if getattr(self, 'relative_path'):
+ tree_name = os.path.split(self.relative_path)[1]
+ subtree = self._get_commit_subtree(commit.tree, tree_name)
+ [dir_entries.append(entry.name) for entry in subtree]
+ else:
+ [dir_entries.append(entry.name) for entry in commit.tree]
+ return dir_entries |
84bada1b92e18dad8499964ddf8a4f8120a9cc9e | vsut/case.py | vsut/case.py | class TestCase:
def assertEqual(value, expected):
if value != expected:
raise CaseFailed("{0} != {1}")
def assertTrue(value):
assertEqual(value, True)
def assertFalse(value):
assertEqual(value, False)
class CaseFailed(Exception):
def __init__(self, message):
self.message = message
def __str__(self):
return message
| class TestCase:
def assertEqual(self, value, expected):
if value != expected:
raise CaseFailed("{0} != {1}".format(value, expected))
def assertTrue(self, value):
assertEqual(value, True)
def assertFalse(self, value):
assertEqual(value, False)
class CaseFailed(Exception):
def __init__(self, message):
self.message = message
def __str__(self):
return self.message
| Fix missing self in class methods and wrong formatting | Fix missing self in class methods and wrong formatting
| Python | mit | zillolo/vsut-python | ---
+++
@@ -1,13 +1,13 @@
class TestCase:
- def assertEqual(value, expected):
+ def assertEqual(self, value, expected):
if value != expected:
- raise CaseFailed("{0} != {1}")
+ raise CaseFailed("{0} != {1}".format(value, expected))
- def assertTrue(value):
+ def assertTrue(self, value):
assertEqual(value, True)
- def assertFalse(value):
+ def assertFalse(self, value):
assertEqual(value, False)
class CaseFailed(Exception):
@@ -16,4 +16,4 @@
self.message = message
def __str__(self):
- return message
+ return self.message |
16767206ba1a40dbe217ec9e16b052c848f84b10 | converter.py | converter.py | from pydub import AudioSegment
from io import BytesIO
def convert_to_ogg(f):
bio = BytesIO()
AudioSegment.from_file(f).export(bio, format='ogg')
bio.seek(0)
return bio
| from pydub import AudioSegment
from io import BytesIO
def convert_to_ogg(f):
bio = BytesIO()
AudioSegment.from_file(f).export(bio, format='ogg', codec='libopus')
bio.seek(0)
return bio
| Use libopus codec while converting to Voice | Use libopus codec while converting to Voice
| Python | mit | MelomanCool/telegram-audiomemes | ---
+++
@@ -5,7 +5,7 @@
def convert_to_ogg(f):
bio = BytesIO()
- AudioSegment.from_file(f).export(bio, format='ogg')
+ AudioSegment.from_file(f).export(bio, format='ogg', codec='libopus')
bio.seek(0)
return bio |
2d8d540e10f2bdcd4f8b3cbb5d6e378b8c2c6b44 | speedtest-charts.py | speedtest-charts.py | #!/usr/bin/env python3
import os
import subprocess
import re
import datetime
import pygsheets
import speedtest
# Set constants
DATE = datetime.datetime.now().strftime("%d-%m-%y %H:%M:%S")
def get_credentials():
"""Function to check for valid OAuth access tokens."""
gc = pygsheets.authorize(outh_file="credentials.json")
return gc
def submit_into_spreadsheet(download, upload, ping):
"""Function to submit speedtest result."""
gc = get_credentials()
speedtest = gc.open(os.getenv('SPREADSHEET', 'Speedtest'))
sheet = speedtest.sheet1
data = [DATE, download, upload, ping]
sheet.append_table(values=data)
def main():
# Check for proper credentials
print("Checking OAuth validity...")
credentials = get_credentials()
# Run speedtest and store output
print("Starting speed test...")
spdtest = speedtest.Speedtest()
spdtest.get_best_server()
download = round(spdtest.download() / 1024 / 1024, 2)
upload = round(spdtest.upload() / 1024 / 1024, 2)
ping = round(spdtest.results.ping)
print("Starting speed finished (Download: ", download, ", Upload: ", upload, ", Ping: ", ping, ")")
# Write to spreadsheet
print("Writing to spreadsheet...")
submit_into_spreadsheet(download, upload, ping)
print("Successfuly written to spreadsheet!")
if __name__ == "__main__":
main()
| #!/usr/bin/env python3
import os
import subprocess
import re
import datetime
import pygsheets
import speedtest
# Set constants
DATE = datetime.datetime.now().strftime("%d-%m-%y %H:%M:%S")
def get_credentials():
"""Function to check for valid OAuth access tokens."""
gc = pygsheets.authorize(outh_file="credentials.json")
return gc
def submit_into_spreadsheet(download, upload, ping):
"""Function to submit speedtest result."""
gc = get_credentials()
speedtest = gc.open(os.getenv('SPREADSHEET', 'Speedtest'))
sheet = speedtest.sheet1
data = [DATE, download, upload, ping]
sheet.append_table(values=data)
def main():
# Check for proper credentials
print("Checking OAuth validity...")
credentials = get_credentials()
# Run speedtest and store output
print("Starting speed test...")
spdtest = speedtest.Speedtest()
spdtest.get_best_server()
download = round(spdtest.download() / 1000 / 1000, 2)
upload = round(spdtest.upload() / 1000 / 1000, 2)
ping = round(spdtest.results.ping)
print("Starting speed finished (Download: ", download, ", Upload: ", upload, ", Ping: ", ping, ")")
# Write to spreadsheet
print("Writing to spreadsheet...")
submit_into_spreadsheet(download, upload, ping)
print("Successfuly written to spreadsheet!")
if __name__ == "__main__":
main()
| Fix division for bits (not bytes) | Fix division for bits (not bytes)
| Python | mit | frdmn/google-speedtest-chart | ---
+++
@@ -36,8 +36,8 @@
spdtest = speedtest.Speedtest()
spdtest.get_best_server()
- download = round(spdtest.download() / 1024 / 1024, 2)
- upload = round(spdtest.upload() / 1024 / 1024, 2)
+ download = round(spdtest.download() / 1000 / 1000, 2)
+ upload = round(spdtest.upload() / 1000 / 1000, 2)
ping = round(spdtest.results.ping)
print("Starting speed finished (Download: ", download, ", Upload: ", upload, ", Ping: ", ping, ")") |
85be5c1e0510d928f8b5a9a3de77ce674bf38dc4 | datafilters/extra_lookup.py | datafilters/extra_lookup.py |
class Extra(object):
def __init__(self, where=None, tables=None):
self.where = where if where is not None else []
self.tables = tables if tables is not None else []
def is_empty(self):
return self.where or self.tables
def add(self, extra):
self.where.extend(extra.where)
self.tables.extend(extra.tables)
return self
def as_kwargs(self):
return {
'where': self.where,
'tables': self.tables,
}
# little magic
__iadd__ = add
__bool__ = is_empty
| class Extra(object):
def __init__(self, where=None, tables=None):
self.where = where if where is not None else []
self.tables = tables if tables is not None else []
def is_empty(self):
return self.where or self.tables
def add(self, extra):
self.where.extend(extra.where)
self.tables.extend(extra.tables)
return self
def as_kwargs(self):
return {
'where': self.where,
'tables': self.tables,
}
# little magic
__iadd__ = add
__bool__ = __nonzero__ = is_empty
| Add a magic member __nonzero__ to Extra | Add a magic member __nonzero__ to Extra
| Python | mit | zorainc/django-datafilters,freevoid/django-datafilters,zorainc/django-datafilters | ---
+++
@@ -1,4 +1,3 @@
-
class Extra(object):
def __init__(self, where=None, tables=None):
@@ -21,4 +20,4 @@
# little magic
__iadd__ = add
- __bool__ = is_empty
+ __bool__ = __nonzero__ = is_empty |
f359aa0eef680a3cc11cacaac4b20ade29594bcd | slave/skia_slave_scripts/flavor_utils/xsan_build_step_utils.py | slave/skia_slave_scripts/flavor_utils/xsan_build_step_utils.py | #!/usr/bin/env python
# Copyright (c) 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
""" Utilities for ASAN,TSAN,etc. build steps. """
from default_build_step_utils import DefaultBuildStepUtils
from utils import shell_utils
import os
LLVM_PATH = '/home/chrome-bot/llvm-3.4/Release+Asserts/bin/'
class XsanBuildStepUtils(DefaultBuildStepUtils):
def Compile(self, target):
# Run the xsan_build script.
os.environ['PATH'] = LLVM_PATH + ':' + os.environ['PATH']
shell_utils.run(['which', 'clang'])
shell_utils.run(['clang', '--version'])
os.environ['GYP_DEFINES'] = self._step.args['gyp_defines']
print 'GYP_DEFINES="%s"' % os.environ['GYP_DEFINES']
cmd = [
os.path.join('tools', 'xsan_build'),
self._step.args['sanitizer'],
target,
'BUILDTYPE=%s' % self._step.configuration,
]
cmd.extend(self._step.default_make_flags)
cmd.extend(self._step.make_flags)
shell_utils.run(cmd)
def RunFlavoredCmd(self, app, args):
os.environ['TSAN_OPTIONS'] = 'suppressions=tools/tsan.supp'
return shell_utils.run([self._PathToBinary(app)] + args)
| #!/usr/bin/env python
# Copyright (c) 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
""" Utilities for ASAN,TSAN,etc. build steps. """
from default_build_step_utils import DefaultBuildStepUtils
from utils import shell_utils
import os
class XsanBuildStepUtils(DefaultBuildStepUtils):
def Compile(self, target):
# Run the xsan_build script.
os.environ['GYP_DEFINES'] = self._step.args['gyp_defines']
print 'GYP_DEFINES="%s"' % os.environ['GYP_DEFINES']
cmd = [
os.path.join('tools', 'xsan_build'),
self._step.args['sanitizer'],
target,
'BUILDTYPE=%s' % self._step.configuration,
]
cmd.extend(self._step.default_make_flags)
cmd.extend(self._step.make_flags)
shell_utils.run(cmd)
def RunFlavoredCmd(self, app, args):
# New versions of ASAN run LSAN by default. We're not yet clean for that.
os.environ['ASAN_OPTIONS'] = 'detect_leaks=0'
# Point TSAN at our suppressions file.
os.environ['TSAN_OPTIONS'] = 'suppressions=tools/tsan.supp'
return shell_utils.run([self._PathToBinary(app)] + args)
| Update xsan flavor now that they're running on GCE bots. | Update xsan flavor now that they're running on GCE bots.
- Don't add ~/llvm-3.4 to PATH: we've installed Clang 3.4 systemwide.
- Don't `which clang` or `clang --version`: tools/xsan_build does it anyway.
- Explicitly disable LSAN. Clang 3.5 seems to enable this by default.
Going to submit this before review for the LSAN change, to shut up
failures like this one:
http://108.170.220.120:10117/builders/Test-Ubuntu13.10-GCE-NoGPU-x86_64-Debug-ASAN/builds/1424/steps/RunTests/logs/stdio
BUG=skia:
R=borenet@google.com, mtklein@google.com
Author: mtklein@chromium.org
Review URL: https://codereview.chromium.org/312263003
| Python | bsd-3-clause | Tiger66639/skia-buildbot,google/skia-buildbot,google/skia-buildbot,Tiger66639/skia-buildbot,Tiger66639/skia-buildbot,google/skia-buildbot,google/skia-buildbot,Tiger66639/skia-buildbot,google/skia-buildbot,google/skia-buildbot,Tiger66639/skia-buildbot,Tiger66639/skia-buildbot,google/skia-buildbot,Tiger66639/skia-buildbot,google/skia-buildbot | ---
+++
@@ -10,14 +10,9 @@
import os
-LLVM_PATH = '/home/chrome-bot/llvm-3.4/Release+Asserts/bin/'
-
class XsanBuildStepUtils(DefaultBuildStepUtils):
def Compile(self, target):
# Run the xsan_build script.
- os.environ['PATH'] = LLVM_PATH + ':' + os.environ['PATH']
- shell_utils.run(['which', 'clang'])
- shell_utils.run(['clang', '--version'])
os.environ['GYP_DEFINES'] = self._step.args['gyp_defines']
print 'GYP_DEFINES="%s"' % os.environ['GYP_DEFINES']
cmd = [
@@ -32,5 +27,8 @@
shell_utils.run(cmd)
def RunFlavoredCmd(self, app, args):
+ # New versions of ASAN run LSAN by default. We're not yet clean for that.
+ os.environ['ASAN_OPTIONS'] = 'detect_leaks=0'
+ # Point TSAN at our suppressions file.
os.environ['TSAN_OPTIONS'] = 'suppressions=tools/tsan.supp'
return shell_utils.run([self._PathToBinary(app)] + args) |
4e7c71304710178dbd668073ecfca59e8da459df | tacker/db/models_v1.py | tacker/db/models_v1.py | # Copyright (c) 2012 OpenStack Foundation.
# 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 sqlalchemy as sa
from tacker.openstack.common import uuidutils
class HasTenant(object):
"""Tenant mixin, add to subclasses that have a tenant."""
# NOTE(jkoelker) tenant_id is just a free form string ;(
tenant_id = sa.Column(sa.String(255))
class HasId(object):
"""id mixin, add to subclasses that have an id."""
id = sa.Column(sa.String(36),
primary_key=True,
default=uuidutils.generate_uuid)
class HasStatusDescription(object):
"""Status with description mixin."""
status = sa.Column(sa.String(16), nullable=False)
status_description = sa.Column(sa.String(255))
| # Copyright (c) 2012 OpenStack Foundation.
# 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 sqlalchemy as sa
from tacker.openstack.common import uuidutils
class HasTenant(object):
"""Tenant mixin, add to subclasses that have a tenant."""
# NOTE(jkoelker) tenant_id is just a free form string ;(
tenant_id = sa.Column(sa.String(255))
class HasId(object):
"""id mixin, add to subclasses that have an id."""
id = sa.Column(sa.String(36),
primary_key=True,
default=uuidutils.generate_uuid)
| Remove unused model class from db layer | Remove unused model class from db layer
Change-Id: I42cf91dc3132d0d0f2f509b5350958b7499c68f9
| Python | apache-2.0 | zeinsteinz/tacker,openstack/tacker,priya-pp/Tacker,trozet/tacker,stackforge/tacker,openstack/tacker,trozet/tacker,priya-pp/Tacker,openstack/tacker,stackforge/tacker,zeinsteinz/tacker | ---
+++
@@ -31,10 +31,3 @@
id = sa.Column(sa.String(36),
primary_key=True,
default=uuidutils.generate_uuid)
-
-
-class HasStatusDescription(object):
- """Status with description mixin."""
-
- status = sa.Column(sa.String(16), nullable=False)
- status_description = sa.Column(sa.String(255)) |
89bc764364137d18d825d316f5433e25cf9c4ceb | jungle/cli.py | jungle/cli.py | # -*- coding: utf-8 -*-
import click
class JungleCLI(click.MultiCommand):
"""Jangle CLI main class"""
def list_commands(self, ctx):
"""return available modules"""
return ['ec2', 'elb']
def get_command(self, ctx, name):
"""get command"""
mod = __import__('jungle.' + name, None, None, ['cli'])
return mod.cli
cli = JungleCLI(help='aws operation cli')
if __name__ == '__main__':
cli()
| # -*- coding: utf-8 -*-
import click
from jungle import __version__
class JungleCLI(click.MultiCommand):
"""Jangle CLI main class"""
def list_commands(self, ctx):
"""return available modules"""
return ['ec2', 'elb']
def get_command(self, ctx, name):
"""get command"""
mod = __import__('jungle.' + name, None, None, ['cli'])
return mod.cli
cli = JungleCLI(help="aws operation cli (v{})".format(__version__))
if __name__ == '__main__':
cli()
| Add version number to help text | Add version number to help text
| Python | mit | achiku/jungle | ---
+++
@@ -1,5 +1,7 @@
# -*- coding: utf-8 -*-
import click
+
+from jungle import __version__
class JungleCLI(click.MultiCommand):
@@ -16,7 +18,7 @@
return mod.cli
-cli = JungleCLI(help='aws operation cli')
+cli = JungleCLI(help="aws operation cli (v{})".format(__version__))
if __name__ == '__main__': |
9cafbdb268435eafffdbf15ce0d63af37ee1b0f0 | erudite/components/commands/find_owner.py | erudite/components/commands/find_owner.py | """
Command that will allow for a user to inject triples into a database.
"""
from rhobot.components.commands.base_command import BaseCommand
from rdflib.namespace import FOAF, RDF
from rhobot.namespace import RHO
from rhobot.components.storage import ResultPayload, ResultCollectionPayload
import logging
logger = logging.getLogger(__name__)
class FindOwner(BaseCommand):
def initialize_command(self):
super(FindOwner, self).initialize_command()
logger.info('Initialize Command')
self._initialize_command(identifier='find_owner', name='Find Owner',
additional_dependencies={'rho_bot_storage_client'})
def command_start(self, request, initial_session):
"""
Provide the configuration details back to the requester and end the command.
:param request:
:param initial_session:
:return:
"""
storage = self.xmpp['rho_bot_storage_client'].create_payload()
storage.add_type(FOAF.Person, RHO.Owner)
results = self.xmpp['rho_bot_storage_client'].find_nodes(storage)
initial_session['payload'] = results._populate_payload()
initial_session['next'] = None
initial_session['has_next'] = False
return initial_session
find_owner = FindOwner
| """
Command that will allow for a user to inject triples into a database.
"""
from rhobot.components.commands.base_command import BaseCommand
from rdflib.namespace import FOAF, RDF
from rhobot.namespace import RHO
from rhobot.components.storage import ResultPayload, ResultCollectionPayload
import logging
logger = logging.getLogger(__name__)
class FindOwner(BaseCommand):
def initialize_command(self):
super(FindOwner, self).initialize_command()
logger.info('Initialize Command')
self._initialize_command(identifier='find_owner', name='Find Owner',
additional_dependencies={'rho_bot_storage_client'})
def command_start(self, request, initial_session):
"""
Provide the configuration details back to the requester and end the command.
:param request:
:param initial_session:
:return:
"""
storage = self.xmpp['rho_bot_storage_client'].create_payload()
storage.add_type(FOAF.Person, RHO.Owner)
results = self.xmpp['rho_bot_storage_client'].find_nodes(storage)
initial_session['payload'] = results.populate_payload()
initial_session['next'] = None
initial_session['has_next'] = False
return initial_session
find_owner = FindOwner
| Update to new storage payload api | Update to new storage payload api
| Python | bsd-3-clause | rerobins/rho_erudite | ---
+++
@@ -31,7 +31,7 @@
results = self.xmpp['rho_bot_storage_client'].find_nodes(storage)
- initial_session['payload'] = results._populate_payload()
+ initial_session['payload'] = results.populate_payload()
initial_session['next'] = None
initial_session['has_next'] = False
|
d4f5471a7975df526751ffa5c0653e6fe058227f | trex/urls.py | trex/urls.py | # -*- coding: utf-8 -*-
#
# (c) 2014 Bjoern Ricks <bjoern.ricks@gmail.com>
#
# See LICENSE comming with the source of 'trex' for details.
#
from django.conf.urls import patterns, include, url
from django.contrib import admin
from trex.views.project import (
ProjectListCreateAPIView, ProjectDetailAPIView)
urlpatterns = patterns(
'',
url(r"^admin/", include(admin.site.urls)),
url(r"^projects/$", ProjectListCreateAPIView.as_view(),
name="project-list"),
url(r"^projects/(?P<pk>[0-9]+)/$", ProjectDetailAPIView.as_view(),
name="project-detail"),
)
| # -*- coding: utf-8 -*-
#
# (c) 2014 Bjoern Ricks <bjoern.ricks@gmail.com>
#
# See LICENSE comming with the source of 'trex' for details.
#
from django.conf.urls import patterns, include, url
from django.contrib import admin
from trex.views.project import (
ProjectListCreateAPIView, ProjectDetailAPIView, EntryDetailAPIView)
urlpatterns = patterns(
'',
url(r"^admin/", include(admin.site.urls)),
url(r"^projects/$", ProjectListCreateAPIView.as_view(),
name="project-list"),
url(r"^projects/(?P<pk>[0-9]+)/$", ProjectDetailAPIView.as_view(),
name="project-detail"),
url(r"^entries/(?P<pk>[0-9]+)/$", EntryDetailAPIView.as_view(),
name="entry-detail"),
)
| Add url mapping for EntryDetailAPIView | Add url mapping for EntryDetailAPIView
| Python | mit | bjoernricks/trex,bjoernricks/trex | ---
+++
@@ -9,7 +9,7 @@
from django.contrib import admin
from trex.views.project import (
- ProjectListCreateAPIView, ProjectDetailAPIView)
+ ProjectListCreateAPIView, ProjectDetailAPIView, EntryDetailAPIView)
urlpatterns = patterns(
@@ -19,4 +19,6 @@
name="project-list"),
url(r"^projects/(?P<pk>[0-9]+)/$", ProjectDetailAPIView.as_view(),
name="project-detail"),
+ url(r"^entries/(?P<pk>[0-9]+)/$", EntryDetailAPIView.as_view(),
+ name="entry-detail"),
) |
921977589a6837575ab7aadaa6238b20d0771ae2 | mesonbuild/dependencies/platform.py | mesonbuild/dependencies/platform.py | # Copyright 2013-2017 The Meson development team
# 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.
# This file contains the detection logic for external dependencies that are
# platform-specific (generally speaking).
from .. import mesonlib
from .base import ExternalDependency, DependencyException
class AppleFrameworks(ExternalDependency):
def __init__(self, env, kwargs):
super().__init__('appleframeworks', env, None, kwargs)
modules = kwargs.get('modules', [])
if isinstance(modules, str):
modules = [modules]
if not modules:
raise DependencyException("AppleFrameworks dependency requires at least one module.")
self.frameworks = modules
# FIXME: Use self.clib_compiler to check if the frameworks are available
for f in self.frameworks:
self.link_args += ['-framework', f]
def found(self):
return mesonlib.is_osx()
def get_version(self):
return 'unknown'
| # Copyright 2013-2017 The Meson development team
# 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.
# This file contains the detection logic for external dependencies that are
# platform-specific (generally speaking).
from .. import mesonlib
from .base import ExternalDependency, DependencyException
class AppleFrameworks(ExternalDependency):
def __init__(self, env, kwargs):
super().__init__('appleframeworks', env, None, kwargs)
modules = kwargs.get('modules', [])
if isinstance(modules, str):
modules = [modules]
if not modules:
raise DependencyException("AppleFrameworks dependency requires at least one module.")
self.frameworks = modules
# FIXME: Use self.clib_compiler to check if the frameworks are available
for f in self.frameworks:
self.link_args += ['-framework', f]
self.is_found = mesonlib.is_osx()
def get_version(self):
return 'unknown'
| Set is_found in AppleFrameworks constructor | Set is_found in AppleFrameworks constructor
Set is_found in AppleFrameworks constructor, rather than overriding the
found() method, as other superclass methods may access is_found.
| Python | apache-2.0 | QuLogic/meson,pexip/meson,QuLogic/meson,pexip/meson,QuLogic/meson,pexip/meson,becm/meson,jeandet/meson,pexip/meson,becm/meson,pexip/meson,becm/meson,jpakkane/meson,pexip/meson,jeandet/meson,mesonbuild/meson,jeandet/meson,MathieuDuponchelle/meson,mesonbuild/meson,QuLogic/meson,jeandet/meson,mesonbuild/meson,jeandet/meson,jpakkane/meson,jeandet/meson,MathieuDuponchelle/meson,becm/meson,pexip/meson,QuLogic/meson,jpakkane/meson,jeandet/meson,MathieuDuponchelle/meson,becm/meson,mesonbuild/meson,MathieuDuponchelle/meson,jpakkane/meson,MathieuDuponchelle/meson,QuLogic/meson,jpakkane/meson,jeandet/meson,MathieuDuponchelle/meson,MathieuDuponchelle/meson,QuLogic/meson,pexip/meson,pexip/meson,becm/meson,mesonbuild/meson,jpakkane/meson,QuLogic/meson,mesonbuild/meson,becm/meson,mesonbuild/meson,jeandet/meson,QuLogic/meson,jpakkane/meson,jpakkane/meson,MathieuDuponchelle/meson,jpakkane/meson,becm/meson,mesonbuild/meson,becm/meson,mesonbuild/meson,becm/meson,pexip/meson,MathieuDuponchelle/meson,mesonbuild/meson | ---
+++
@@ -33,8 +33,7 @@
for f in self.frameworks:
self.link_args += ['-framework', f]
- def found(self):
- return mesonlib.is_osx()
+ self.is_found = mesonlib.is_osx()
def get_version(self):
return 'unknown' |
c13fb7a0decf8b5beb0399523f4e9b9b7b71b361 | opps/core/tags/views.py | opps/core/tags/views.py | # -*- encoding: utf-8 -*-
from django.utils import timezone
from django.contrib.sites.models import get_current_site
from opps.views.generic.list import ListView
from opps.containers.models import Container
class TagList(ListView):
model = Container
template_name_suffix = '_tags'
def get_context_data(self, **kwargs):
context = super(TagList, self).get_context_data(**kwargs)
context['tag'] = self.kwargs['tag']
return context
def get_queryset(self):
self.site = get_current_site(self.request)
self.long_slug = self.kwargs['tag']
self.containers = self.model.objects.filter(
site_domain=self.site,
tags__icontains=self.long_slug,
date_available__lte=timezone.now(),
published=True)
return self.containers
| # -*- encoding: utf-8 -*-
from django.utils import timezone
from django.contrib.sites.models import get_current_site
from django.core.cache import cache
from django.conf import settings
from opps.views.generic.list import ListView
from opps.containers.models import Container
from .models import Tag
class TagList(ListView):
model = Container
template_name_suffix = '_tags'
def get_context_data(self, **kwargs):
context = super(TagList, self).get_context_data(**kwargs)
context['tag'] = self.kwargs['tag']
return context
def get_queryset(self):
self.site = get_current_site(self.request)
# without the long_slug, the queryset will cause an error
self.long_slug = 'tags'
self.tag = self.kwargs['tag']
cache_key = 'taglist-{}'.format(self.tag)
if cache.get(cache_key):
return cache.get(cache_key)
tags = Tag.objects.filter(slug=self.tag).values_list('name') or []
tags_names = []
if tags:
tags_names = [i[0] for i in tags]
ids = []
for tag in tags_names:
result = self.containers = self.model.objects.filter(
site_domain=self.site,
tags__contains=tag,
date_available__lte=timezone.now(),
published=True
)
if result.exists():
ids.extend([i.id for i in result])
# remove the repeated
ids = list(set(ids))
# grab the containers
self.containers = self.model.objects.filter(id__in=ids)
expires = getattr(settings, 'OPPS_CACHE_EXPIRE', 3600)
cache.set(cache_key, list(self.containers), expires)
return self.containers
| Add new approach on taglist get_queryset | Add new approach on taglist get_queryset
| Python | mit | jeanmask/opps,YACOWS/opps,opps/opps,opps/opps,jeanmask/opps,williamroot/opps,jeanmask/opps,williamroot/opps,williamroot/opps,jeanmask/opps,YACOWS/opps,opps/opps,williamroot/opps,YACOWS/opps,opps/opps,YACOWS/opps | ---
+++
@@ -1,9 +1,13 @@
# -*- encoding: utf-8 -*-
from django.utils import timezone
from django.contrib.sites.models import get_current_site
+from django.core.cache import cache
+from django.conf import settings
from opps.views.generic.list import ListView
from opps.containers.models import Container
+
+from .models import Tag
class TagList(ListView):
@@ -17,10 +21,35 @@
def get_queryset(self):
self.site = get_current_site(self.request)
- self.long_slug = self.kwargs['tag']
- self.containers = self.model.objects.filter(
- site_domain=self.site,
- tags__icontains=self.long_slug,
- date_available__lte=timezone.now(),
- published=True)
+ # without the long_slug, the queryset will cause an error
+ self.long_slug = 'tags'
+ self.tag = self.kwargs['tag']
+
+ cache_key = 'taglist-{}'.format(self.tag)
+ if cache.get(cache_key):
+ return cache.get(cache_key)
+
+ tags = Tag.objects.filter(slug=self.tag).values_list('name') or []
+ tags_names = []
+ if tags:
+ tags_names = [i[0] for i in tags]
+
+ ids = []
+ for tag in tags_names:
+ result = self.containers = self.model.objects.filter(
+ site_domain=self.site,
+ tags__contains=tag,
+ date_available__lte=timezone.now(),
+ published=True
+ )
+ if result.exists():
+ ids.extend([i.id for i in result])
+
+ # remove the repeated
+ ids = list(set(ids))
+
+ # grab the containers
+ self.containers = self.model.objects.filter(id__in=ids)
+ expires = getattr(settings, 'OPPS_CACHE_EXPIRE', 3600)
+ cache.set(cache_key, list(self.containers), expires)
return self.containers |
29eeb2ca5988e9a4f6d8ec2493701b278ee2b554 | backend/mcapiserver.py | backend/mcapiserver.py | #!/usr/bin/env python
from mcapi.mcapp import app, mcdb_connect
from mcapi import utils, access
from mcapi import objects, cache
from mcapi.user import account, usergroups, projects
from mcapi.globus import globus_service
from os import environ
import optparse
import signal
from mcapi import apikeydb
_HOST = environ.get('MC_SERVICE_HOST') or 'localhost'
def reload_users(signum, frame):
apikeydb.reset()
access.reset()
if __name__ == '__main__':
parser = optparse.OptionParser()
parser.add_option("-p", "--port", dest="port",
help="Port to run on", default=5000)
(options, args) = parser.parse_args()
signal.signal(signal.SIGHUP, reload_users)
conn = mcdb_connect()
# cache.load_project_tree_cache(conn)
app.run(debug=True, host=_HOST, port=int(options.port), processes=5)
| #!/usr/bin/env python
from mcapi.mcapp import app, mcdb_connect
from mcapi import utils, access
from mcapi import objects, cache
from mcapi.user import account, usergroups, projects
from os import environ
import optparse
import signal
from mcapi import apikeydb
_HOST = environ.get('MC_SERVICE_HOST') or 'localhost'
def reload_users(signum, frame):
apikeydb.reset()
access.reset()
if __name__ == '__main__':
parser = optparse.OptionParser()
parser.add_option("-p", "--port", dest="port",
help="Port to run on", default=5000)
(options, args) = parser.parse_args()
signal.signal(signal.SIGHUP, reload_users)
conn = mcdb_connect()
# cache.load_project_tree_cache(conn)
app.run(debug=True, host=_HOST, port=int(options.port), processes=5)
| Remove globus interface from mcapi - now in its own server | Remove globus interface from mcapi - now in its own server
| Python | mit | materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org | ---
+++
@@ -4,7 +4,6 @@
from mcapi import utils, access
from mcapi import objects, cache
from mcapi.user import account, usergroups, projects
-from mcapi.globus import globus_service
from os import environ
import optparse
import signal |
1c3eadcbc378ae528f3a4cbf82d41675343ac104 | badgus/base/helpers.py | badgus/base/helpers.py | from jingo import register
import jinja2
# TODO: Allow configurable whitelists
ALLOWED_TAGS = [
'a', 'abbr', 'br', 'acronym', 'b', 'blockquote', 'code', 'em', 'i', 'li',
'ol', 'p', 'strong', 'ul'
]
@register.filter
def bleach_markup(val):
"""Template filter to linkify and clean content expected to allow HTML"""
try:
import bleach
val = val.replace('\n', '<br />')
val = bleach.linkify(val)
val = bleach.clean(val, tags=ALLOWED_TAGS)
return jinja2.Markup(val)
except ImportError:
return val
| from jingo import register
import jinja2
# TODO: Allow configurable whitelists
ALLOWED_TAGS = [
'a', 'abbr', 'br', 'acronym', 'b', 'blockquote', 'code', 'em', 'i', 'img', 'li',
'ol', 'p', 'strong', 'ul'
]
ALLOWED_ATTRIBUTES = {
"img": ["src"]
}
@register.filter
def bleach_markup(val):
"""Template filter to linkify and clean content expected to allow HTML"""
try:
import bleach
val = val.replace('\n', '<br />')
val = bleach.linkify(val)
val = bleach.clean(val,
tags=ALLOWED_TAGS,
attributes=ALLOWED_ATTRIBUTES)
return jinja2.Markup(val)
except ImportError:
return val
| Allow images in limited markup for descriptions | Allow images in limited markup for descriptions
| Python | bsd-3-clause | lmorchard/badg.us,lmorchard/badg.us,deepankverma/badges.mozilla.org,mozilla/badges.mozilla.org,lmorchard/badg.us,mozilla/badg.us,mozilla/badg.us,deepankverma/badges.mozilla.org,deepankverma/badges.mozilla.org,mozilla/badg.us,mozilla/badges.mozilla.org,mozilla/badges.mozilla.org,mozilla/badges.mozilla.org,lmorchard/badg.us,deepankverma/badges.mozilla.org | ---
+++
@@ -4,10 +4,13 @@
# TODO: Allow configurable whitelists
ALLOWED_TAGS = [
- 'a', 'abbr', 'br', 'acronym', 'b', 'blockquote', 'code', 'em', 'i', 'li',
+ 'a', 'abbr', 'br', 'acronym', 'b', 'blockquote', 'code', 'em', 'i', 'img', 'li',
'ol', 'p', 'strong', 'ul'
]
+ALLOWED_ATTRIBUTES = {
+ "img": ["src"]
+}
@register.filter
def bleach_markup(val):
@@ -16,7 +19,9 @@
import bleach
val = val.replace('\n', '<br />')
val = bleach.linkify(val)
- val = bleach.clean(val, tags=ALLOWED_TAGS)
+ val = bleach.clean(val,
+ tags=ALLOWED_TAGS,
+ attributes=ALLOWED_ATTRIBUTES)
return jinja2.Markup(val)
except ImportError:
return val |
e7ccf47114bbae254f40029b9188eacc6d1c5465 | IPython/html/widgets/__init__.py | IPython/html/widgets/__init__.py | from .widget import Widget, DOMWidget, CallbackDispatcher, register
from .widget_bool import Checkbox, ToggleButton
from .widget_button import Button
from .widget_box import Box, Popup, FlexBox, HBox, VBox
from .widget_float import FloatText, BoundedFloatText, FloatSlider, FloatProgress, FloatRangeSlider
from .widget_image import Image
from .widget_int import IntText, BoundedIntText, IntSlider, IntProgress, IntRangeSlider
from .widget_output import Output
from .widget_selection import RadioButtons, ToggleButtons, Dropdown, Select
from .widget_selectioncontainer import Tab, Accordion
from .widget_string import HTML, Latex, Text, Textarea
from .interaction import interact, interactive, fixed, interact_manual
# Deprecated classes
from .widget_bool import CheckboxWidget, ToggleButtonWidget
from .widget_button import ButtonWidget
from .widget_box import ContainerWidget, PopupWidget
from .widget_float import FloatTextWidget, BoundedFloatTextWidget, FloatSliderWidget, FloatProgressWidget
from .widget_image import ImageWidget
from .widget_int import IntTextWidget, BoundedIntTextWidget, IntSliderWidget, IntProgressWidget
from .widget_selection import RadioButtonsWidget, ToggleButtonsWidget, DropdownWidget, SelectWidget
from .widget_selectioncontainer import TabWidget, AccordionWidget
from .widget_string import HTMLWidget, LatexWidget, TextWidget, TextareaWidget
| from .widget import Widget, DOMWidget, CallbackDispatcher, register
from .widget_bool import Checkbox, ToggleButton
from .widget_button import Button
from .widget_box import Box, Popup, FlexBox, HBox, VBox
from .widget_float import FloatText, BoundedFloatText, FloatSlider, FloatProgress, FloatRangeSlider
from .widget_image import Image
from .widget_int import IntText, BoundedIntText, IntSlider, IntProgress, IntRangeSlider
from .widget_output import Output
from .widget_selection import RadioButtons, ToggleButtons, Dropdown, Select
from .widget_selectioncontainer import Tab, Accordion
from .widget_string import HTML, Latex, Text, Textarea
from .interaction import interact, interactive, fixed, interact_manual
# Deprecated classes
from .widget_bool import CheckboxWidget, ToggleButtonWidget
from .widget_button import ButtonWidget
from .widget_box import ContainerWidget, PopupWidget
from .widget_float import FloatTextWidget, BoundedFloatTextWidget, FloatSliderWidget, FloatProgressWidget
from .widget_image import ImageWidget
from .widget_int import IntTextWidget, BoundedIntTextWidget, IntSliderWidget, IntProgressWidget
from .widget_selection import RadioButtonsWidget, ToggleButtonsWidget, DropdownWidget, SelectWidget
from .widget_selectioncontainer import TabWidget, AccordionWidget
from .widget_string import HTMLWidget, LatexWidget, TextWidget, TextareaWidget
# Warn on import
from IPython.utils.warn import warn
warn("""The widget API is still considered experimental and
may change by the next major release of IPython.""")
| Add warning to widget namespace import. | Add warning to widget namespace import.
| Python | bsd-3-clause | ipython/ipython,ipython/ipython | ---
+++
@@ -22,3 +22,8 @@
from .widget_selection import RadioButtonsWidget, ToggleButtonsWidget, DropdownWidget, SelectWidget
from .widget_selectioncontainer import TabWidget, AccordionWidget
from .widget_string import HTMLWidget, LatexWidget, TextWidget, TextareaWidget
+
+# Warn on import
+from IPython.utils.warn import warn
+warn("""The widget API is still considered experimental and
+ may change by the next major release of IPython.""") |
8e051959bc69305cb4987a913a2b0bd845a9fa70 | plugins/ball8.py | plugins/ball8.py | import random
from plugin import CommandPlugin, PluginException
class Ball8(CommandPlugin):
"""
8ball command (by javipepe :))
"""
def __init__(self, bot):
CommandPlugin.__init__(self, bot)
self.triggers = ['8ball']
self.short_help = 'Ask me a question'
self.help = 'Ask me a question, I\'ll decide what the answer should be. Based on https://en.wikipedia.org/wiki/Magic_8-Ball'
self.help_example = ['!8ball Is linux better than windows?']
# ^ obviously yes.
def on_command(self, event, response):
args = event['text']
if not args or not args[-1:].__contains__('?'):
raise PluginException('Invalid argument! Ask me a question!')
else:
possible_answers = ['It is certain', 'It is decidedly so', 'Without a doubt', 'Yes, definitely', 'You may rely on it', 'As I see it, yes', 'Most likely', 'Outlook good', 'Yes', 'Signs point to yes', 'Reply hazy try again', 'Ask again later', 'Better not tell you now', 'Cannot predict now', 'Concentrate and ask again', 'Do\'t count on it', 'My reply is no', 'My sources say no', 'Outlook not so good', 'Very doubtful']
response['text'] = ':8ball: says *_%s_*!' % random.choice(possible_answers)
self.bot.sc.api_call('chat.postMessage', **response)
| import random
from plugin import CommandPlugin, PluginException
class Ball8(CommandPlugin):
"""
8ball command (by javipepe :))
"""
def __init__(self, bot):
CommandPlugin.__init__(self, bot)
self.triggers = ['8ball']
self.short_help = 'Ask me a question'
self.help = 'Ask me a question, I\'ll decide what the answer should be. Based on https://en.wikipedia.org/wiki/Magic_8-Ball'
self.help_example = ['!8ball Is linux better than windows?']
# ^ obviously yes.
def on_command(self, event, response):
args = event['text']
if not args or not args[-1:].__contains__('?'):
raise PluginException('Invalid argument! Ask me a question!')
else:
possible_answers = ['It is certain', 'It is decidedly so', 'Without a doubt', 'Yes, definitely', 'You may rely on it', 'As I see it, yes', 'Most likely', 'Outlook good', 'Yes', 'Signs point to yes', 'Reply hazy try again', 'Ask again later', 'Better not tell you now', 'Cannot predict now', 'Concentrate and ask again', 'Don\'t count on it', 'My reply is no', 'My sources say no', 'Outlook not so good', 'Very doubtful']
response['text'] = ':8ball: says *_%s_*!' % random.choice(possible_answers)
self.bot.sc.api_call('chat.postMessage', **response)
| Fix typo in 8ball response | Fix typo in 8ball response
| Python | mit | Brottweiler/nimbus,itsmartin/nimbus,bcbwilla/nimbus,Plastix/nimbus | ---
+++
@@ -20,7 +20,7 @@
if not args or not args[-1:].__contains__('?'):
raise PluginException('Invalid argument! Ask me a question!')
else:
- possible_answers = ['It is certain', 'It is decidedly so', 'Without a doubt', 'Yes, definitely', 'You may rely on it', 'As I see it, yes', 'Most likely', 'Outlook good', 'Yes', 'Signs point to yes', 'Reply hazy try again', 'Ask again later', 'Better not tell you now', 'Cannot predict now', 'Concentrate and ask again', 'Do\'t count on it', 'My reply is no', 'My sources say no', 'Outlook not so good', 'Very doubtful']
+ possible_answers = ['It is certain', 'It is decidedly so', 'Without a doubt', 'Yes, definitely', 'You may rely on it', 'As I see it, yes', 'Most likely', 'Outlook good', 'Yes', 'Signs point to yes', 'Reply hazy try again', 'Ask again later', 'Better not tell you now', 'Cannot predict now', 'Concentrate and ask again', 'Don\'t count on it', 'My reply is no', 'My sources say no', 'Outlook not so good', 'Very doubtful']
response['text'] = ':8ball: says *_%s_*!' % random.choice(possible_answers)
self.bot.sc.api_call('chat.postMessage', **response) |
e90e4fe8ad2679ff978d4d8b69ea2b9402029ccd | pinax/apps/account/context_processors.py | pinax/apps/account/context_processors.py |
from account.models import Account, AnonymousAccount
def openid(request):
return {'openid': request.openid}
def account(request):
if request.user.is_authenticated():
try:
account = Account._default_manager.get(user=request.user)
except Account.DoesNotExist:
account = AnonymousAccount(request)
else:
account = AnonymousAccount(request)
return {'account': account}
|
from account.models import Account, AnonymousAccount
def openid(request):
if hasattr(request, "openid"):
openid = request.openid
else:
openid = None
return {
"openid": openid,
}
def account(request):
if request.user.is_authenticated():
try:
account = Account._default_manager.get(user=request.user)
except Account.DoesNotExist:
account = AnonymousAccount(request)
else:
account = AnonymousAccount(request)
return {'account': account}
| Handle no openid attribute on request in openid context processor | Handle no openid attribute on request in openid context processor
| Python | mit | amarandon/pinax,alex/pinax,amarandon/pinax,amarandon/pinax,alex/pinax,amarandon/pinax,alex/pinax | ---
+++
@@ -2,7 +2,14 @@
from account.models import Account, AnonymousAccount
def openid(request):
- return {'openid': request.openid}
+ if hasattr(request, "openid"):
+ openid = request.openid
+ else:
+ openid = None
+ return {
+ "openid": openid,
+ }
+
def account(request):
if request.user.is_authenticated(): |
207c3fc8467c7f216e06b88f87433dc4eb46e13c | tests/name_injection_test.py | tests/name_injection_test.py | """Test for the name inject utility."""
from drudge import Drudge
def test_drudge_injects_names():
"""Test the name injection method of drudge."""
dr = Drudge(None) # Dummy drudge.
string_name = 'string_name'
dr.set_name(string_name)
dr.set_name(1, 'one')
dr.inject_names(suffix='_')
assert string_name_ == string_name
assert one_ == 1
| """Test for the name inject utility."""
import types
from drudge import Drudge
def test_drudge_injects_names():
"""Test the name injection method of drudge."""
# Dummy drudge.
dr = Drudge(types.SimpleNamespace(defaultParallelism=1))
string_name = 'string_name'
dr.set_name(string_name)
dr.set_name(1, 'one')
dr.inject_names(suffix='_')
assert string_name_ == string_name
assert one_ == 1
| Fix name injection test for the new Drudge update | Fix name injection test for the new Drudge update
| Python | mit | tschijnmo/drudge,tschijnmo/drudge,tschijnmo/drudge | ---
+++
@@ -1,4 +1,6 @@
"""Test for the name inject utility."""
+
+import types
from drudge import Drudge
@@ -6,7 +8,9 @@
def test_drudge_injects_names():
"""Test the name injection method of drudge."""
- dr = Drudge(None) # Dummy drudge.
+ # Dummy drudge.
+ dr = Drudge(types.SimpleNamespace(defaultParallelism=1))
+
string_name = 'string_name'
dr.set_name(string_name)
dr.set_name(1, 'one') |
27ab5b022dec68f18d07988b97d65ec8fd8db83e | zenaida/contrib/hints/views.py | zenaida/contrib/hints/views.py | from zenaida.contrib.hints.models import Dismissed
from zenaida.contrib.hints.forms import DismissHintForm
from django.http import (HttpResponse, HttpResponseNotAllowed,
HttpResponseBadRequest, HttpResponseRedirect)
def dismiss(request):
if not request.POST:
return HttpResponseNotAllowed(['POST'])
else:
form = DismissHintForm(request.POST)
dismissed = form.save(commit=False)
dismissed.user = request.user
dismissed.save()
if 'next' in request.GET:
next_url = request.GET['next']
else:
next_url = request.META['HTTP_REFERER']
return HttpResponseRedirect(next_url)
| from zenaida.contrib.hints.models import Dismissed
from zenaida.contrib.hints.forms import DismissHintForm
from django.core.exceptions import SuspiciousOperation
from django.http import (HttpResponse, HttpResponseNotAllowed,
HttpResponseBadRequest, HttpResponseRedirect)
from django.utils.http import is_safe_url
def dismiss(request):
if not request.POST:
return HttpResponseNotAllowed(['POST'])
else:
form = DismissHintForm(request.POST)
dismissed = form.save(commit=False)
dismissed.user = request.user
dismissed.save()
if 'next' in request.GET:
next_url = request.GET['next']
else:
next_url = request.META['HTTP_REFERER']
if not is_safe_url(next_url, host=request.get_host()):
raise SuspiciousOperation("Url {} is not safe to redirect to.".format(next_url))
return HttpResponseRedirect(next_url)
| Check url safety before redirecting. Safety first! | [hints] Check url safety before redirecting. Safety first!
| Python | bsd-3-clause | littleweaver/django-zenaida,littleweaver/django-zenaida,littleweaver/django-zenaida,littleweaver/django-zenaida | ---
+++
@@ -1,8 +1,11 @@
from zenaida.contrib.hints.models import Dismissed
from zenaida.contrib.hints.forms import DismissHintForm
+from django.core.exceptions import SuspiciousOperation
from django.http import (HttpResponse, HttpResponseNotAllowed,
HttpResponseBadRequest, HttpResponseRedirect)
+from django.utils.http import is_safe_url
+
def dismiss(request):
if not request.POST:
@@ -16,4 +19,8 @@
next_url = request.GET['next']
else:
next_url = request.META['HTTP_REFERER']
+
+ if not is_safe_url(next_url, host=request.get_host()):
+ raise SuspiciousOperation("Url {} is not safe to redirect to.".format(next_url))
+
return HttpResponseRedirect(next_url) |
d73654fd4d11a2bf5730c6fbf4bc2167593f7cc4 | queue_timings.py | queue_timings.py | # queue_timings.py
# Analysis script for bodyfetcher queue timings. Call from the command line using Python 3.
import os.path
import platform
if int(platform.python_version_tuple()[0]) == 2:
import cPickle as pickle
elif int(platform.python_version_tuple()[0]) == 3:
import pickle
else:
raise EnvironmentError("Invalid or Incompatible Python Version: %s" % platform.python_version())
def main():
if os.path.isfile("bodyfetcherQueueTimings.p"):
try:
with open("bodyfetcherQueueTimings.p", "rb") as f:
queue_data = pickle.load(f)
except EOFError:
print("Hit EOFError while reading file. Smokey handles this by deleting the file.")
resp = input("Delete? (y/n)").lower()
if resp == "y":
os.remove("bodyfetcherQueueTimings.p")
return # If we don't return, we run into an error in the for loop below.
for site, times in queue_data.iteritems():
print("{0}: min {1}, max {2}, avg {3}".format(site.split(".")[0], min(times), max(times),
sum(times) / len(times)))
else:
print("bodyfetcherQueueTimings.p doesn't exist. No data to analyse.")
if __name__ == "__main__":
main()
| # queue_timings.py
# Analysis script for bodyfetcher queue timings. Call from the command line using Python 3.
import os.path
import cPickle as pickle
def main():
if os.path.isfile("bodyfetcherQueueTimings.p"):
try:
with open("bodyfetcherQueueTimings.p", "rb") as f:
queue_data = pickle.load(f)
except EOFError:
print("Hit EOFError while reading file. Smokey handles this by deleting the file.")
resp = input("Delete? (y/n)").lower()
if resp == "y":
os.remove("bodyfetcherQueueTimings.p")
for site, times in queue_data.iteritems():
print("{0}: min {1}, max {2}, avg {3}".format(site.split(".")[0], min(times), max(times),
sum(times) / len(times)))
else:
print("bodyfetcherQueueTimings.p doesn't exist. No data to analyse.")
if __name__ == "__main__":
main()
| Revert "Python2/3 Reverse Compat functionality, also 'return' if EOFError" | Revert "Python2/3 Reverse Compat functionality, also 'return' if EOFError"
This reverts commit f604590ca7a704ef941db5342bae3cef5c60cf2e.
| Python | apache-2.0 | Charcoal-SE/SmokeDetector,Charcoal-SE/SmokeDetector | ---
+++
@@ -2,13 +2,7 @@
# Analysis script for bodyfetcher queue timings. Call from the command line using Python 3.
import os.path
-import platform
-if int(platform.python_version_tuple()[0]) == 2:
- import cPickle as pickle
-elif int(platform.python_version_tuple()[0]) == 3:
- import pickle
-else:
- raise EnvironmentError("Invalid or Incompatible Python Version: %s" % platform.python_version())
+import cPickle as pickle
def main():
@@ -21,7 +15,6 @@
resp = input("Delete? (y/n)").lower()
if resp == "y":
os.remove("bodyfetcherQueueTimings.p")
- return # If we don't return, we run into an error in the for loop below.
for site, times in queue_data.iteritems():
print("{0}: min {1}, max {2}, avg {3}".format(site.split(".")[0], min(times), max(times), |
2faf9d30ae7eb935ace3ff9012844de1d4149f45 | capstone/rl/learner.py | capstone/rl/learner.py | import abc
import six
@six.add_metaclass(abc.ABCMeta)
class Learner(object):
def __init__(self, env, n_episodes=1000, verbose=True):
self.env = env
self.n_episodes = n_episodes
self.verbose = verbose
self.cur_episode = 1
def learn(self):
for _ in range(self.n_episodes):
if self.verbose:
print('Episode {self.cur_episode} / {self.n_episodes}'.format(self=self))
self.env.reset()
self.episode()
self.cur_episode += 1
def reset(self):
self.cur_episode = 1
@abc.abstractmethod
def episode(self):
pass
| import abc
import six
@six.add_metaclass(abc.ABCMeta)
class Learner(object):
def __init__(self, env, n_episodes=1000, verbose=True):
self.env = env
self.n_episodes = n_episodes
self.verbose = verbose
self.cur_episode = 1
def learn(self):
for _ in range(self.n_episodes):
if self.verbose:
print('Episode {self.cur_episode} / {self.n_episodes}'.format(self=self))
self.env.reset()
self.episode()
self.cur_episode += 1
def reset(self):
self.cur_episode = 1
@abc.abstractmethod
def episode(self):
pass
| Fix episode count increment bug | Fix episode count increment bug
| Python | mit | davidrobles/mlnd-capstone-code | ---
+++
@@ -17,7 +17,7 @@
print('Episode {self.cur_episode} / {self.n_episodes}'.format(self=self))
self.env.reset()
self.episode()
- self.cur_episode += 1
+ self.cur_episode += 1
def reset(self):
self.cur_episode = 1 |
8a40d0df910cf9e17db99155ba148c69737809dc | ConnorBrozic-CymonScriptA2P2.py | ConnorBrozic-CymonScriptA2P2.py | #!/usr/bin/python
#SRT411 Assignment 2 - Part 2
#Cymon API Interaction
#Written by: Connor Brozic
#Malware Domains retrieved from https://malwaredomains.usu.edu/
#Implements Cymon API Calls
#Import time for sleep function.
#Import Cymon to allow for Cymon API calls
import time
from cymon import Cymon
#Personal Key Removed. Replace 'xxx' with your own key.
api = Cymon('xxx')
#Parsing Text file retrieved from:
#http://stackoverflow.com/questions/6277107/parsing-text-file-in-python
#Open malware domain file.
f = open('text.txt','r')
#Open output file to write to
cymondata = open('cymondata.txt','w')
while True:
try:
#Read the next domain in file.
text = f.readline()
print(text)
#Lookup the domain through Cymon and print results back to output file.
cymondata.write(repr(api.domain_lookup(text)))
cymondata.write("\n")
cymondata.write("\n")
#If 404 error encountered, skip domain and move to the next one.
except Exception:
pass
time.sleep(1)
#Once finished, close the connection.
cymondata.close()
| #!/usr/bin/python
#SRT411 Assignment 2 - Part 2
#Cymon API Interaction
#Written by: Connor Brozic
#Malware Domains retrieved from https://malwaredomains.usu.edu/
#Implements Cymon API Calls
#Import time for sleep function.
#Import Cymon to allow for Cymon API calls
import time
from cymon import Cymon
#Personal Key Removed. Replace 'xxx' with your own key.
api = Cymon('xxx')
#Parsing Text file retrieved from:
#http://stackoverflow.com/questions/6277107/parsing-text-file-in-python
#Open malware domain file.
f = open('TestedMalwareDomains.txt','r')
#Open output file to write to
cymondata = open('cymondata.txt','w')
while True:
try:
#Read the next domain in file.
text = f.readline()
print(text)
#Lookup the domain through Cymon and print results back to output file.
cymondata.write(repr(api.domain_lookup(text)))
cymondata.write("\n")
cymondata.write("\n")
#If 404 error encountered, skip domain and move to the next one.
except Exception:
pass
time.sleep(1)
#Once finished, close the connection.
cymondata.close()
| Update to Script, Fixed malware domain file name | Update to Script, Fixed malware domain file name
Fixed malware domains file name to accurately represent the file opened. (Better than text.txt) | Python | mit | ConnorBrozic/SRT411-Assignment2 | ---
+++
@@ -17,7 +17,7 @@
#http://stackoverflow.com/questions/6277107/parsing-text-file-in-python
#Open malware domain file.
-f = open('text.txt','r')
+f = open('TestedMalwareDomains.txt','r')
#Open output file to write to
cymondata = open('cymondata.txt','w')
while True: |
f2012869d3e16f0a610e18021e6ec8967eddf635 | tests/sqltypes_test.py | tests/sqltypes_test.py | import enum
from sqlalchemy.schema import Column
from sqlalchemy.types import Integer
from cliche.sqltypes import EnumType
from cliche.orm import Base
class Color(enum.Enum):
red = 1
green = 2
blue = 3
class ColorTable(Base):
__tablename__ = 'color_table'
id = Column(Integer, primary_key=True)
test_col = Column(EnumType(Color))
def test_enum_type(fx_session):
red_obj = ColorTable(test_col=Color.red)
green_obj = ColorTable(test_col=Color.green)
blue_obj = ColorTable(test_col=Color.blue)
fx_session.add(red_obj)
fx_session.add(green_obj)
fx_session.add(blue_obj)
fx_session.flush()
result_obj = fx_session.query(ColorTable) \
.filter(ColorTable.test_col == Color.green) \
.one()
assert green_obj is result_obj
| import enum
from sqlalchemy.schema import Column
from sqlalchemy.types import Integer
from cliche.sqltypes import EnumType
from cliche.orm import Base
class Color(enum.Enum):
red = 1
green = 2
blue = 3
class ColorTable(Base):
__tablename__ = 'color_table'
id = Column(Integer, primary_key=True)
color = Column(EnumType(Color, name='color'))
def test_enum_type(fx_session):
red_obj = ColorTable(color=Color.red)
green_obj = ColorTable(color=Color.green)
blue_obj = ColorTable(color=Color.blue)
fx_session.add(red_obj)
fx_session.add(green_obj)
fx_session.add(blue_obj)
fx_session.flush()
result_obj = fx_session.query(ColorTable) \
.filter(ColorTable.color == Color.green) \
.one()
assert green_obj is result_obj
| Add name to EnumType in test since pgsql needs it. | Add name to EnumType in test since pgsql needs it.
| Python | mit | item4/cliche,clicheio/cliche,item4/cliche,clicheio/cliche,clicheio/cliche | ---
+++
@@ -19,18 +19,18 @@
__tablename__ = 'color_table'
id = Column(Integer, primary_key=True)
- test_col = Column(EnumType(Color))
+ color = Column(EnumType(Color, name='color'))
def test_enum_type(fx_session):
- red_obj = ColorTable(test_col=Color.red)
- green_obj = ColorTable(test_col=Color.green)
- blue_obj = ColorTable(test_col=Color.blue)
+ red_obj = ColorTable(color=Color.red)
+ green_obj = ColorTable(color=Color.green)
+ blue_obj = ColorTable(color=Color.blue)
fx_session.add(red_obj)
fx_session.add(green_obj)
fx_session.add(blue_obj)
fx_session.flush()
result_obj = fx_session.query(ColorTable) \
- .filter(ColorTable.test_col == Color.green) \
+ .filter(ColorTable.color == Color.green) \
.one()
assert green_obj is result_obj |
3471024a63f2bf55763563693f439a704291fc7d | examples/apt.py | examples/apt.py | from pyinfra import host
from pyinfra.modules import apt
SUDO = True
code_name = host.fact.linux_distribution['release_meta'].get('DISTRIB_CODENAME')
print(host.fact.linux_name, code_name)
if host.fact.linux_name in ['Debian', 'Ubuntu']:
apt.packages(
{'Install some packages'},
['vim-addon-manager', 'vim', 'software-properties-common', 'wget', 'curl'],
update=True,
)
apt.ppa(
{'Add the Bitcoin ppa'},
'ppa:bitcoin/bitcoin',
)
# typically after adding a ppk, you want to update
apt.update()
# but you could just include the update in the apt install step
# like this:
apt.packages(
{'Install Bitcoin'},
'bitcoin-qt',
update=True,
)
apt.deb(
{'Install Chrome via deb'},
'https://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb',
)
apt.key(
{'Install VirtualBox key'},
'https://www.virtualbox.org/download/oracle_vbox_2016.asc',
)
apt.repo(
{'Install VirtualBox repo'},
'deb https://download.virtualbox.org/virtualbox/debian {} contrib'.format(code_name),
)
| from pyinfra import host
from pyinfra.modules import apt
SUDO = True
code_name = host.fact.linux_distribution['release_meta'].get('DISTRIB_CODENAME')
print(host.fact.linux_name, code_name)
if host.fact.linux_name in ['Debian', 'Ubuntu']:
apt.packages(
{'Install some packages'},
['vim-addon-manager', 'vim', 'software-properties-common', 'wget', 'curl'],
update=True,
)
# NOTE: the bitcoin PPA is no longer supported
# apt.ppa(
# {'Add the Bitcoin ppa'},
# 'ppa:bitcoin/bitcoin',
# )
#
# apt.packages(
# {'Install Bitcoin'},
# 'bitcoin-qt',
# update=True,
# )
apt.deb(
{'Install Chrome via deb'},
'https://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb',
)
apt.key(
{'Install VirtualBox key'},
'https://www.virtualbox.org/download/oracle_vbox_2016.asc',
)
apt.repo(
{'Install VirtualBox repo'},
'deb https://download.virtualbox.org/virtualbox/debian {} contrib'.format(code_name),
)
| Comment out the bitcoin PPA code. | Comment out the bitcoin PPA code.
The bitcoin PPA is no longer maintained/supported.
| Python | mit | Fizzadar/pyinfra,Fizzadar/pyinfra | ---
+++
@@ -14,21 +14,17 @@
update=True,
)
- apt.ppa(
- {'Add the Bitcoin ppa'},
- 'ppa:bitcoin/bitcoin',
- )
-
- # typically after adding a ppk, you want to update
- apt.update()
-
- # but you could just include the update in the apt install step
- # like this:
- apt.packages(
- {'Install Bitcoin'},
- 'bitcoin-qt',
- update=True,
- )
+ # NOTE: the bitcoin PPA is no longer supported
+ # apt.ppa(
+ # {'Add the Bitcoin ppa'},
+ # 'ppa:bitcoin/bitcoin',
+ # )
+ #
+ # apt.packages(
+ # {'Install Bitcoin'},
+ # 'bitcoin-qt',
+ # update=True,
+ # )
apt.deb(
{'Install Chrome via deb'}, |
d20039737d1e25f4462c4865347fa22411045677 | budgetsupervisor/users/models.py | budgetsupervisor/users/models.py | from django.db import models
from django.contrib.auth.models import AbstractUser
from django.conf import settings
from django.db.models.signals import post_save
from saltedge.factory import get_saltedge_app
class User(AbstractUser):
pass
class ProfileManager(models.Manager):
def create_in_saltedge(self, profile):
app = get_saltedge_app()
url = "https://www.saltedge.com/api/v5/customers"
payload = json.dumps({"data": {"identifier": profile.user.id}})
response = app.post(url, payload)
data = response.json()
profile.external_id = data["data"]["id"]
profile.save()
class Profile(models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
external_id = models.BigIntegerField(blank=True, null=True)
objects = ProfileManager()
def __str__(self):
return str(self.user)
def create_user_profile(sender, instance, created, **kwargs):
if created:
Profile.objects.create(user=instance)
post_save.connect(create_user_profile, sender=settings.AUTH_USER_MODEL)
| from django.db import models
from django.contrib.auth.models import AbstractUser
from django.conf import settings
from django.db.models.signals import post_save
from saltedge.factory import get_saltedge_app
class User(AbstractUser):
pass
class ProfileManager(models.Manager):
def create_in_saltedge(self, profile):
app = get_saltedge_app()
url = "https://www.saltedge.com/api/v5/customers"
payload = json.dumps({"data": {"identifier": profile.user.id}})
response = app.post(url, payload)
data = response.json()
profile.external_id = data["data"]["id"]
profile.save()
def remove_from_saltedge(self, profile):
pass
class Profile(models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
external_id = models.BigIntegerField(blank=True, null=True)
objects = ProfileManager()
def __str__(self):
return str(self.user)
def create_user_profile(sender, instance, created, **kwargs):
if created:
Profile.objects.create(user=instance)
post_save.connect(create_user_profile, sender=settings.AUTH_USER_MODEL)
| Add placeholder for removing customer from saltedge | Add placeholder for removing customer from saltedge
| Python | mit | ltowarek/budget-supervisor | ---
+++
@@ -20,6 +20,9 @@
profile.external_id = data["data"]["id"]
profile.save()
+ def remove_from_saltedge(self, profile):
+ pass
+
class Profile(models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) |
45c7b58dde546711c07969b6b59be9983d45e27e | simple/parsers/utils/laws_parser_utils.py | simple/parsers/utils/laws_parser_utils.py | # -*- coding: utf-8 -*
import re
def normalize_correction_title_dashes(raw_title):
"""returns s with normalized spaces before and after the dash"""
if not raw_title:
return None
m = re.match(r'(תיקון)( ?)(-)( ?)(.*)'.decode('utf8'), raw_title)
if not m:
return raw_title
return ' '.join(m.groups()[0:5:2])
def parse_title(unparsed_title):
return re.match(u'הצעת ([^\(,]*)(.*?\((.*?)\))?(.*?\((.*?)\))?(.*?,(.*))?', unparsed_title)
def clean_line(a_line_str):
return a_line_str.strip().replace('\n', '').replace(' ', ' ')
| # -*- coding: utf-8 -*
import re
def normalize_correction_title_dashes(raw_title):
"""returns s with normalized spaces before and after the dash"""
if not raw_title:
return None
m = re.match(r'(תיקון)( ?)(-)( ?)(.*)'.decode('utf8'), raw_title)
if not m:
return raw_title
return ' '.join(m.groups()[0:5:2])
def parse_title(unparsed_title):
return re.match(u'הצע[תה] ([^\(,]*)(.*?\((.*?)\))?(.*?\((.*?)\))?(.*?,(.*))?', unparsed_title)
def clean_line(a_line_str):
return a_line_str.strip().replace('\n', '').replace(' ', ' ')
| Fix title parser to fix certain missing laws | Fix title parser to fix certain missing laws
| Python | bsd-3-clause | alonisser/Open-Knesset,OriHoch/Open-Knesset,daonb/Open-Knesset,alonisser/Open-Knesset,OriHoch/Open-Knesset,OriHoch/Open-Knesset,daonb/Open-Knesset,OriHoch/Open-Knesset,daonb/Open-Knesset,alonisser/Open-Knesset,daonb/Open-Knesset,alonisser/Open-Knesset | ---
+++
@@ -13,7 +13,7 @@
def parse_title(unparsed_title):
- return re.match(u'הצעת ([^\(,]*)(.*?\((.*?)\))?(.*?\((.*?)\))?(.*?,(.*))?', unparsed_title)
+ return re.match(u'הצע[תה] ([^\(,]*)(.*?\((.*?)\))?(.*?\((.*?)\))?(.*?,(.*))?', unparsed_title)
def clean_line(a_line_str): |
08f80959be067178d4e58138309f7d1b402339e5 | http_ping.py | http_ping.py | from locust import HttpLocust, TaskSet, task
class HttpPingTasks(TaskSet):
@task
def ping(self):
self.client.get("/")
class SayHelloLocust(HttpLocust):
task_set = HttpPingTasks
min_wait = 100
max_wait = 500
| from locust import HttpLocust, TaskSet, task
class HttpPingTasks(TaskSet):
@task
def ping(self):
self.client.get("/")
class HttpPingLocust(HttpLocust):
task_set = HttpPingTasks
min_wait = 100
max_wait = 500
| Rename locust to be consistent with other entities | Rename locust to be consistent with other entities
| Python | apache-2.0 | drednout/locust_on_meetup | ---
+++
@@ -5,7 +5,7 @@
def ping(self):
self.client.get("/")
-class SayHelloLocust(HttpLocust):
+class HttpPingLocust(HttpLocust):
task_set = HttpPingTasks
min_wait = 100
max_wait = 500 |
72d65a50d31fc32fadccc907c91c8e66ad192beb | source/forms/search_form.py | source/forms/search_form.py | import django_countries
from django import forms
from django_countries.fields import LazyTypedChoiceField
class SearchForm(forms.Form):
title = forms.CharField(label='', widget=forms.TextInput(attrs={'placeholder': 'Movie Title'}), max_length=150)
country = LazyTypedChoiceField(choices=django_countries.countries)
| import django_countries
from django import forms
from django_countries.fields import LazyTypedChoiceField
class SearchForm(forms.Form):
title = forms.CharField(label='', widget=forms.TextInput(attrs={'placeholder': 'Movie Title', 'onfocus': 'this.placeholder = ""', 'onblur': 'this.placeholder = "Movie Title"'}), max_length=150)
country = LazyTypedChoiceField(choices=django_countries.countries)
| Hide text input placeholder when onfocus | Hide text input placeholder when onfocus
| Python | mit | jeremyrea/caterblu,jeremyrea/caterblu,jeremyrea/caterblu,jeremyrea/caterblu | ---
+++
@@ -5,5 +5,5 @@
class SearchForm(forms.Form):
- title = forms.CharField(label='', widget=forms.TextInput(attrs={'placeholder': 'Movie Title'}), max_length=150)
+ title = forms.CharField(label='', widget=forms.TextInput(attrs={'placeholder': 'Movie Title', 'onfocus': 'this.placeholder = ""', 'onblur': 'this.placeholder = "Movie Title"'}), max_length=150)
country = LazyTypedChoiceField(choices=django_countries.countries) |
2ac69facc6da342c38c9d851f1ec53a3be0b820a | spacy/tests/regression/test_issue2800.py | spacy/tests/regression/test_issue2800.py | '''Test issue that arises when too many labels are added to NER model.'''
import random
from ...lang.en import English
def train_model(train_data, entity_types):
nlp = English(pipeline=[])
ner = nlp.create_pipe("ner")
nlp.add_pipe(ner)
for entity_type in list(entity_types):
ner.add_label(entity_type)
optimizer = nlp.begin_training()
# Start training
for i in range(20):
losses = {}
index = 0
random.shuffle(train_data)
for statement, entities in train_data:
nlp.update([statement], [entities], sgd=optimizer, losses=losses, drop=0.5)
return nlp
def test_train_with_many_entity_types():
train_data = []
train_data.extend([("One sentence", {"entities": []})])
entity_types = [str(i) for i in range(1000)]
model = train_model(train_data, entity_types)
| '''Test issue that arises when too many labels are added to NER model.'''
from __future__ import unicode_literals
import random
from ...lang.en import English
def train_model(train_data, entity_types):
nlp = English(pipeline=[])
ner = nlp.create_pipe("ner")
nlp.add_pipe(ner)
for entity_type in list(entity_types):
ner.add_label(entity_type)
optimizer = nlp.begin_training()
# Start training
for i in range(20):
losses = {}
index = 0
random.shuffle(train_data)
for statement, entities in train_data:
nlp.update([statement], [entities], sgd=optimizer, losses=losses, drop=0.5)
return nlp
def test_train_with_many_entity_types():
train_data = []
train_data.extend([("One sentence", {"entities": []})])
entity_types = [str(i) for i in range(1000)]
model = train_model(train_data, entity_types)
| Fix Python 2 test failure | Fix Python 2 test failure
| Python | mit | aikramer2/spaCy,spacy-io/spaCy,honnibal/spaCy,aikramer2/spaCy,recognai/spaCy,aikramer2/spaCy,spacy-io/spaCy,explosion/spaCy,recognai/spaCy,aikramer2/spaCy,honnibal/spaCy,recognai/spaCy,explosion/spaCy,explosion/spaCy,explosion/spaCy,aikramer2/spaCy,recognai/spaCy,recognai/spaCy,spacy-io/spaCy,aikramer2/spaCy,honnibal/spaCy,spacy-io/spaCy,explosion/spaCy,explosion/spaCy,recognai/spaCy,spacy-io/spaCy,spacy-io/spaCy,honnibal/spaCy | ---
+++
@@ -1,4 +1,6 @@
'''Test issue that arises when too many labels are added to NER model.'''
+from __future__ import unicode_literals
+
import random
from ...lang.en import English
|
f52465918a1243fc17a8cc5de0b05d68c3ca9218 | src/tempel/urls.py | src/tempel/urls.py | from django.conf.urls.defaults import *
from django.conf import settings
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
(r'^\+media/(?P<path>.*)$', 'django.views.static.serve',
{'document_root': settings.MEDIA_ROOT}),
(r'^admin/', include(admin.site.urls)),
url(r'^(?P<id>\d+)$', 'tempel.views.view', {'mode': 'html'}, name='tempel_view'),
url(r'^(?P<id>\d+).html$', 'tempel.views.view', {'mode': 'html'}, name='tempel_html'),
url(r'^(?P<id>\d+).txt$', 'tempel.views.view', {'mode': 'txt'}, name='tempel_raw'),
url(r'^e/(?P<id>\d+)/download/$', 'tempel.views.download', name='tempel_download'),
url(r'^e/(?P<id>\d+)/edit/(?P<token>\w{8})/$', 'tempel.views.edit', name='tempel_edit'),
url(r'^$', 'tempel.views.index', name='tempel_index'),
)
| from django.conf.urls.defaults import *
from django.conf import settings
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
(r'^\+media/(?P<path>.*)$', 'django.views.static.serve',
{'document_root': settings.MEDIA_ROOT}),
(r'^admin/', include(admin.site.urls)),
url(r'^(?P<id>\d+)$', 'tempel.views.view', {'mode': 'html'}, name='tempel_view'),
url(r'^(?P<id>\d+).html$', 'tempel.views.view', {'mode': 'html'}, name='tempel_html'),
url(r'^(?P<id>\d+).txt$', 'tempel.views.view', {'mode': 'txt'}, name='tempel_raw'),
url(r'^entry/(?P<id>\d+)/download/$', 'tempel.views.download', name='tempel_download'),
url(r'^entry/(?P<id>\d+)/edit/(?P<token>\w{8})/$', 'tempel.views.edit', name='tempel_edit'),
url(r'^$', 'tempel.views.index', name='tempel_index'),
)
| Change url pattern from /e/ to /entry/ | Change url pattern from /e/ to /entry/
| Python | agpl-3.0 | fajran/tempel | ---
+++
@@ -11,8 +11,10 @@
url(r'^(?P<id>\d+)$', 'tempel.views.view', {'mode': 'html'}, name='tempel_view'),
url(r'^(?P<id>\d+).html$', 'tempel.views.view', {'mode': 'html'}, name='tempel_html'),
url(r'^(?P<id>\d+).txt$', 'tempel.views.view', {'mode': 'txt'}, name='tempel_raw'),
- url(r'^e/(?P<id>\d+)/download/$', 'tempel.views.download', name='tempel_download'),
- url(r'^e/(?P<id>\d+)/edit/(?P<token>\w{8})/$', 'tempel.views.edit', name='tempel_edit'),
+
+ url(r'^entry/(?P<id>\d+)/download/$', 'tempel.views.download', name='tempel_download'),
+ url(r'^entry/(?P<id>\d+)/edit/(?P<token>\w{8})/$', 'tempel.views.edit', name='tempel_edit'),
+
url(r'^$', 'tempel.views.index', name='tempel_index'),
)
|
96199b0d6dfea835d6bb23bc87060e5732ef4094 | server/lib/python/cartodb_services/cartodb_services/mapzen/matrix_client.py | server/lib/python/cartodb_services/cartodb_services/mapzen/matrix_client.py | import requests
import json
class MatrixClient:
ONE_TO_MANY_URL = 'https://matrix.mapzen.com/one_to_many'
def __init__(self, matrix_key):
self._matrix_key = matrix_key
"""Get distances and times to a set of locations.
See https://mapzen.com/documentation/matrix/api-reference/
Args:
locations Array of {lat: y, lon: x}
costing Costing model to use
Returns:
A dict with one_to_many, units and locations
"""
def one_to_many(self, locations, costing):
request_params = {
'json': json.dumps({'locations': locations}),
'costing': costing,
'api_key': self._matrix_key
}
response = requests.get(self.ONE_TO_MANY_URL, params=request_params)
return response.json()
| import requests
import json
class MatrixClient:
"""
A minimal client for Mapzen Time-Distance Matrix Service
Example:
client = MatrixClient('your_api_key')
locations = [{"lat":40.744014,"lon":-73.990508},{"lat":40.739735,"lon":-73.979713},{"lat":40.752522,"lon":-73.985015},{"lat":40.750117,"lon":-73.983704},{"lat":40.750552,"lon":-73.993519}]
costing = 'pedestrian'
print client.one_to_many(locations, costing)
"""
ONE_TO_MANY_URL = 'https://matrix.mapzen.com/one_to_many'
def __init__(self, matrix_key):
self._matrix_key = matrix_key
"""Get distances and times to a set of locations.
See https://mapzen.com/documentation/matrix/api-reference/
Args:
locations Array of {lat: y, lon: x}
costing Costing model to use
Returns:
A dict with one_to_many, units and locations
"""
def one_to_many(self, locations, costing):
request_params = {
'json': json.dumps({'locations': locations}),
'costing': costing,
'api_key': self._matrix_key
}
response = requests.get(self.ONE_TO_MANY_URL, params=request_params)
return response.json()
| Add example to code doc | Add example to code doc
| Python | bsd-3-clause | CartoDB/geocoder-api,CartoDB/geocoder-api,CartoDB/geocoder-api,CartoDB/dataservices-api,CartoDB/dataservices-api,CartoDB/dataservices-api,CartoDB/geocoder-api,CartoDB/dataservices-api | ---
+++
@@ -2,6 +2,18 @@
import json
class MatrixClient:
+
+ """
+ A minimal client for Mapzen Time-Distance Matrix Service
+
+ Example:
+
+ client = MatrixClient('your_api_key')
+ locations = [{"lat":40.744014,"lon":-73.990508},{"lat":40.739735,"lon":-73.979713},{"lat":40.752522,"lon":-73.985015},{"lat":40.750117,"lon":-73.983704},{"lat":40.750552,"lon":-73.993519}]
+ costing = 'pedestrian'
+
+ print client.one_to_many(locations, costing)
+ """
ONE_TO_MANY_URL = 'https://matrix.mapzen.com/one_to_many'
@@ -17,7 +29,7 @@
Returns:
A dict with one_to_many, units and locations
- """
+ """
def one_to_many(self, locations, costing):
request_params = {
'json': json.dumps({'locations': locations}), |
0c0f56dba4b9f08f4cb443f2668cdee51fe80c32 | chapter02/fahrenheitToCelsius.py | chapter02/fahrenheitToCelsius.py | #!/usr/bin/env python
F = input("Gimme Fahrenheit: ")
print (F-32) * 5 / 9
print (F-32) / 1.8000
| #!/usr/bin/env python
fahrenheit = input("Gimme Fahrenheit: ")
print (fahrenheit-32) * 5 / 9
print (fahrenheit-32) / 1.8000
| Change variable name to fahrenheit | Change variable name to fahrenheit
| Python | apache-2.0 | MindCookin/python-exercises | ---
+++
@@ -1,6 +1,6 @@
#!/usr/bin/env python
-F = input("Gimme Fahrenheit: ")
+fahrenheit = input("Gimme Fahrenheit: ")
-print (F-32) * 5 / 9
-print (F-32) / 1.8000
+print (fahrenheit-32) * 5 / 9
+print (fahrenheit-32) / 1.8000 |
2664e9124af6b0d8f6b2eacd50f4d7e93b91e931 | examples/GoBot/gobot.py | examples/GoBot/gobot.py | from minibot.bot import Bot
from minibot.hardware.rpi.gpio import PWM
from minibot.interface.servo import Servo
import math
import time
L_MOTOR_PIN = 12
R_MOTOR_PIN = 18
class GoBot(Bot):
def __init__(self):
Bot.__init__(self, "GoBot")
self.l_motor = Servo(PWM(L_MOTOR_PIN, 2, 15))
self.r_motor = Servo(PWM(R_MOTOR_PIN, 2, 15))
self.l_motor.set(17)
self.r_motor.set(13)
def run(self):
pass
if __name__ == "__main__":
bot = GoBot()
while True:
bot.run()
| """
GoBot Example
"""
from minibot.bot import Bot
from minibot.hardware.rpi.gpio import PWM
from minibot.interface.servo import Servo
L_MOTOR_PIN = 12
R_MOTOR_PIN = 18
class GoBot(Bot):
"""
GoBot
"""
def __init__(self):
Bot.__init__(self, "GoBot")
self.l_motor = Servo(PWM(L_MOTOR_PIN, 2, 15))
self.r_motor = Servo(PWM(R_MOTOR_PIN, 2, 15))
self.l_motor.set(17)
self.r_motor.set(13)
def run(self):
pass
if __name__ == "__main__":
bot = GoBot()
while True:
bot.run()
| Fix linting errors in GoBot | Fix linting errors in GoBot
| Python | apache-2.0 | cornell-cup/cs-minibot,cornell-cup/cs-minibot,cornell-cup/cs-minibot,cornell-cup/cs-minibot,cornell-cup/cs-minibot | ---
+++
@@ -1,14 +1,18 @@
+"""
+GoBot Example
+"""
+
from minibot.bot import Bot
from minibot.hardware.rpi.gpio import PWM
from minibot.interface.servo import Servo
-
-import math
-import time
L_MOTOR_PIN = 12
R_MOTOR_PIN = 18
class GoBot(Bot):
+ """
+ GoBot
+ """
def __init__(self):
Bot.__init__(self, "GoBot") |
c8376eddddd7bb61d4ae608e2fe0a0f333b0be84 | backend/zotero.py | backend/zotero.py | # -*- encoding: utf-8 -*-
from django.conf import settings
from papers.errors import MetadataSourceException
from papers.utils import sanitize_html
import requests
##### Zotero interface #####
def fetch_zotero_by_DOI(doi):
"""
Fetch Zotero metadata for a given DOI.
Works only with the doi_cache proxy.
"""
try:
request = requests.get('http://'+settings.DOI_PROXY_DOMAIN+'/zotero/'+doi)
return request.json()
except ValueError as e:
raise MetadataSourceException('Error while fetching Zotero metadata:\nInvalid JSON response.\n' +
'Error: '+str(e))
def consolidate_publication(publi):
"""
Fetches the abstract from Zotero and adds it to the publication if it succeeds.
"""
zotero = fetch_zotero_by_DOI(publi.doi)
if zotero is None:
return publi
for item in zotero:
if 'abstractNote' in item:
publi.description = sanitize_html(item['abstractNote'])
publi.save(update_fields=['description'])
for attachment in item.get('attachments', []):
if attachment.get('mimeType') == 'application/pdf':
publi.pdf_url = attachment.get('url')
publi.save(update_fields=['pdf_url'])
publi.about.update_availability()
return publi
| # -*- encoding: utf-8 -*-
from django.conf import settings
from papers.errors import MetadataSourceException
from papers.utils import sanitize_html
import requests
##### Zotero interface #####
def fetch_zotero_by_DOI(doi):
"""
Fetch Zotero metadata for a given DOI.
Works only with the doi_cache proxy.
"""
try:
request = requests.get('https://'+settings.DOI_PROXY_DOMAIN+'/zotero/'+doi)
return request.json()
except ValueError as e:
raise MetadataSourceException('Error while fetching Zotero metadata:\nInvalid JSON response.\n' +
'Error: '+str(e))
def consolidate_publication(publi):
"""
Fetches the abstract from Zotero and adds it to the publication if it succeeds.
"""
zotero = fetch_zotero_by_DOI(publi.doi)
if zotero is None:
return publi
for item in zotero:
if 'abstractNote' in item:
publi.description = sanitize_html(item['abstractNote'])
publi.save(update_fields=['description'])
for attachment in item.get('attachments', []):
if attachment.get('mimeType') == 'application/pdf':
publi.pdf_url = attachment.get('url')
publi.save(update_fields=['pdf_url'])
publi.about.update_availability()
return publi
| Use HTTPS instead of HTTP since cache does redirect anyways | Use HTTPS instead of HTTP since cache does redirect anyways
| Python | agpl-3.0 | wetneb/dissemin,dissemin/dissemin,dissemin/dissemin,wetneb/dissemin,dissemin/dissemin,wetneb/dissemin,wetneb/dissemin,dissemin/dissemin,dissemin/dissemin | ---
+++
@@ -14,7 +14,7 @@
Works only with the doi_cache proxy.
"""
try:
- request = requests.get('http://'+settings.DOI_PROXY_DOMAIN+'/zotero/'+doi)
+ request = requests.get('https://'+settings.DOI_PROXY_DOMAIN+'/zotero/'+doi)
return request.json()
except ValueError as e:
raise MetadataSourceException('Error while fetching Zotero metadata:\nInvalid JSON response.\n' + |
525fdd26dac942d90352276f00f06460d1f950ee | setup.py | setup.py | from distutils.core import setup
setup(name="zutil",
version='0.1.2',
description="Utilities used for generating zCFD control dictionaries",
author="Zenotech",
author_email="support@zenotech.com",
url="https://zcfd.zenotech.com/",
packages=["zutil", "zutil.post", "zutil.analysis", "zutil.plot"],
install_requires=[
'mpi4py',
'ipython',
'Fabric',
'ipywidgets',
'matplotlib',
'numpy',
'pandas',
'PyYAML'
],
) | from distutils.core import setup
setup(name="zutil",
version='0.1.2',
description="Utilities used for generating zCFD control dictionaries",
author="Zenotech",
author_email="support@zenotech.com",
url="https://zcfd.zenotech.com/",
packages=["zutil", "zutil.post", "zutil.analysis", "zutil.plot"],
install_requires=[
'mpi4py',
'ipython<6.0',
'Fabric',
'ipywidgets',
'matplotlib',
'numpy',
'pandas',
'PyYAML'
],
) | Set max version of iPython required | Set max version of iPython required
| Python | mit | zCFD/zutil | ---
+++
@@ -9,7 +9,7 @@
packages=["zutil", "zutil.post", "zutil.analysis", "zutil.plot"],
install_requires=[
'mpi4py',
- 'ipython',
+ 'ipython<6.0',
'Fabric',
'ipywidgets',
'matplotlib', |
84ecbb0200c4d0cc170593835a5ae7ca5a6a09fc | setup.py | setup.py | #!/usr/bin/env python
import os
from setuptools import setup, find_packages
def get_readme():
return open(os.path.join(os.path.dirname(__file__), 'README.rst')).read()
setup(
name='rest_framework_ember',
version='1.0.3',
description="Make EmberJS and Django Rest Framework play nice together.",
long_description=get_readme(),
author="nGen Works",
author_email='tech@ngenworks.com',
url='https://github.com/ngenworks/rest_framework_ember',
license='BSD',
keywords="EmberJS Django REST",
packages=find_packages(),
install_requires=['django', 'djangorestframework', 'inflection' ],
platforms=['any'],
classifiers=[
'Development Status :: 4 - Beta',
'Framework :: Django',
'Environment :: Web Environment',
'License :: OSI Approved :: BSD License',
'Intended Audience :: Developers',
'Programming Language :: Python',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Topic :: Software Development :: Libraries :: Application Frameworks',
'Topic :: Software Development :: Libraries :: Python Modules',
]
)
| #!/usr/bin/env python
import os
from setuptools import setup, find_packages
def get_readme():
return open(os.path.join(os.path.dirname(__file__), 'README.rst')).read()
setup(
name='rest_framework_ember',
version='1.0.3',
description="Make EmberJS and Django Rest Framework play nice together.",
long_description=get_readme(),
author="nGen Works",
author_email='tech@ngenworks.com',
url='https://github.com/ngenworks/rest_framework_ember',
license='BSD',
keywords="EmberJS Django REST",
packages=find_packages(),
install_requires=['django', 'djangorestframework >= 3.0.0', 'inflection' ],
platforms=['any'],
classifiers=[
'Development Status :: 4 - Beta',
'Framework :: Django',
'Environment :: Web Environment',
'License :: OSI Approved :: BSD License',
'Intended Audience :: Developers',
'Programming Language :: Python',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Topic :: Software Development :: Libraries :: Application Frameworks',
'Topic :: Software Development :: Libraries :: Python Modules',
]
)
| Set a minimum DRF version for the next release | Set a minimum DRF version for the next release
| Python | bsd-2-clause | coUrbanize/rest_framework_ember,grapo/django-rest-framework-json-api,pombredanne/django-rest-framework-json-api,leo-naeka/django-rest-framework-json-api,django-json-api/django-rest-framework-json-api,schtibe/django-rest-framework-json-api,leifurhauks/django-rest-framework-json-api,abdulhaq-e/django-rest-framework-json-api,martinmaillard/django-rest-framework-json-api,scottfisk/django-rest-framework-json-api,lukaslundgren/django-rest-framework-json-api,django-json-api/rest_framework_ember,Instawork/django-rest-framework-json-api,hnakamur/django-rest-framework-json-api,leo-naeka/rest_framework_ember,aquavitae/django-rest-framework-json-api,kaldras/django-rest-framework-json-api,pattisdr/django-rest-framework-json-api,django-json-api/django-rest-framework-json-api | ---
+++
@@ -16,7 +16,7 @@
license='BSD',
keywords="EmberJS Django REST",
packages=find_packages(),
- install_requires=['django', 'djangorestframework', 'inflection' ],
+ install_requires=['django', 'djangorestframework >= 3.0.0', 'inflection' ],
platforms=['any'],
classifiers=[
'Development Status :: 4 - Beta', |
672a5daeec78d5ac6a35dfe82cd48ef3e45a648c | setup.py | setup.py | import sys
from setuptools import find_packages, setup
tests_require = [
'coverage>=4.0',
'pytest-isort',
'pytest-cache>=1.0',
'flake8<3.0.0',
'pytest-flake8>=0.5',
'pytest>=2.8.0',
'pytest-wholenodeid',
]
needs_pytest = set(['pytest', 'test', 'ptr']).intersection(sys.argv)
pytest_runner = ['pytest-runner'] if needs_pytest else []
setup(
name='jupyter-notebook-gist',
version='0.4a1',
description='Create a gist from the Jupyter Notebook UI',
author='Mozilla Telemetry',
author_email='telemetry@lists.mozilla.org',
packages=find_packages(where='src'),
package_dir={'': 'src'},
include_package_data=True,
license='MPL2',
install_requires=[
'ipython >= 4',
'notebook >= 4.2',
'jupyter',
'requests',
'widgetsnbextension',
],
setup_requires=[] + pytest_runner,
tests_require=tests_require,
url='https://github.com/mozilla/jupyter-notebook-gist',
zip_safe=False,
)
| import sys
from setuptools import find_packages, setup
tests_require = [
'coverage>=4.0',
'pytest-isort',
'pytest-cache>=1.0',
'flake8<3.0.0',
'pytest-flake8>=0.5',
'pytest>=2.8.0',
'pytest-wholenodeid',
]
needs_pytest = set(['pytest', 'test', 'ptr']).intersection(sys.argv)
pytest_runner = ['pytest-runner'] if needs_pytest else []
setup(
name='jupyter-notebook-gist',
version='0.4a1',
description='Create a gist from the Jupyter Notebook UI',
author='Mozilla Firefox Data Platform',
author_email='fx-data-platform@mozilla.com',
packages=find_packages(where='src'),
package_dir={'': 'src'},
include_package_data=True,
license='MPL2',
install_requires=[
'ipython >= 4',
'notebook >= 4.2',
'jupyter',
'requests',
'widgetsnbextension',
],
setup_requires=[] + pytest_runner,
tests_require=tests_require,
url='https://github.com/mozilla/jupyter-notebook-gist',
zip_safe=False,
)
| Update author and email in package metadata | Update author and email in package metadata
| Python | mpl-2.0 | mozilla/jupyter-notebook-gist,mreid-moz/jupyter-notebook-gist,mozilla/jupyter-notebook-gist,mreid-moz/jupyter-notebook-gist | ---
+++
@@ -19,8 +19,8 @@
name='jupyter-notebook-gist',
version='0.4a1',
description='Create a gist from the Jupyter Notebook UI',
- author='Mozilla Telemetry',
- author_email='telemetry@lists.mozilla.org',
+ author='Mozilla Firefox Data Platform',
+ author_email='fx-data-platform@mozilla.com',
packages=find_packages(where='src'),
package_dir={'': 'src'},
include_package_data=True, |
d57088b4beeae269786970041b7837f69f0e9daf | setup.py | setup.py |
#! /usr/bin/env python
import os
from setuptools import setup, find_packages
# with open(os.path.join(os.path.dirname(__file__), 'README.md')) as readme:
# README = readme.read()
# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name="django-name",
version="1.0.0",
packages=find_packages(),
include_package_data=True,
license="BSD",
description="A Django application for inviting users to a site.",
# long_description=README,
keywords="django invite invitation",
author="University of North Texas Libraries",
# cmdclass={'test': PyTest},
url="https://github.com/unt-libraries/django-invite",
classifiers=[
"Environment :: Web Environment",
"Framework :: Django",
"Intended Audience :: System Administrators",
"Intended Audience :: End Users/Desktop",
"License :: OSI Approved :: BSD License",
"Natural Language :: English",
"Operating System :: OS Independent",
"Programming Language :: Python",
"Programming Language :: Python :: 2.7",
"Topic :: Internet :: WWW/HTTP :: WSGI :: Application :: User Management"
]
)
|
#! /usr/bin/env python
import os
from setuptools import setup, find_packages
# with open(os.path.join(os.path.dirname(__file__), 'README.md')) as readme:
# README = readme.read()
# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name="django-name",
version="pre-release",
packages=find_packages(),
include_package_data=True,
license="BSD",
description="Name Authority App for Django.",
# long_description=README,
keywords="django name citation",
author="University of North Texas Libraries",
# cmdclass={'test': PyTest},
url="https://github.com/unt-libraries/django-name",
classifiers=[
"Environment :: Web Environment",
"Framework :: Django",
"Intended Audience :: System Administrators",
"Intended Audience :: End Users/Desktop",
"License :: OSI Approved :: BSD License",
"Natural Language :: English",
"Operating System :: OS Independent",
"Programming Language :: Python",
"Programming Language :: Python :: 2.7",
"Topic :: Internet :: WWW/HTTP :: WSGI :: Application :: User Management"
]
)
| Fix the keywords, url, and description. | Fix the keywords, url, and description.
| Python | bsd-3-clause | unt-libraries/django-name,damonkelley/django-name,unt-libraries/django-name,unt-libraries/django-name,damonkelley/django-name,damonkelley/django-name | ---
+++
@@ -12,17 +12,17 @@
setup(
name="django-name",
- version="1.0.0",
+ version="pre-release",
packages=find_packages(),
include_package_data=True,
license="BSD",
- description="A Django application for inviting users to a site.",
+ description="Name Authority App for Django.",
# long_description=README,
- keywords="django invite invitation",
+ keywords="django name citation",
author="University of North Texas Libraries",
# cmdclass={'test': PyTest},
- url="https://github.com/unt-libraries/django-invite",
+ url="https://github.com/unt-libraries/django-name",
classifiers=[
"Environment :: Web Environment",
"Framework :: Django", |
fb00316ac62014564e299c94b8130b9316ee3d31 | setup.py | setup.py | from setuptools import setup, find_packages
import os
version = '0.6.3'
here = os.path.abspath(os.path.dirname(__file__))
try:
README = open(os.path.join(here, 'README.txt')).read()
CHANGES = open(os.path.join(here, 'docs/HISTORY.txt')).read()
except IOError:
README = CHANGES = ''
setup(name='tgext.admin',
version=version,
description="Admin Controller add-on for basic TG identity model.",
long_description=README + "\n" +
CHANGES,
# Get more strings from http://www.python.org/pypi?%3Aaction=list_classifiers
classifiers=[
"Programming Language :: Python",
"Topic :: Software Development :: Libraries :: Python Modules",
],
keywords='turbogears2.extension, TG2, TG, sprox, Rest, internet, admin',
author='Christopher Perkins',
author_email='chris@percious.com',
url='https://github.com/TurboGears/tgext.admin',
license='MIT',
packages=find_packages(exclude=['ez_setup']),
namespace_packages=['tgext'],
include_package_data=True,
zip_safe=True,
install_requires=[
'setuptools',
'tgext.crud>=0.7.1',
# -*- Extra requirements: -*-
],
entry_points="""
# -*- Entry points: -*-
""",
)
| from setuptools import setup, find_packages
import os
version = '0.6.3'
here = os.path.abspath(os.path.dirname(__file__))
try:
README = open(os.path.join(here, 'README.txt')).read()
CHANGES = open(os.path.join(here, 'docs/HISTORY.txt')).read()
except IOError:
README = CHANGES = ''
setup(name='tgext.admin',
version=version,
description="Admin Controller add-on for basic TG identity model.",
long_description=README + "\n" +
CHANGES,
# Get more strings from http://www.python.org/pypi?%3Aaction=list_classifiers
classifiers=[
"Programming Language :: Python",
"Topic :: Software Development :: Libraries :: Python Modules",
],
keywords='turbogears2.extension, TG2, TG, sprox, Rest, internet, admin',
author='Christopher Perkins',
author_email='chris@percious.com',
url='https://github.com/TurboGears/tgext.admin',
license='MIT',
packages=find_packages(exclude=['ez_setup']),
namespace_packages=['tgext'],
include_package_data=True,
zip_safe=False,
install_requires=[
'setuptools',
'tgext.crud>=0.7.1',
# -*- Extra requirements: -*-
],
entry_points="""
# -*- Entry points: -*-
""",
)
| Set zip_safe=False to make TW2 happy | Set zip_safe=False to make TW2 happy
| Python | mit | TurboGears/tgext.admin,TurboGears/tgext.admin | ---
+++
@@ -27,7 +27,7 @@
packages=find_packages(exclude=['ez_setup']),
namespace_packages=['tgext'],
include_package_data=True,
- zip_safe=True,
+ zip_safe=False,
install_requires=[
'setuptools',
'tgext.crud>=0.7.1', |
fe60f4b290403ccdf17f78502f9033e70dbff52a | setup.py | setup.py | # -*- coding: utf-8 -*-
import sys
from setuptools import setup
with open('README.rst', 'rb') as f:
long_desc = f.read().decode('utf-8')
# We have to be able to install on Linux to build the docs, even though
# dmgbuild presently won't work there because there's no SetFile
requires=['ds_store >= 1.1.0',
'mac_alias >= 2.0.1']
if sys.platform.startswith('darwin'):
requires.append('pyobjc-framework-Quartz >= 3.0.4')
setup(name='dmgbuild',
version='1.3.0',
description='macOS command line utility to build disk images',
long_description=long_desc,
author='Alastair Houghton',
author_email='alastair@alastairs-place.net',
url='http://alastairs-place.net/projects/dmgbuild',
license='MIT License',
platforms='darwin',
packages=['dmgbuild'],
classifiers=[
'Development Status :: 5 - Production/Stable',
'License :: OSI Approved :: MIT License',
'Topic :: Desktop Environment',
],
package_data = {
'dmgbuild': ['resources/*']
},
scripts=['scripts/dmgbuild'],
install_requires=requires,
provides=['dmgbuild']
)
| # -*- coding: utf-8 -*-
import sys
from setuptools import setup
with open('README.rst', 'rb') as f:
long_desc = f.read().decode('utf-8')
# We have to be able to install on Linux to build the docs, even though
# dmgbuild presently won't work there because there's no SetFile
requires=['ds_store >= 1.1.0',
'mac_alias >= 2.0.1']
setup(name='dmgbuild',
version='1.3.0',
description='macOS command line utility to build disk images',
long_description=long_desc,
author='Alastair Houghton',
author_email='alastair@alastairs-place.net',
url='http://alastairs-place.net/projects/dmgbuild',
license='MIT License',
platforms='darwin',
packages=['dmgbuild'],
classifiers=[
'Development Status :: 5 - Production/Stable',
'License :: OSI Approved :: MIT License',
'Topic :: Desktop Environment',
],
package_data = {
'dmgbuild': ['resources/*']
},
scripts=['scripts/dmgbuild'],
install_requires=requires,
provides=['dmgbuild']
)
| Remove pyobjc-framework-Quartz dependency as it seems to be unnecessary | Remove pyobjc-framework-Quartz dependency as it seems to be unnecessary
closes #11
| Python | mit | al45tair/dmgbuild | ---
+++
@@ -9,9 +9,6 @@
# dmgbuild presently won't work there because there's no SetFile
requires=['ds_store >= 1.1.0',
'mac_alias >= 2.0.1']
-
-if sys.platform.startswith('darwin'):
- requires.append('pyobjc-framework-Quartz >= 3.0.4')
setup(name='dmgbuild',
version='1.3.0', |
3121d42bdca353d459ae61a6a93bdb854fcabe13 | pymacaroons/__init__.py | pymacaroons/__init__.py | __author__ = 'Evan Cordell'
__version__ = "0.5.1"
__version_info__ = tuple(__version__.split('.'))
__short_version__ = __version__
from .macaroon import Macaroon
from .caveat import Caveat
from .verifier import Verifier
| __author__ = 'Evan Cordell'
__version__ = "0.5.1"
__version_info__ = tuple(__version__.split('.'))
__short_version__ = __version__
from .macaroon import Macaroon
from .caveat import Caveat
from .verifier import Verifier
__all__ = [
'Macaroon',
'Caveat',
'Verifier',
]
| Add __all__ to main module | Add __all__ to main module
| Python | mit | illicitonion/pymacaroons,ecordell/pymacaroons,matrix-org/pymacaroons,matrix-org/pymacaroons | ---
+++
@@ -7,3 +7,9 @@
from .macaroon import Macaroon
from .caveat import Caveat
from .verifier import Verifier
+
+__all__ = [
+ 'Macaroon',
+ 'Caveat',
+ 'Verifier',
+] |
53d1a66498f05d89b9644d2013104bb7ec739a31 | setup.py | setup.py | # -*- coding: utf-8 -*-
from setuptools import setup, find_packages
try:
long_description = open("README.md").read()
except IOError:
long_description = ""
setup(
name="vania",
version="0.1.0",
description="A module to fairly distribute tasks considering people preferences.",
license="MIT",
author="Hackathonners",
packages=find_packages(),
install_requires=[
'pulp',
],
package_dir={'': '.'},
long_description=long_description,
classifiers=[
"Programming Language :: Python",
"Programming Language :: Python :: 2.7",
],
test_suite='nose.collector',
tests_require=['nose'],
)
| # -*- coding: utf-8 -*-
from setuptools import setup, find_packages
try:
long_description = open("README.md").read()
except IOError:
long_description = ""
setup(
name="vania",
version="0.1.0",
description="A module to fairly distribute tasks considering people preferences.",
license="MIT",
author="Hackathonners",
packages=find_packages(),
install_requires=[
'pulp',
],
package_dir={'': '.'},
long_description=long_description,
classifiers=[
"Programming Language :: Python",
"Programming Language :: Python :: 3",
],
test_suite='nose.collector',
tests_require=['nose'],
)
| Add Python 3 as dependency | Add Python 3 as dependency
| Python | mit | Hackathonners/vania | ---
+++
@@ -20,7 +20,7 @@
long_description=long_description,
classifiers=[
"Programming Language :: Python",
- "Programming Language :: Python :: 2.7",
+ "Programming Language :: Python :: 3",
],
test_suite='nose.collector',
tests_require=['nose'], |
6531a8c9da651f57a64036b777ff7fa4f430b517 | setup.py | setup.py | #!/usr/bin/env python
from setuptools import setup
from fandjango import __version__
setup(
name = 'fandjango',
version = __version__,
description = "Fandjango makes it stupidly easy to create Facebook applications with Django.",
long_description = open('README.rst').read(),
author = "Johannes Gorset",
author_email = "jgorset@gmail.com",
url = "http://github.com/jgorset/fandjango",
packages = [
'fandjango',
'fandjango.migrations',
'fandjango.templatetags'
],
package_data = {
'fandjango': ['templates/*', 'locale/*']
},
install_requires = [
'facepy==0.5.1',
'requests==0.7.6'
],
classifiers = [
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'Natural Language :: English',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7'
]
)
| #!/usr/bin/env python
from setuptools import setup
from fandjango import __version__
setup(
name = 'fandjango',
version = __version__,
description = "Fandjango makes it stupidly easy to create Facebook applications with Django.",
long_description = open('README.rst').read(),
author = "Johannes Gorset",
author_email = "jgorset@gmail.com",
url = "http://github.com/jgorset/fandjango",
packages = [
'fandjango',
'fandjango.migrations',
'fandjango.templatetags'
],
package_data = {
'fandjango': [
'templates/*',
'locale/*'
'migrations/*'
]
},
install_requires = [
'facepy==0.5.1',
'requests==0.7.6'
],
classifiers = [
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'Natural Language :: English',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7'
]
)
| Add migrations to package data | Add migrations to package data
| Python | mit | jgorset/fandjango,jgorset/fandjango | ---
+++
@@ -18,7 +18,11 @@
'fandjango.templatetags'
],
package_data = {
- 'fandjango': ['templates/*', 'locale/*']
+ 'fandjango': [
+ 'templates/*',
+ 'locale/*'
+ 'migrations/*'
+ ]
},
install_requires = [
'facepy==0.5.1', |
5dcfeb2a13f3ab9fe8b20e2620cbc15593cd56dc | pytest_watch/spooler.py | pytest_watch/spooler.py | # -*- coding: utf-8
from multiprocessing import Queue, Process, Event
class Timer(Process):
def __init__(self, interval, function, args=[], kwargs={}):
super(Timer, self).__init__()
self.interval = interval
self.function = function
self.args = args
self.kwargs = kwargs
self.finished = Event()
def cancel(self):
self.finished.set()
def run(self):
self.finished.wait(self.interval)
if not self.finished.is_set():
self.function(*self.args, **self.kwargs)
self.finished.set()
class EventSpooler(object):
def __init__(self, cooldown, callback):
self.cooldown = cooldown
self.callback = callback
self.inbox = Queue()
self.outbox = Queue()
def enqueue(self, event):
self.inbox.put(event)
Timer(self.cooldown, self.process).start()
def process(self):
self.outbox.put(self.inbox.get())
if self.inbox.empty():
events = []
while not self.outbox.empty():
events.append(self.outbox.get())
self.callback(events)
| from threading import Thread, Event
try:
from queue import Queue
except ImportError:
from Queue import Queue
class Timer(Thread):
def __init__(self, interval, function, args=[], kwargs={}):
super(Timer, self).__init__()
self.interval = interval
self.function = function
self.args = args
self.kwargs = kwargs
self.finished = Event()
def cancel(self):
self.finished.set()
def run(self):
self.finished.wait(self.interval)
if not self.finished.is_set():
self.function(*self.args, **self.kwargs)
self.finished.set()
class EventSpooler(object):
def __init__(self, cooldown, callback):
self.cooldown = cooldown
self.callback = callback
self.inbox = Queue()
self.outbox = Queue()
def enqueue(self, event):
self.inbox.put(event)
Timer(self.cooldown, self.process).start()
def process(self):
self.outbox.put(self.inbox.get())
if self.inbox.empty():
events = []
while not self.outbox.empty():
events.append(self.outbox.get())
self.callback(events)
| Use threading instead of multiprocessing. | Use threading instead of multiprocessing.
| Python | mit | blueyed/pytest-watch,rakjin/pytest-watch,ColtonProvias/pytest-watch,joeyespo/pytest-watch | ---
+++
@@ -1,9 +1,12 @@
-# -*- coding: utf-8
+from threading import Thread, Event
-from multiprocessing import Queue, Process, Event
+try:
+ from queue import Queue
+except ImportError:
+ from Queue import Queue
-class Timer(Process):
+class Timer(Thread):
def __init__(self, interval, function, args=[], kwargs={}):
super(Timer, self).__init__()
self.interval = interval |
e4badca1d01e25efec8cf2b45f1e2731f4dc2d5a | setup.py | setup.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from setuptools import find_packages, setup
with open("README.md") as readme_file:
readme = readme_file.read()
requirements = ["Pillow>=5.3.0", "numpy>=1.15.4", "Click>=7.0"]
setup(
author="Ryan Gibson",
author_email="ryanalexandergibson@gmail.com",
name="stego_lsb",
version="1.3",
description="stego lsb",
keywords="stego lsb",
license="MIT",
long_description=readme,
long_description_content_type="text/markdown",
url="https://github.com/ragibson/Steganography",
install_requires=requirements,
entry_points="""
[console_scripts]
stegolsb=stego_lsb.cli:main
""",
include_package_data=True,
packages=find_packages(include=["stego_lsb"]),
zip_safe=False,
python_requires=">=3.6",
classifiers=[
"Development Status :: 4 - Beta",
"Intended Audience :: Developers",
"License :: OSI Approved :: MIT License",
"Natural Language :: English",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.6",
"Programming Language :: Python :: 3.7",
"Programming Language :: Python :: 3.8",
"Programming Language :: Python :: 3.9",
"Programming Language :: Python :: 3 :: Only",
],
)
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
from setuptools import find_packages, setup
with open("README.md") as readme_file:
readme = readme_file.read()
requirements = ["Pillow>=5.3.0", "numpy>=1.15.4", "Click>=7.0"]
setup(
author="Ryan Gibson",
author_email="ryanalexandergibson@gmail.com",
name="stego_lsb",
version="1.3.1",
description="stego lsb",
keywords="stego lsb",
license="MIT",
long_description=readme,
long_description_content_type="text/markdown",
url="https://github.com/ragibson/Steganography",
install_requires=requirements,
entry_points="""
[console_scripts]
stegolsb=stego_lsb.cli:main
""",
include_package_data=True,
packages=find_packages(include=["stego_lsb"]),
zip_safe=False,
python_requires=">=3.6",
classifiers=[
"Development Status :: 4 - Beta",
"Intended Audience :: Developers",
"License :: OSI Approved :: MIT License",
"Natural Language :: English",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.6",
"Programming Language :: Python :: 3.7",
"Programming Language :: Python :: 3.8",
"Programming Language :: Python :: 3.9",
"Programming Language :: Python :: 3 :: Only",
],
)
| Increase version number for Python 3.9 support | Increase version number for Python 3.9 support
| Python | mit | ragibson/Steganography | ---
+++
@@ -12,7 +12,7 @@
author="Ryan Gibson",
author_email="ryanalexandergibson@gmail.com",
name="stego_lsb",
- version="1.3",
+ version="1.3.1",
description="stego lsb",
keywords="stego lsb",
license="MIT", |
af63afb5d5a010406557e325e759cdd310214c71 | setup.py | setup.py | #!/Applications/anaconda/envs/Python3/bin
def main():
x = input("Enter a number: ")
print("Your number is {}".format(x))
if __name__ == '__main__':
main()
| #!/Applications/anaconda/envs/Python3/bin
def main():
# Get input from user and display it
feels = input("On a scale of 1-10, how do you feel? ")
print("You selected: {}".format(feels))
# Python Data Types
integer = 42
floater = 3.14
stringer = 'Hello, World!'
tupler = (1, 2, 3)
lister = [1, 2, 3]
dicter = dict(
one = 1,
two = 2,
three = 3
)
boolTrue = True
boolFalse = False
# Conditionals
num1, num2 = 0, 1
if (num1 > num2):
print("{} is greater than {}".format(num1, num2))
elif (num1 < num2):
print("{} is less than {}".format(num1, num2))
else:
print("{} is equal to {}".format(num1, num2))
bigger = num1 if num1 >= num2 else num2
smaller = num1 if num1 < num2 else num2
print("Conditional statment says {} is greater than or equal to {}".format(bigger, smaller))
# Python version of a switch statement
choices = dict(
a = 'First',
b = 'Second',
c = 'Third',
d = 'Fourth',
e = 'Fifth'
)
opt1 = 'c'
opt2 = 'f'
default = 'Option not found'
print(choices)
print("Option 1 was {} and returned: {}".format(opt1, choices.get(opt1, default)))
print("Option 2 was {} and returned: {}".format(opt2, choices.get(opt2, default)))
# Loops
print("Fibonacci series up to 100:")
a, b = 0, 1
while b < 100:
print(b, end=" ")
a, b = b, a + b
print()
for letter in stringer:
if letter in 'aeiouAEIOU':
continue
if letter in '!@#$%^&*.,?;:-_+=|':
break
print(letter)
# Get an index using a for loop with enumerate()
for index, letter in enumerate(stringer):
print("Index: {} is letter: {}".format(index, letter))
if __name__ == '__main__':
main()
| Add PY quick start examples | Add PY quick start examples
| Python | mit | HKuz/Test_Code | ---
+++
@@ -1,8 +1,71 @@
#!/Applications/anaconda/envs/Python3/bin
def main():
- x = input("Enter a number: ")
- print("Your number is {}".format(x))
+ # Get input from user and display it
+ feels = input("On a scale of 1-10, how do you feel? ")
+ print("You selected: {}".format(feels))
+
+ # Python Data Types
+ integer = 42
+ floater = 3.14
+ stringer = 'Hello, World!'
+ tupler = (1, 2, 3)
+ lister = [1, 2, 3]
+ dicter = dict(
+ one = 1,
+ two = 2,
+ three = 3
+ )
+ boolTrue = True
+ boolFalse = False
+
+ # Conditionals
+ num1, num2 = 0, 1
+ if (num1 > num2):
+ print("{} is greater than {}".format(num1, num2))
+ elif (num1 < num2):
+ print("{} is less than {}".format(num1, num2))
+ else:
+ print("{} is equal to {}".format(num1, num2))
+
+ bigger = num1 if num1 >= num2 else num2
+ smaller = num1 if num1 < num2 else num2
+ print("Conditional statment says {} is greater than or equal to {}".format(bigger, smaller))
+
+ # Python version of a switch statement
+ choices = dict(
+ a = 'First',
+ b = 'Second',
+ c = 'Third',
+ d = 'Fourth',
+ e = 'Fifth'
+ )
+ opt1 = 'c'
+ opt2 = 'f'
+ default = 'Option not found'
+
+ print(choices)
+ print("Option 1 was {} and returned: {}".format(opt1, choices.get(opt1, default)))
+ print("Option 2 was {} and returned: {}".format(opt2, choices.get(opt2, default)))
+
+ # Loops
+ print("Fibonacci series up to 100:")
+ a, b = 0, 1
+ while b < 100:
+ print(b, end=" ")
+ a, b = b, a + b
+ print()
+
+ for letter in stringer:
+ if letter in 'aeiouAEIOU':
+ continue
+ if letter in '!@#$%^&*.,?;:-_+=|':
+ break
+ print(letter)
+
+ # Get an index using a for loop with enumerate()
+ for index, letter in enumerate(stringer):
+ print("Index: {} is letter: {}".format(index, letter))
if __name__ == '__main__': |
8f5341324be97e7c6c7f0e93bd23762f3ad0b4a1 | setup.py | setup.py | from distutils.core import setup
from setuptools import find_packages
import os
import sys
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
def find_packages_in(where, **kwargs):
return [where] + ['%s.%s' % (where, package) for package in find_packages(where=where, **kwargs)]
setup(
name = 'django-multitenant',
version = '0.2.7',
author = 'Allan Lei',
author_email = 'allanlei@helveticode.com',
description = ('Multi-tenant addons for Django'),
license = 'New BSD',
keywords = 'multitenant multidb multischema django',
url = 'https://github.com/allanlei/django-multitenant',
packages=find_packages_in('tenant'),
long_description=read('README.md'),
classifiers=[
'Development Status :: 3 - Alpha',
'License :: OSI Approved :: BSD License',
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Software Development :: Libraries :: Python Modules',
],
)
| from distutils.core import setup
from setuptools import find_packages
import os
import sys
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
def find_packages_in(where, **kwargs):
return [where] + ['%s.%s' % (where, package) for package in find_packages(where=where, **kwargs)]
setup(
name = 'django-multitenant',
version = '0.2.7',
author = 'Allan Lei',
author_email = 'allanlei@helveticode.com',
description = ('Multi-tenant addons for Django'),
license = 'New BSD',
keywords = 'multitenant multidb multischema django',
url = 'https://github.com/allanlei/django-multitenant',
packages=find_packages_in('tenant'),
long_description=read('README.md'),
install_requires=[
'Django<1.4',
],
classifiers=[
'Development Status :: 3 - Alpha',
'License :: OSI Approved :: BSD License',
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Software Development :: Libraries :: Python Modules',
],
)
| Add Django < 1.4 requirements | Add Django < 1.4 requirements
| Python | bsd-3-clause | allanlei/django-multitenant | ---
+++
@@ -20,6 +20,9 @@
url = 'https://github.com/allanlei/django-multitenant',
packages=find_packages_in('tenant'),
long_description=read('README.md'),
+ install_requires=[
+ 'Django<1.4',
+ ],
classifiers=[
'Development Status :: 3 - Alpha',
'License :: OSI Approved :: BSD License', |
f58e8e3b4a00069186a3a7f7075a76aa6d95cc60 | setup.py | setup.py | from setuptools import setup, find_packages
setup(
name='panoptes_client',
url='https://github.com/zooniverse/panoptes-python-client',
author='Adam McMaster',
author_email='adam@zooniverse.org',
version='1.1.1',
packages=find_packages(),
include_package_data=True,
install_requires=[
'requests>=2.4.2,<2.22',
'future>=0.16,<0.18',
'python-magic>=0.4,<0.5',
'redo>=1.7',
'six>=1.9',
],
extras_require={
'testing': [
'mock>=2.0,<2.1',
],
'docs': [
'sphinx',
],
':python_version == "2.7"': ['futures'],
}
)
| from setuptools import setup, find_packages
setup(
name='panoptes_client',
url='https://github.com/zooniverse/panoptes-python-client',
author='Adam McMaster',
author_email='adam@zooniverse.org',
version='1.1.1',
packages=find_packages(),
include_package_data=True,
install_requires=[
'requests>=2.4.2,<2.22',
'future>=0.16,<0.18',
'python-magic>=0.4,<0.5',
'redo>=1.7',
'six>=1.9',
],
extras_require={
'testing': [
'mock>=2.0,<3.1',
],
'docs': [
'sphinx',
],
':python_version == "2.7"': ['futures'],
}
)
| Update mock requirement from <2.1,>=2.0 to >=2.0,<3.1 | Update mock requirement from <2.1,>=2.0 to >=2.0,<3.1
Updates the requirements on [mock](https://github.com/testing-cabal/mock) to permit the latest version.
- [Release notes](https://github.com/testing-cabal/mock/releases)
- [Changelog](https://github.com/testing-cabal/mock/blob/master/CHANGELOG.rst)
- [Commits](https://github.com/testing-cabal/mock/compare/2.0.0...3.0.2)
Signed-off-by: dependabot[bot] <5bdcd3c0d4d24ae3e71b3b452a024c6324c7e4bb@dependabot.com> | Python | apache-2.0 | zooniverse/panoptes-python-client | ---
+++
@@ -17,7 +17,7 @@
],
extras_require={
'testing': [
- 'mock>=2.0,<2.1',
+ 'mock>=2.0,<3.1',
],
'docs': [
'sphinx', |
6457af6c631ca92c3c55df225c25cf8130c0aa3b | setup.py | setup.py | # Copyright 2019 The resource-policy-evaluation-library 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.
from __future__ import print_function
from setuptools import setup
setup(
name="rpe-lib",
description="A resource policy evaluation library",
author="Joe Ceresini",
url="https://github.com/forseti-security/resource-policy-evaluation-library",
use_scm_version=True,
setup_requires=['setuptools_scm'],
install_requires=[
'google-api-python-client',
'google-api-python-client-helpers',
'tenacity',
],
packages=[
'rpe',
'rpe.engines',
'rpe.resources',
],
package_data={},
license="Apache 2.0",
keywords="gcp policy enforcement",
)
| # Copyright 2019 The resource-policy-evaluation-library 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.
from __future__ import print_function
from setuptools import setup
setup(
name="rpe-lib",
description="A resource policy evaluation library",
long_description=open('README.md').read(),
author="Joe Ceresini",
url="https://github.com/forseti-security/resource-policy-evaluation-library",
use_scm_version=True,
setup_requires=['setuptools_scm'],
install_requires=[
'google-api-python-client',
'google-api-python-client-helpers',
'tenacity',
],
packages=[
'rpe',
'rpe.engines',
'rpe.resources',
],
package_data={},
license="Apache 2.0",
keywords="gcp policy enforcement",
)
| Read in README.md as long description | Read in README.md as long description | Python | apache-2.0 | forseti-security/resource-policy-evaluation-library | ---
+++
@@ -20,6 +20,7 @@
setup(
name="rpe-lib",
description="A resource policy evaluation library",
+ long_description=open('README.md').read(),
author="Joe Ceresini",
url="https://github.com/forseti-security/resource-policy-evaluation-library",
use_scm_version=True, |
4c629e16c6dcd5ea78ddccca75c0a5cee602cfa6 | setup.py | setup.py | ###############################################################################
# Copyright 2015-2016 University of Florida. All rights reserved.
# This file is part of UF CTS-IT's NACCulator project.
# Use of this source code is governed by the license found in the LICENSE file.
###############################################################################
from setuptools import setup, find_packages
VERSION="0.5.0"
setup(
name="nacculator",
version=VERSION,
author="Taeber Rapczak",
author_email="taeber@ufl.edu",
maintainer="UF CTS-IT",
maintainer_email="ctsit@ctsi.ufl.edu",
url="https://github.com/ctsit/nacculator",
license="BSD 2-Clause",
description="CSV to NACC's UDS3 format converter",
keywords=["REDCap", "NACC", "UDS", "Clinical data"],
download_url="https://github.com/ctsit/nacculator/releases/tag/" + VERSION,
package_dir = {'nacc': 'nacc'},
packages = find_packages(),
entry_points={
"console_scripts": [
"redcap2nacc = nacc.redcap2nacc:main"
]
}
)
| ###############################################################################
# Copyright 2015-2019 University of Florida. All rights reserved.
# This file is part of UF CTS-IT's NACCulator project.
# Use of this source code is governed by the license found in the LICENSE file.
###############################################################################
from setuptools import setup, find_packages
VERSION="0.5.0"
setup(
name="nacculator",
version=VERSION,
author="Taeber Rapczak",
author_email="taeber@ufl.edu",
maintainer="UF CTS-IT",
maintainer_email="ctsit@ctsi.ufl.edu",
url="https://github.com/ctsit/nacculator",
license="BSD 2-Clause",
description="CSV to NACC's UDS3 format converter",
keywords=["REDCap", "NACC", "UDS", "Clinical data"],
download_url="https://github.com/ctsit/nacculator/releases/tag/" + VERSION,
package_dir = {'nacc': 'nacc'},
packages = find_packages(),
entry_points={
"console_scripts": [
"redcap2nacc = nacc.redcap2nacc:main"
]
},
install_requires=[
"cappy @ git+https://github.com/ctsit/cappy.git@1.2.1"
]
)
| Add cappy to dependency list | Add cappy to dependency list
| Python | bsd-2-clause | ctsit/nacculator,ctsit/nacculator,ctsit/nacculator | ---
+++
@@ -1,5 +1,5 @@
###############################################################################
-# Copyright 2015-2016 University of Florida. All rights reserved.
+# Copyright 2015-2019 University of Florida. All rights reserved.
# This file is part of UF CTS-IT's NACCulator project.
# Use of this source code is governed by the license found in the LICENSE file.
###############################################################################
@@ -28,5 +28,9 @@
"console_scripts": [
"redcap2nacc = nacc.redcap2nacc:main"
]
- }
+ },
+
+ install_requires=[
+ "cappy @ git+https://github.com/ctsit/cappy.git@1.2.1"
+ ]
) |
36456b313a24ffb5502a9020217e5172bc73bc15 | setup.py | setup.py | #!/usr/bin/env python
from setuptools import setup
import os
# Utility function to read README file
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name='iss',
version='2.7',
description="Ideally Single Source app for MemberSuite data.",
author='AASHE',
author_email='it@aashe.org',
url='https://github.com/aashe/iss',
long_description=read("README.md"),
packages=[
'iss',
],
include_package_data=True,
classifiers=[
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Framework :: Django',
],
install_requires=[
"beatbox==32.1",
"membersuite_api_client==1.0",
"pycountry",
"pyYAML==3.12",
]
)
| #!/usr/bin/env python
from setuptools import setup
import os
# Utility function to read README file
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name='iss',
version='2.7',
description="Ideally Single Source app for MemberSuite data.",
author='AASHE',
author_email='it@aashe.org',
url='https://github.com/aashe/iss',
long_description=read("README.md"),
packages=[
'iss',
],
include_package_data=True,
classifiers=[
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Framework :: Django',
],
install_requires=[
"beatbox==32.1",
"membersuite_api_client==0.4.4",
"pycountry",
"pyYAML==3.12",
]
)
| Downgrade to v0.4.4 of membersuite-api-client | Downgrade to v0.4.4 of membersuite-api-client
| Python | mit | AASHE/iss | ---
+++
@@ -31,7 +31,7 @@
],
install_requires=[
"beatbox==32.1",
- "membersuite_api_client==1.0",
+ "membersuite_api_client==0.4.4",
"pycountry",
"pyYAML==3.12",
] |
1fc72a38e1e62bde62650356cddf4e22bab21d73 | setup.py | setup.py | import os
from setuptools import setup
base = os.path.dirname(__file__)
mdata = {}
with open(os.path.join(base, 'uniplot', '__about__.py')) as f:
exec(f.read(), mdata)
setup(
name=mdata['__title__'],
version=mdata['__version__'],
author=mdata['__author__'],
author_email=mdata['__email__'],
description=mdata['__description__'],
long_description=open(os.path.join('README.rst')).read(),
url=mdata['__homepage__'],
download_url=mdata['__download__'],
license=mdata['__license__'],
install_requires=['hippy', 'matplotlib'],
)
| import os
from setuptools import setup
base = os.path.dirname(__file__)
mdata = {}
with open(os.path.join(base, 'uniplot', '__about__.py')) as f:
exec(f.read(), mdata)
setup(
name=mdata['__title__'],
version=mdata['__version__'],
author=mdata['__author__'],
author_email=mdata['__email__'],
description=mdata['__description__'],
long_description=open(os.path.join('README.rst')).read(),
url=mdata['__homepage__'],
download_url=mdata['__download__'],
license=mdata['__license__'],
install_requires=['hippy', 'matplotlib'],
extras_require={
'YAML': ['PyYAML'],
'TOML': ['PyTOML'],
},
entry_points={'console_scripts': ['uniplot = uniplot:main'],},
)
| Improve dependencies and add entry_points. | Improve dependencies and add entry_points.
| Python | mit | Sean1708/uniplot | ---
+++
@@ -17,5 +17,11 @@
url=mdata['__homepage__'],
download_url=mdata['__download__'],
license=mdata['__license__'],
+
install_requires=['hippy', 'matplotlib'],
+ extras_require={
+ 'YAML': ['PyYAML'],
+ 'TOML': ['PyTOML'],
+ },
+ entry_points={'console_scripts': ['uniplot = uniplot:main'],},
) |
9b2d464a2562ecf915f22c4664f00af3d66b34ce | setup.py | setup.py | from setuptools import setup, find_packages
import os
scriptnames = ['runElegant.sh',
'sddsprintdata.sh',
'renametolower.sh',
'file2lower.sh',
'lte2json',
'json2lte',
'latticeviewer',
'lv']
def readme():
with open('README.rst') as f:
return f.read()
requiredpackages = ['pyrpn', 'h5py', 'numpy', 'matplotlib', 'pyepics', 'wxPython']
setup(
name = "beamline",
version = "1.3.6",
description = "online model package for electron accelerator",
long_description = readme() + '\n\n',
author = "Tong Zhang",
author_email = "warriorlance@gmail.com",
platforms = ["Linux"],
license = "MIT",
packages = find_packages(),
url = "http://archman.github.io/beamline/",
scripts = [os.path.join('scripts',sn) for sn in scriptnames],
requires = requiredpackages,
install_requires = requiredpackages,
extras_require = {'sdds': ['sddswhl']},
)
| from setuptools import setup, find_packages
import os
scriptnames = ['runElegant.sh',
'sddsprintdata.sh',
'renametolower.sh',
'file2lower.sh',
'lte2json',
'json2lte',
'latticeviewer',
'lv']
def readme():
with open('README.rst') as f:
return f.read()
requiredpackages = ['pyrpn', 'h5py', 'numpy', 'matplotlib', 'pyepics']
setup(
name = "beamline",
version = "1.3.6",
description = "online model package for electron accelerator",
long_description = readme() + '\n\n',
author = "Tong Zhang",
author_email = "warriorlance@gmail.com",
platforms = ["Linux"],
license = "MIT",
packages = find_packages(),
url = "http://archman.github.io/beamline/",
scripts = [os.path.join('scripts',sn) for sn in scriptnames],
install_requires = requiredpackages,
extras_require = {'sdds': ['sddswhl']},
)
| Delete `requires` and `wxPython` dependency | Delete `requires` and `wxPython` dependency
`wxPython` is not easily installable via pip on all Linux distributions without explicitly providing the path to the wheel, yet.
`requires` is obsolete, because of the use of `install_requires` | Python | mit | Archman/beamline | ---
+++
@@ -14,7 +14,7 @@
with open('README.rst') as f:
return f.read()
-requiredpackages = ['pyrpn', 'h5py', 'numpy', 'matplotlib', 'pyepics', 'wxPython']
+requiredpackages = ['pyrpn', 'h5py', 'numpy', 'matplotlib', 'pyepics']
setup(
name = "beamline",
@@ -28,7 +28,6 @@
packages = find_packages(),
url = "http://archman.github.io/beamline/",
scripts = [os.path.join('scripts',sn) for sn in scriptnames],
- requires = requiredpackages,
install_requires = requiredpackages,
extras_require = {'sdds': ['sddswhl']},
) |
dde21c684965c76144adf2654ff04c89ad2c86c8 | setup.py | setup.py | from setuptools import setup
setup(
name="ticket_auth",
version="0.1.0",
packages=['ticket_auth'],
author='Gnarly Chicken',
author_email='gnarlychicken@gmx.com',
test_suite='tests',
license='MIT')
| from setuptools import setup
setup(
name="ticket_auth",
version="0.1.1",
packages=['ticket_auth'],
author='Gnarly Chicken',
author_email='gnarlychicken@gmx.com',
test_suite='tests',
license='MIT')
| Update of version information in preparation for release | Update of version information in preparation for release
| Python | mit | gnarlychicken/ticket_auth | ---
+++
@@ -3,7 +3,7 @@
setup(
name="ticket_auth",
- version="0.1.0",
+ version="0.1.1",
packages=['ticket_auth'],
author='Gnarly Chicken',
author_email='gnarlychicken@gmx.com', |
8e3e72b26e490f35c7e9c4a33ac5314d3be07077 | setup.py | setup.py | #! /usr/bin/env python
from setuptools import setup, find_packages
from setuptools.command.test import test as TestCommand
import os
import sys
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'saleor.settings')
class PyTest(TestCommand):
user_options = [('pytest-args=', 'a', 'Arguments to pass to py.test')]
test_args = []
def initialize_options(self):
TestCommand.initialize_options(self)
self.pytest_args = []
def finalize_options(self):
TestCommand.finalize_options(self)
self.test_args = []
self.test_suite = True
def run_tests(self):
# import here, cause outside the eggs aren't loaded
import pytest
errno = pytest.main(self.pytest_args)
sys.exit(errno)
with open('requirements.in', 'r') as req_file:
requirements = req_file.readlines()
setup(
name='saleor',
author='Mirumee Software',
author_email='hello@mirumee.com',
description="A fork'n'play e-commerce in Django",
license='BSD',
version='0.1.0a0',
url='http://getsaleor.com/',
packages=find_packages(),
include_package_data=True,
install_requires=requirements,
cmdclass={
'test': PyTest},
entry_points={
'console_scripts': ['saleor = saleor:manage']})
| #! /usr/bin/env python
from setuptools import setup, find_packages
from setuptools.command.test import test as TestCommand
import os
import sys
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'saleor.settings')
class PyTest(TestCommand):
user_options = [('pytest-args=', 'a', 'Arguments to pass to py.test')]
test_args = []
def initialize_options(self):
TestCommand.initialize_options(self)
self.pytest_args = []
def finalize_options(self):
TestCommand.finalize_options(self)
self.test_args = []
self.test_suite = True
def run_tests(self):
# import here, cause outside the eggs aren't loaded
import pytest
errno = pytest.main(self.pytest_args)
sys.exit(errno)
with open('requirements.txt', 'r') as req_file:
requirements = req_file.readlines()
setup(
name='saleor',
author='Mirumee Software',
author_email='hello@mirumee.com',
description="A fork'n'play e-commerce in Django",
license='BSD',
version='0.1.0a0',
url='http://getsaleor.com/',
packages=find_packages(),
include_package_data=True,
install_requires=requirements,
cmdclass={
'test': PyTest},
entry_points={
'console_scripts': ['saleor = saleor:manage']})
| Read requirements from the .txt file | Read requirements from the .txt file
| Python | bsd-3-clause | laosunhust/saleor,tfroehlich82/saleor,tfroehlich82/saleor,spartonia/saleor,laosunhust/saleor,maferelo/saleor,maferelo/saleor,mociepka/saleor,rodrigozn/CW-Shop,UITools/saleor,rodrigozn/CW-Shop,car3oon/saleor,itbabu/saleor,itbabu/saleor,rchav/vinerack,jreigel/saleor,car3oon/saleor,jreigel/saleor,HyperManTT/ECommerceSaleor,KenMutemi/saleor,mociepka/saleor,UITools/saleor,KenMutemi/saleor,laosunhust/saleor,UITools/saleor,maferelo/saleor,rodrigozn/CW-Shop,HyperManTT/ECommerceSaleor,UITools/saleor,laosunhust/saleor,spartonia/saleor,itbabu/saleor,HyperManTT/ECommerceSaleor,UITools/saleor,spartonia/saleor,car3oon/saleor,rchav/vinerack,mociepka/saleor,spartonia/saleor,KenMutemi/saleor,tfroehlich82/saleor,rchav/vinerack,jreigel/saleor | ---
+++
@@ -27,7 +27,7 @@
sys.exit(errno)
-with open('requirements.in', 'r') as req_file:
+with open('requirements.txt', 'r') as req_file:
requirements = req_file.readlines()
|
05a0b448b647a7a0d968bfd0019a1520b3496bd1 | setup.py | setup.py | from setuptools import setup, find_packages
setup(
name='panoptes_client',
url='https://github.com/zooniverse/panoptes-python-client',
author='Adam McMaster',
author_email='adam@zooniverse.org',
version='1.1.1',
packages=find_packages(),
include_package_data=True,
install_requires=[
'requests>=2.4.2,<2.22',
'future>=0.16,<0.18',
'python-magic>=0.4,<0.5',
'redo>=1.7',
'six>=1.9',
],
extras_require={
'testing': [
'mock>=2.0,<3.1',
],
'docs': [
'sphinx',
],
':python_version == "2.7"': ['futures'],
}
)
| from setuptools import setup, find_packages
setup(
name='panoptes_client',
url='https://github.com/zooniverse/panoptes-python-client',
author='Adam McMaster',
author_email='adam@zooniverse.org',
version='1.1.1',
packages=find_packages(),
include_package_data=True,
install_requires=[
'requests>=2.4.2,<2.23',
'future>=0.16,<0.18',
'python-magic>=0.4,<0.5',
'redo>=1.7',
'six>=1.9',
],
extras_require={
'testing': [
'mock>=2.0,<3.1',
],
'docs': [
'sphinx',
],
':python_version == "2.7"': ['futures'],
}
)
| Update requests requirement from <2.22,>=2.4.2 to >=2.4.2,<2.23 | Update requests requirement from <2.22,>=2.4.2 to >=2.4.2,<2.23
Updates the requirements on [requests](https://github.com/requests/requests) to permit the latest version.
- [Release notes](https://github.com/requests/requests/releases)
- [Changelog](https://github.com/kennethreitz/requests/blob/master/HISTORY.md)
- [Commits](https://github.com/requests/requests/compare/v2.4.2...v2.22.0)
Signed-off-by: dependabot[bot] <5bdcd3c0d4d24ae3e71b3b452a024c6324c7e4bb@dependabot.com> | Python | apache-2.0 | zooniverse/panoptes-python-client | ---
+++
@@ -9,7 +9,7 @@
packages=find_packages(),
include_package_data=True,
install_requires=[
- 'requests>=2.4.2,<2.22',
+ 'requests>=2.4.2,<2.23',
'future>=0.16,<0.18',
'python-magic>=0.4,<0.5',
'redo>=1.7', |
961f8ab2b664dd24886b5dcf350c437a17fefe1a | setup.py | setup.py | # -*- coding: utf-8 -*-
from setuptools import setup, find_packages
setup(
name='orges',
version='0.0.1',
description='OrgES Package - Organic Computing for Evolution Strategies',
long_description=open('README.rst').read(),
author='Renke Grunwald, Bengt Lüers, Jendrik Poloczek',
author_email='info@orges.org',
url='http://organic-es.tumblr.com/',
#TODO use relative path
license=open('/home/bengt/Arbeit/CI/OrgES/LICENSE').read(),
packages=find_packages(exclude=('tests', 'docs'))
)
| # -*- coding: utf-8 -*-
from setuptools import setup, find_packages, Extension
import os
setup(
name='orges',
version='0.0.1',
description='OrgES Package - Organic Computing for Evolution Strategies',
long_description=open('README.rst').read(),
author='Renke Grunwald, Bengt Lüers, Jendrik Poloczek',
author_email='info@orges.org',
url='http://organic-es.tumblr.com/',
license=open(os.path.join(os.path.dirname(os.path.realpath(__file__)), "LICENSE")).read(),
packages=find_packages(exclude=('tests', 'docs')),
)
| Use relative path in for LICENSE | Use relative path in for LICENSE
| Python | bsd-3-clause | cigroup-ol/metaopt,cigroup-ol/metaopt,cigroup-ol/metaopt | ---
+++
@@ -1,16 +1,16 @@
# -*- coding: utf-8 -*-
-from setuptools import setup, find_packages
+from setuptools import setup, find_packages, Extension
+import os
setup(
- name='orges',
- version='0.0.1',
- description='OrgES Package - Organic Computing for Evolution Strategies',
- long_description=open('README.rst').read(),
- author='Renke Grunwald, Bengt Lüers, Jendrik Poloczek',
- author_email='info@orges.org',
- url='http://organic-es.tumblr.com/',
- #TODO use relative path
- license=open('/home/bengt/Arbeit/CI/OrgES/LICENSE').read(),
- packages=find_packages(exclude=('tests', 'docs'))
+ name='orges',
+ version='0.0.1',
+ description='OrgES Package - Organic Computing for Evolution Strategies',
+ long_description=open('README.rst').read(),
+ author='Renke Grunwald, Bengt Lüers, Jendrik Poloczek',
+ author_email='info@orges.org',
+ url='http://organic-es.tumblr.com/',
+ license=open(os.path.join(os.path.dirname(os.path.realpath(__file__)), "LICENSE")).read(),
+ packages=find_packages(exclude=('tests', 'docs')),
) |
af328240631dd31b405e90c09052c1872490713d | setup.py | setup.py | from distutils.core import setup
setup(
name='gapi',
version='0.5.0',
author='Scott Hendrickson, Josh Montague',
author_email='scott@drskippy.net',
packages=[],
scripts=['search_api.py', 'paged_search_api.py'],
url='https://github.com/DrSkippy27/Gnip-Python-Search-API-Utilities',
download_url='https://github.com/DrSkippy27/Gnip-Python-Search-API-Utilities/tags/',
license='LICENSE.txt',
description='Simple utilties to to explore the Gnip search API',
install_requires=[
"gnacs > 0.7.0",
"sngrams > 0.1.0"
]
)
| from distutils.core import setup
setup(
name='gapi',
version='0.5.2',
author='Scott Hendrickson, Josh Montague',
author_email='scott@drskippy.net',
packages=[],
scripts=['search_api.py', 'paged_search_api.py'],
url='https://github.com/DrSkippy27/Gnip-Python-Search-API-Utilities',
download_url='https://github.com/DrSkippy27/Gnip-Python-Search-API-Utilities/tags/',
license='LICENSE.txt',
description='Simple utilties to to explore the Gnip search API',
install_requires=[
"gnacs > 0.7.0",
"sngrams > 0.1.0",
"reqeusts > 1.2.2"
]
)
| Update pip package. Added proper requests dependency | Update pip package. Added proper requests dependency
| Python | bsd-2-clause | DrSkippy/Gnip-Python-Search-API-Utilities,blehman/Gnip-Python-Search-API-Utilities,DrSkippy/Gnip-Python-Search-API-Utilities,blehman/Gnip-Python-Search-API-Utilities | ---
+++
@@ -2,7 +2,7 @@
setup(
name='gapi',
- version='0.5.0',
+ version='0.5.2',
author='Scott Hendrickson, Josh Montague',
author_email='scott@drskippy.net',
packages=[],
@@ -13,6 +13,7 @@
description='Simple utilties to to explore the Gnip search API',
install_requires=[
"gnacs > 0.7.0",
- "sngrams > 0.1.0"
+ "sngrams > 0.1.0",
+ "reqeusts > 1.2.2"
]
) |
ca29731fd9b8f207a927c8c96c9d9fbb3c98e930 | setup.py | setup.py | from setuptools import setup, find_packages
setup(
name = 'ckanext-archiver',
version = '0.1',
packages = find_packages(),
install_requires = [
'celery>=2.3.3',
'kombu-sqlalchemy>=1.1.0',
'SQLAlchemy>=0.6.6'
],
# metadata for upload to PyPI
author = 'Open Knowledge Foundation',
author_email = 'info@okfn.org',
description = 'Archive ckan resources',
long_description = 'Archive ckan resources',
license = 'MIT',
url='http://ckan.org/wiki/Extensions',
download_url = '',
include_package_data = True,
classifiers = [
'Development Status :: 3 - Alpha',
'Environment :: Console',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Software Development :: Libraries :: Python Modules'
],
entry_points = '''
[paste.paster_command]
archiver = ckanext.archiver.commands:Archiver
'''
)
| from setuptools import setup, find_packages
setup(
name = 'ckanext-archiver',
version = '0.1',
packages = find_packages(),
install_requires = [
'celery>=2.3.3',
'kombu-sqlalchemy>=1.1.0',
'SQLAlchemy>=0.6.6',
'requests==0.6.1'
],
# metadata for upload to PyPI
author = 'Open Knowledge Foundation',
author_email = 'info@okfn.org',
description = 'Archive ckan resources',
long_description = 'Archive ckan resources',
license = 'MIT',
url='http://ckan.org/wiki/Extensions',
download_url = '',
include_package_data = True,
classifiers = [
'Development Status :: 3 - Alpha',
'Environment :: Console',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Software Development :: Libraries :: Python Modules'
],
entry_points = '''
[paste.paster_command]
archiver = ckanext.archiver.commands:Archiver
'''
)
| Add requests module to installation requirements | Add requests module to installation requirements
| Python | mit | ckan/ckanext-archiver,datagovuk/ckanext-archiver,DanePubliczneGovPl/ckanext-archiver,DanePubliczneGovPl/ckanext-archiver,datagovuk/ckanext-archiver,ckan/ckanext-archiver,ckan/ckanext-archiver,datagovuk/ckanext-archiver,DanePubliczneGovPl/ckanext-archiver | ---
+++
@@ -7,7 +7,8 @@
install_requires = [
'celery>=2.3.3',
'kombu-sqlalchemy>=1.1.0',
- 'SQLAlchemy>=0.6.6'
+ 'SQLAlchemy>=0.6.6',
+ 'requests==0.6.1'
],
# metadata for upload to PyPI
author = 'Open Knowledge Foundation', |
13a29de045e1386dde2be6185f5f05095f3d4c2d | setup.py | setup.py | from os import path, pardir, chdir
from setuptools import setup, find_packages
README = open(path.join(path.dirname(__file__), 'README.rst')).read()
# allow setup.py to be run from any path
chdir(path.normpath(path.join(path.abspath(__file__), pardir)))
setup(
name='django-perimeter',
version='0.9',
packages=find_packages(),
include_package_data=True,
license='MIT',
description='Site-wide perimeter access control for Django projects.',
long_description=README,
url='https://github.com/yunojuno/django-perimeter',
author='YunoJuno',
author_email='code@yunojuno.com',
maintainer='YunoJuno',
maintainer_email='code@yunojuno.com',
install_requires=['Django>=1.8'],
classifiers=[
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.6',
'Topic :: Internet :: WWW/HTTP',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
],
)
| from os import path, pardir, chdir
from setuptools import setup, find_packages
README = open(path.join(path.dirname(__file__), 'README.rst')).read()
# allow setup.py to be run from any path
chdir(path.normpath(path.join(path.abspath(__file__), pardir)))
setup(
name='django-perimeter',
version='0.9',
packages=find_packages(),
include_package_data=True,
license='MIT',
description='Site-wide perimeter access control for Django projects.',
long_description=README,
url='https://github.com/yunojuno/django-perimeter',
author='YunoJuno',
author_email='code@yunojuno.com',
maintainer='YunoJuno',
maintainer_email='code@yunojuno.com',
install_requires=['Django>=1.8'],
classifiers=[
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.6',
'Topic :: Internet :: WWW/HTTP',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
],
)
| Update license classifier to MIT | Update license classifier to MIT
| Python | mit | yunojuno/django-perimeter,yunojuno/django-perimeter | ---
+++
@@ -24,7 +24,7 @@
'Environment :: Web Environment',
'Framework :: Django',
'Intended Audience :: Developers',
- 'License :: OSI Approved :: MIT',
+ 'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2.7', |
f87c291ce7ee7a54a987f3d8bd1a43e1cee2b6a0 | setup.py | setup.py |
from setuptools import setup
setup(
name = 'diabric',
version = '0.1',
license = 'MIT',
description = 'Diabolically atomic Python Fabric fabfile tasks and utilities.',
long_description = open('README.md').read(),
keywords = 'fabric fabfile boto ec2 virtualenv python wsgi webapp deployment',
url = 'https://github.com/todddeluca/diabric',
author = 'Todd Francis DeLuca',
author_email = 'todddeluca@yahoo.com',
classifiers = ['License :: OSI Approved :: MIT License',
'Development Status :: 2 - Pre-Alpha',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
],
packages = ['diabric'],
install_requires = ['setuptools', 'Fabric>=1.4','boto>=2.3'],
include_package_data = True,
package_data = {'' : ['README.md', 'LICENSE.txt']},
)
|
import os
from setuptools import setup, find_packages
setup(
name = 'diabric',
version = '0.1.1',
license = 'MIT',
description = 'Diabolically atomic Python Fabric fabfile tasks and utilities.',
long_description = open(os.path.join(os.path.dirname(__file__), 'README.md')).read(),
keywords = 'fabric fabfile boto ec2 virtualenv python wsgi webapp deployment',
url = 'https://github.com/todddeluca/diabric',
author = 'Todd Francis DeLuca',
author_email = 'todddeluca@yahoo.com',
classifiers = ['License :: OSI Approved :: MIT License',
'Development Status :: 2 - Pre-Alpha',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
],
install_requires = ['setuptools', 'Fabric>=1.4','boto>=2.3'],
packages = ['diabric'],
)
| Fix pip installation failure involving README.md | Fix pip installation failure involving README.md
Two bugs with "easy" fixes:
- README.md was not being included in the source distribution. I'm not
sure what I did to fix it, since the distutils/setuptools/distribute
docs are quite incomplete and convoluted on something so
straight-forward. The fix: I removed some 'package_data' type lines
from setup.py, and now LICENSE.txt and README.md are being included.
- In addition to README.md not being included in the distribution
(tar.gz file) it was being read by setup.py as open('README.md'),
which is relative to the current working directory, which I'm not sure
pip sets to the directory containing setup.py. The fix is to open the
file using the directory of setup.py, via the __file__ attribute.
| Python | mit | todddeluca/diabric | ---
+++
@@ -1,12 +1,13 @@
-from setuptools import setup
+import os
+from setuptools import setup, find_packages
setup(
name = 'diabric',
- version = '0.1',
+ version = '0.1.1',
license = 'MIT',
description = 'Diabolically atomic Python Fabric fabfile tasks and utilities.',
- long_description = open('README.md').read(),
+ long_description = open(os.path.join(os.path.dirname(__file__), 'README.md')).read(),
keywords = 'fabric fabfile boto ec2 virtualenv python wsgi webapp deployment',
url = 'https://github.com/todddeluca/diabric',
author = 'Todd Francis DeLuca',
@@ -16,9 +17,7 @@
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
],
+ install_requires = ['setuptools', 'Fabric>=1.4','boto>=2.3'],
packages = ['diabric'],
- install_requires = ['setuptools', 'Fabric>=1.4','boto>=2.3'],
- include_package_data = True,
- package_data = {'' : ['README.md', 'LICENSE.txt']},
)
|
e0bbd05c252438d157de6f9b85079848920f574e | setup.py | setup.py | from setuptools import setup, find_packages
def listify(filename):
return filter(None, open(filename, 'r').readlines())
setup(
name="python-smpp",
version="0.1.6a",
url='http://github.com/praekelt/python-smpp',
license='BSD',
description="Python SMPP Library",
long_description=open('README.rst', 'r').read(),
author='Praekelt Foundation',
author_email='dev@praekeltfoundation.org',
packages=find_packages(),
install_requires=['setuptools'].extend(listify('requirements.pip')),
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Software Development :: Libraries :: Python Modules',
]
)
| import os
from setuptools import setup, find_packages
def listify(filename):
return filter(None, open(filename, 'r').readlines())
def read_file(filename):
filepath = os.path.join(os.path.dirname(__file__), filename)
return open(filepath, 'r').read()
setup(
name="python-smpp",
version="0.1.6a",
url='http://github.com/praekelt/python-smpp',
license='BSD',
description="Python SMPP Library",
long_description=read_file('README.rst'),
author='Praekelt Foundation',
author_email='dev@praekeltfoundation.org',
packages=find_packages(),
install_requires=['setuptools'].extend(listify('requirements.pip')),
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'License :: OSI Approved :: BSD License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Software Development :: Libraries :: Python Modules',
]
)
| Use absolute path for reading description from file (thanks @hodgestar) | Use absolute path for reading description from file (thanks @hodgestar)
| Python | bsd-3-clause | praekelt/python-smpp,praekelt/python-smpp | ---
+++
@@ -1,8 +1,14 @@
+import os
from setuptools import setup, find_packages
def listify(filename):
return filter(None, open(filename, 'r').readlines())
+
+
+def read_file(filename):
+ filepath = os.path.join(os.path.dirname(__file__), filename)
+ return open(filepath, 'r').read()
setup(
name="python-smpp",
@@ -10,7 +16,7 @@
url='http://github.com/praekelt/python-smpp',
license='BSD',
description="Python SMPP Library",
- long_description=open('README.rst', 'r').read(),
+ long_description=read_file('README.rst'),
author='Praekelt Foundation',
author_email='dev@praekeltfoundation.org',
packages=find_packages(), |
c015a16ef24ae8e6b07c1fc74a613ded75a6084a | setup.py | setup.py | #!/usr/bin/env python
from setuptools import setup, find_packages
setup(
name='organizations-edx-platform-extensions',
version='1.2.3',
description='Organization management extension for edX platform',
long_description=open('README.rst').read(),
author='edX',
url='https://github.com/edx-solutions/organizations-edx-platform-extensions.git',
packages=find_packages(),
include_package_data=True,
install_requires=[
"django>=1.8",
],
)
| #!/usr/bin/env python
from setuptools import setup, find_packages
setup(
name='organizations-edx-platform-extensions',
version='1.2.6',
description='Organization management extension for edX platform',
long_description=open('README.rst').read(),
author='edX',
url='https://github.com/edx-solutions/organizations-edx-platform-extensions.git',
packages=find_packages(),
include_package_data=True,
install_requires=[
"django>=1.8",
],
)
| Delete organization field API issues | Delete organization field API issues
Changed the database field to unlimited sized field which is TextField in the case of django=1.8. fixed the delete api checks and randomized the key for attributes.
[YONK-1151]
| Python | agpl-3.0 | edx-solutions/organizations-edx-platform-extensions | ---
+++
@@ -4,7 +4,7 @@
setup(
name='organizations-edx-platform-extensions',
- version='1.2.3',
+ version='1.2.6',
description='Organization management extension for edX platform',
long_description=open('README.rst').read(),
author='edX', |
96871ab62c6635c396325591c84bed243745fd16 | setup.py | setup.py | from setuptools import setup
setup(
name='icapservice',
version='0.1.1',
description='ICAP service library for Python',
author='Giles Brown',
author_email='giles_brown@hotmail.com',
url='https://github.com/gilesbrown/icapservice',
license='MIT',
packages=['icapservice'],
zip_safe=False,
install_requires=['six', 'brotlipy'],
include_package_data=True,
package_data={'': ['LICENSE']},
classifiers=(
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'Natural Language :: English',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python',
'Programming Language :: Python :: 2.7',
#'Programming Language :: Python :: 3',
#'Programming Language :: Python :: 3.4',
#'Programming Language :: Python :: 3.5',
),
)
| from setuptools import setup
setup(
name='icapservice',
version='0.2.0',
description='ICAP service library for Python',
author='Giles Brown',
author_email='giles_brown@hotmail.com',
url='https://github.com/gilesbrown/icapservice',
license='MIT',
packages=['icapservice'],
zip_safe=False,
install_requires=['six', 'brotlipy'],
include_package_data=True,
package_data={'': ['LICENSE']},
classifiers=(
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers',
'Natural Language :: English',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python',
'Programming Language :: Python :: 2.7',
#'Programming Language :: Python :: 3',
#'Programming Language :: Python :: 3.4',
#'Programming Language :: Python :: 3.5',
),
)
| Add support for brotli content encoding and alias for none | Add support for brotli content encoding and alias for none
| Python | mit | gilesbrown/python-icapservice,gilesbrown/python-icapservice | ---
+++
@@ -3,7 +3,7 @@
setup(
name='icapservice',
- version='0.1.1',
+ version='0.2.0',
description='ICAP service library for Python',
author='Giles Brown',
author_email='giles_brown@hotmail.com', |
7b9f9fe1816233d59d32fc41c737250f15fd1b7c | setup.py | setup.py | import os
from setuptools import setup
setup(
name='algorithmia',
version='0.9.2',
description='Algorithmia Python Client',
long_description='Algorithmia Python Client is a client library for accessing Algorithmia from python code. This library also gets bundled with any Python algorithms in Algorithmia.',
url='http://github.com/algorithmiaio/algorithmia-python',
license='MIT',
author='Algorithmia',
author_email='support@algorithmia.com',
packages=['Algorithmia'],
include_package_data=True,
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'Natural Language :: English',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Topic :: Software Development :: Libraries :: Python Modules',
],
)
| import os
from setuptools import setup
setup(
name='algorithmia',
version='0.9.0',
description='Algorithmia Python Client',
long_description='Algorithmia Python Client is a client library for accessing Algorithmia from python code. This library also gets bundled with any Python algorithms in Algorithmia.',
url='http://github.com/algorithmiaio/algorithmia-python',
license='MIT',
author='Algorithmia',
author_email='support@algorithmia.com',
packages=['Algorithmia'],
include_package_data=True,
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'Natural Language :: English',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Topic :: Software Development :: Libraries :: Python Modules',
],
)
| Move back to 0.9.0 for prod PyPi upload | Move back to 0.9.0 for prod PyPi upload
| Python | mit | algorithmiaio/algorithmia-python | ---
+++
@@ -4,7 +4,7 @@
setup(
name='algorithmia',
- version='0.9.2',
+ version='0.9.0',
description='Algorithmia Python Client',
long_description='Algorithmia Python Client is a client library for accessing Algorithmia from python code. This library also gets bundled with any Python algorithms in Algorithmia.',
url='http://github.com/algorithmiaio/algorithmia-python', |
5d4baf4d9b2c4967276f188a496d04062041c26c | setup.py | setup.py | from distutils.core import setup
from distutils.extension import Extension
from Cython.Build import cythonize
setup(
name='cygroonga',
version='0.1.0',
ext_modules=cythonize([
Extension("cygroonga", ["cygroonga.pyx"],
libraries=["groonga"])
]),
install_requires=[
'Cython',
],
)
| from distutils.core import setup
from distutils.extension import Extension
from Cython.Build import cythonize
setup(
name='cygroonga',
version='0.1.0',
ext_modules=cythonize([
Extension("cygroonga", ["cygroonga.pyx"],
libraries=["groonga"])
]),
install_requires=[
'Cython==0.22.1',
],
)
| Add cython version to install_requires | Add cython version to install_requires
| Python | apache-2.0 | hnakamur/cygroonga | ---
+++
@@ -10,6 +10,6 @@
libraries=["groonga"])
]),
install_requires=[
- 'Cython',
+ 'Cython==0.22.1',
],
) |
65e72e330bfaf1c8e2dd03cb809ad697a5f9af35 | setup.py | setup.py | from setuptools import setup, find_packages
import board
setup(
name='django-board',
version=board.__version__,
description='A Django app for managing an organisation\'s board members page.',
long_description=open('README.md').read(),
author='Dominic Rodger',
author_email='internet@dominicrodger.com',
url='http://github.com/dominicrodger/django-board',
license='BSD',
packages=find_packages(),
include_package_data=True,
package_data={'': ['README.md']},
zip_safe=False,
install_requires=['Django', 'South', 'sorl-thumbnail',]
)
| from setuptools import setup, find_packages
import board
setup(
name='django-board',
version=board.__version__,
description='A Django app for managing an organisation\'s board members page.',
long_description=open('README.md').read(),
author='Dominic Rodger',
author_email='internet@dominicrodger.com',
url='http://github.com/dominicrodger/django-board',
license='BSD',
packages=find_packages(),
include_package_data=True,
package_data={'': ['README.md']},
zip_safe=False,
install_requires=[
'Django==1.4.3',
'South==0.76',
'sorl-thumbnail==11.12',
]
)
| Use actual version numbers for dependencies | Use actual version numbers for dependencies | Python | mit | dominicrodger/django-board,dominicrodger/django-board | ---
+++
@@ -15,5 +15,9 @@
include_package_data=True,
package_data={'': ['README.md']},
zip_safe=False,
- install_requires=['Django', 'South', 'sorl-thumbnail',]
+ install_requires=[
+ 'Django==1.4.3',
+ 'South==0.76',
+ 'sorl-thumbnail==11.12',
+ ]
) |
d7df3f73b521327a6a7879d47ced1cc8c7a47a2d | tensorbayes/layers/sample.py | tensorbayes/layers/sample.py | import tensorflow as tf
def GaussianSample(mean, var, scope):
with tf.name_scope(scope):
return tf.random_normal(tf.shape(mean), mean, tf.sqrt(var))
| import tensorflow as tf
def GaussianSample(mean, var, scope):
with tf.name_scope(scope):
return tf.random_normal(tf.shape(mean), mean, tf.sqrt(var))
def Duplicate(x, n_iw=1, n_mc=1, scope=None):
""" Duplication function adds samples according to n_iw and n_mc.
This function is specifically for importance weighting and monte carlo
sampling.
"""
with tf.name_scope(scope):
sample_shape = x._shape_as_list()[1:]
y = tf.reshape(x, [1, 1, -1] + sample_shape)
y = tf.tile(y, [n_iw, n_mc, 1] + [1] * len(sample_shape))
y = tf.reshape(y, [-1] + sample_shape)
return y
| Add importance weighting and monte carlo feature | Add importance weighting and monte carlo feature
| Python | mit | RuiShu/tensorbayes | ---
+++
@@ -3,3 +3,16 @@
def GaussianSample(mean, var, scope):
with tf.name_scope(scope):
return tf.random_normal(tf.shape(mean), mean, tf.sqrt(var))
+
+def Duplicate(x, n_iw=1, n_mc=1, scope=None):
+ """ Duplication function adds samples according to n_iw and n_mc.
+
+ This function is specifically for importance weighting and monte carlo
+ sampling.
+ """
+ with tf.name_scope(scope):
+ sample_shape = x._shape_as_list()[1:]
+ y = tf.reshape(x, [1, 1, -1] + sample_shape)
+ y = tf.tile(y, [n_iw, n_mc, 1] + [1] * len(sample_shape))
+ y = tf.reshape(y, [-1] + sample_shape)
+ return y |
c9d992cd69fd1ec5c0b8655b379862527b452fb6 | geotrek/settings/dev.py | geotrek/settings/dev.py | from .default import * # NOQA
#
# Django Development
# ..........................
DEBUG = True
TEMPLATE_DEBUG = True
SOUTH_TESTS_MIGRATE = False # Tested at settings.tests
#
# Developper Toolbar
# ..........................
INSTALLED_APPS = (
# 'debug_toolbar',
'django_extensions',
) + INSTALLED_APPS
#
# Use some default tiles
# ..........................
LEAFLET_CONFIG['TILES'] = [
(gettext_noop('Scan'), 'http://{s}.tile.osm.org/{z}/{x}/{y}.png', '(c) OpenStreetMap Contributors'),
(gettext_noop('Ortho'), 'http://{s}.tiles.mapbox.com/v3/openstreetmap.map-4wvf9l0l/{z}/{x}/{y}.jpg', '(c) MapBox'),
]
LEAFLET_CONFIG['OVERLAYS'] = [
(gettext_noop('Coeur de parc'), 'http://{s}.tilestream.makina-corpus.net/v2/coeur-ecrins/{z}/{x}/{y}.png', 'Ecrins'),
]
LEAFLET_CONFIG['SRID'] = 3857
LOGGING['loggers']['geotrek']['level'] = 'DEBUG'
LOGGING['loggers']['']['level'] = 'DEBUG'
| from .default import * # NOQA
#
# Django Development
# ..........................
DEBUG = True
TEMPLATE_DEBUG = True
SOUTH_TESTS_MIGRATE = False # Tested at settings.tests
#
# Developper Toolbar
# ..........................
INSTALLED_APPS = (
# 'debug_toolbar',
'django_extensions',
) + INSTALLED_APPS
#
# Use some default tiles
# ..........................
LEAFLET_CONFIG['TILES'] = [
(gettext_noop('Scan'), 'http://{s}.tile.osm.org/{z}/{x}/{y}.png', '(c) OpenStreetMap Contributors'),
(gettext_noop('Ortho'), 'http://{s}.tiles.mapbox.com/v3/openstreetmap.map-4wvf9l0l/{z}/{x}/{y}.jpg', '(c) MapBox'),
]
LEAFLET_CONFIG['OVERLAYS'] = [
(gettext_noop('Coeur de parc'), 'http://{s}.tilestream.makina-corpus.net/v2/coeur-ecrins/{z}/{x}/{y}.png', 'Ecrins'),
]
LEAFLET_CONFIG['SRID'] = 3857
LOGGING['loggers']['geotrek']['level'] = 'DEBUG'
LOGGING['loggers']['']['level'] = 'DEBUG'
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
| Set up console email backend in debug mode | Set up console email backend in debug mode
| Python | bsd-2-clause | makinacorpus/Geotrek,Anaethelion/Geotrek,GeotrekCE/Geotrek-admin,makinacorpus/Geotrek,GeotrekCE/Geotrek-admin,makinacorpus/Geotrek,Anaethelion/Geotrek,GeotrekCE/Geotrek-admin,johan--/Geotrek,johan--/Geotrek,johan--/Geotrek,GeotrekCE/Geotrek-admin,makinacorpus/Geotrek,Anaethelion/Geotrek,Anaethelion/Geotrek,johan--/Geotrek | ---
+++
@@ -34,3 +34,5 @@
LOGGING['loggers']['geotrek']['level'] = 'DEBUG'
LOGGING['loggers']['']['level'] = 'DEBUG'
+
+EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend' |
4ca8b6140ea68ee3a4824220590ecd7150cf90a4 | tor.py | tor.py | import socks
import socket
class Tor(object):
"""Tor class for socks proxy and controller"""
def __init__(self, socks_port=9050):
self.socks_port = socks_port
self.default_socket = socket.socket
| import socks
import socket
class Tor(object):
"""Tor class for socks proxy and controller"""
def __init__(self, socks_port=9050):
self.socks_port = socks_port
self.default_socket = socket.socket
def connect(self):
"""connect to Tor socks proxy"""
socks.set_default_proxy(socks.SOCKS5, "127.0.0.1", self.socks_port)
socket.socket = socks.socksocket
def disconnect(self):
"""disconnect Tor socks proxy"""
socket.socket = self.default_socket
| Add connect and disconnect methods | Add connect and disconnect methods
| Python | mit | MA3STR0/simpletor | ---
+++
@@ -7,3 +7,12 @@
def __init__(self, socks_port=9050):
self.socks_port = socks_port
self.default_socket = socket.socket
+
+ def connect(self):
+ """connect to Tor socks proxy"""
+ socks.set_default_proxy(socks.SOCKS5, "127.0.0.1", self.socks_port)
+ socket.socket = socks.socksocket
+
+ def disconnect(self):
+ """disconnect Tor socks proxy"""
+ socket.socket = self.default_socket |
0af1b0bc4448a289c0e21b32face5545ce5d13c7 | test_quick_sort.py | test_quick_sort.py | from random import shuffle
import pytest
from quick_sort import quick_srt
def test_quick_srt():
expected = range(20)
actual = expected[:]
shuffle(actual)
quick_srt(actual)
assert expected == actual
def test_quick_srt_with_duplicates():
expected = [1, 3, 3, 6, 7, 8, 8, 8]
actual = expected[:]
shuffle(actual)
quick_srt(actual)
assert expected == actual
def test_quick_sort_wrong_type():
with pytest.raises(TypeError):
quick_srt(15)
| Add basic tests for quick sort | Add basic tests for quick sort
| Python | mit | jonathanstallings/data-structures | ---
+++
@@ -0,0 +1,26 @@
+from random import shuffle
+import pytest
+
+from quick_sort import quick_srt
+
+
+def test_quick_srt():
+ expected = range(20)
+ actual = expected[:]
+ shuffle(actual)
+ quick_srt(actual)
+ assert expected == actual
+
+
+def test_quick_srt_with_duplicates():
+ expected = [1, 3, 3, 6, 7, 8, 8, 8]
+ actual = expected[:]
+ shuffle(actual)
+ quick_srt(actual)
+ assert expected == actual
+
+
+def test_quick_sort_wrong_type():
+ with pytest.raises(TypeError):
+ quick_srt(15)
+ | |
abebc8a1153a9529a0f805207492cf2f5edece62 | cbor2/__init__.py | cbor2/__init__.py | from .decoder import load, loads, CBORDecoder, CBORDecodeError # noqa
from .encoder import dump, dumps, CBOREncoder, CBOREncodeError, shareable_encoder # noqa
from .types import CBORTag, CBORSimpleValue, undefined # noqa
| from .decoder import load, loads, CBORDecoder # noqa
from .encoder import dump, dumps, CBOREncoder, shareable_encoder # noqa
from .types import ( # noqa
CBORError,
CBOREncodeError,
CBORDecodeError,
CBORTag,
CBORSimpleValue,
undefined
)
try:
from _cbor2 import * # noqa
except ImportError:
# Couldn't import the optimized C version; ignore the failure and leave the
# pure Python implementations in place.
pass
else:
# The pure Python implementations are replaced with the optimized C
# variants, but we still need to create the encoder dictionaries for the C
# variant here (this is much simpler than doing so in C, and doesn't affect
# overall performance as it's a one-off initialization cost).
def _init_cbor2():
from collections import OrderedDict
from .encoder import default_encoders, canonical_encoders
from .types import CBORTag, CBORSimpleValue, undefined # noqa
import _cbor2
_cbor2.default_encoders = OrderedDict([
((
_cbor2.CBORSimpleValue if type_ is CBORSimpleValue else
_cbor2.CBORTag if type_ is CBORTag else
type(_cbor2.undefined) if type_ is type(undefined) else
type_
), getattr(_cbor2.CBOREncoder, method.__name__))
for type_, method in default_encoders.items()
])
_cbor2.canonical_encoders = OrderedDict([
((
_cbor2.CBORSimpleValue if type_ is CBORSimpleValue else
_cbor2.CBORTag if type_ is CBORTag else
type(_cbor2.undefined) if type_ is type(undefined) else
type_
), getattr(_cbor2.CBOREncoder, method.__name__))
for type_, method in canonical_encoders.items()
])
_init_cbor2()
del _init_cbor2
| Make the package import both variants | Make the package import both variants
Favouring the C variant where it successfully imports. This commit also
handles generating the encoding dictionaries for the C variant from
those defined for the Python variant (this is much simpler than doing
this in C).
| Python | mit | agronholm/cbor2,agronholm/cbor2,agronholm/cbor2 | ---
+++
@@ -1,3 +1,47 @@
-from .decoder import load, loads, CBORDecoder, CBORDecodeError # noqa
-from .encoder import dump, dumps, CBOREncoder, CBOREncodeError, shareable_encoder # noqa
-from .types import CBORTag, CBORSimpleValue, undefined # noqa
+from .decoder import load, loads, CBORDecoder # noqa
+from .encoder import dump, dumps, CBOREncoder, shareable_encoder # noqa
+from .types import ( # noqa
+ CBORError,
+ CBOREncodeError,
+ CBORDecodeError,
+ CBORTag,
+ CBORSimpleValue,
+ undefined
+)
+
+try:
+ from _cbor2 import * # noqa
+except ImportError:
+ # Couldn't import the optimized C version; ignore the failure and leave the
+ # pure Python implementations in place.
+ pass
+else:
+ # The pure Python implementations are replaced with the optimized C
+ # variants, but we still need to create the encoder dictionaries for the C
+ # variant here (this is much simpler than doing so in C, and doesn't affect
+ # overall performance as it's a one-off initialization cost).
+ def _init_cbor2():
+ from collections import OrderedDict
+ from .encoder import default_encoders, canonical_encoders
+ from .types import CBORTag, CBORSimpleValue, undefined # noqa
+ import _cbor2
+ _cbor2.default_encoders = OrderedDict([
+ ((
+ _cbor2.CBORSimpleValue if type_ is CBORSimpleValue else
+ _cbor2.CBORTag if type_ is CBORTag else
+ type(_cbor2.undefined) if type_ is type(undefined) else
+ type_
+ ), getattr(_cbor2.CBOREncoder, method.__name__))
+ for type_, method in default_encoders.items()
+ ])
+ _cbor2.canonical_encoders = OrderedDict([
+ ((
+ _cbor2.CBORSimpleValue if type_ is CBORSimpleValue else
+ _cbor2.CBORTag if type_ is CBORTag else
+ type(_cbor2.undefined) if type_ is type(undefined) else
+ type_
+ ), getattr(_cbor2.CBOREncoder, method.__name__))
+ for type_, method in canonical_encoders.items()
+ ])
+ _init_cbor2()
+ del _init_cbor2 |
27f6f1a352ddb72e48550e7d656a3882126d6de6 | pythonic_rules.example/upload/__init__.py | pythonic_rules.example/upload/__init__.py | #!/usr/bin/python
from config import INTERFACES
from built_in_classes import RootHTBClass
from .upload import Interactive, TCPACK, SSH, HTTP, Default
def apply_qos():
public_if = INTERFACES["public_if"]
root_class = RootHTBClass(
interface=public_if["name"],
rate=public_if["speed"],
burst=public_if["speed"]/8,
qdisc_prefix_id="1:",
default=1500
)
# root_class.add_child(Interactive())
# root_class.add_child(TCPACK())
# root_class.add_child(SSH())
# root_class.add_child(HTTP())
root_class.add_child(Default())
root_class.apply_qos()
| #!/usr/bin/python
from config import INTERFACES
from built_in_classes import RootHTBClass
from .upload import Interactive, TCPACK, SSH, HTTP, Default
def apply_qos():
public_if = INTERFACES["public_if"]
root_class = RootHTBClass(
interface=public_if["name"],
rate=public_if["speed"],
burst=public_if["speed"]/8,
qdisc_prefix_id="1:",
default=1500
)
root_class.add_child(Interactive())
root_class.add_child(TCPACK())
root_class.add_child(SSH())
root_class.add_child(HTTP())
root_class.add_child(Default())
root_class.apply_qos()
| Enable all rules in pythonic_rules | Enable all rules in pythonic_rules
Has been disabled to avoid errors until the new design was nos finished.
| Python | bsd-2-clause | Anthony25/python_tc_qos | ---
+++
@@ -14,10 +14,10 @@
qdisc_prefix_id="1:",
default=1500
)
- # root_class.add_child(Interactive())
- # root_class.add_child(TCPACK())
- # root_class.add_child(SSH())
- # root_class.add_child(HTTP())
+ root_class.add_child(Interactive())
+ root_class.add_child(TCPACK())
+ root_class.add_child(SSH())
+ root_class.add_child(HTTP())
root_class.add_child(Default())
root_class.apply_qos() |
ed279b7f2cfcfd4abdf1da36d8406a3f63603529 | dss/mobile/__init__.py | dss/mobile/__init__.py | """ TCP Server for mobile streaming
"""
try:
import SocketServer as socketserver
except ImportError:
import socketserver
from dss.tools import thread, show
from dss.config import config
from .handler import MediaHandler
class ThreadedTCPServer(socketserver.ThreadingMixIn, socketserver.TCPServer):
daemon_threads = True
is_running = False
class TCPServer(object):
def __init__(self):
self.host = config.get('local', 'addr')
self.port = config.getint('local', 'tcp_port')
self.cond = thread.Condition()
self._server = None
def start(self, create_thread=True):
if not create_thread:
self.run_server()
return
with self.cond:
thread.Thread(self.run_server, name='TCP Server').start()
self.cond.wait()
return self
def run_server(self):
self._server = ThreadedTCPServer((self.host, self.port), MediaHandler)
show('Listening at {0.host}:{0.port} (tcp)'.format(self))
with self.cond:
self.cond.notify_all()
self._server.is_running = True
self._server.serve_forever()
def stop(self):
self._server.is_running = False
self._server.shutdown()
| """ TCP Server for mobile streaming
"""
try:
import SocketServer as socketserver
except ImportError:
import socketserver
from dss.tools import thread, show
from dss.config import config
from dss.storage import db
from .handler import MediaHandler
# If some streams are active, the program did no close properly.
db.mobile.update({'active': True}, {'active': False})
class ThreadedTCPServer(socketserver.ThreadingMixIn, socketserver.TCPServer):
daemon_threads = True
is_running = False
class TCPServer(object):
def __init__(self):
self.host = config.get('local', 'addr')
self.port = config.getint('local', 'tcp_port')
self.cond = thread.Condition()
self._server = None
def start(self, create_thread=True):
if not create_thread:
self.run_server()
return
with self.cond:
thread.Thread(self.run_server, name='TCP Server').start()
self.cond.wait()
return self
def run_server(self):
self._server = ThreadedTCPServer((self.host, self.port), MediaHandler)
show('Listening at {0.host}:{0.port} (tcp)'.format(self))
with self.cond:
self.cond.notify_all()
self._server.is_running = True
self._server.serve_forever()
def stop(self):
self._server.is_running = False
self._server.shutdown()
| Mark all mobile streams as inactive when the program starts. | Mark all mobile streams as inactive when the program starts.
| Python | bsd-3-clause | terabit-software/dynamic-stream-server,hmoraes/dynamic-stream-server,terabit-software/dynamic-stream-server,hmoraes/dynamic-stream-server,terabit-software/dynamic-stream-server,terabit-software/dynamic-stream-server,hmoraes/dynamic-stream-server,hmoraes/dynamic-stream-server | ---
+++
@@ -9,7 +9,12 @@
from dss.tools import thread, show
from dss.config import config
+from dss.storage import db
from .handler import MediaHandler
+
+
+# If some streams are active, the program did no close properly.
+db.mobile.update({'active': True}, {'active': False})
class ThreadedTCPServer(socketserver.ThreadingMixIn, socketserver.TCPServer): |
1e1c8a80199eacb64783a3fa69673059aa04da90 | boardinghouse/tests/test_template_tag.py | boardinghouse/tests/test_template_tag.py | from django.test import TestCase
from .models import AwareModel, NaiveModel
from ..templatetags.boardinghouse import *
class TestTemplateTags(TestCase):
def test_is_schema_aware_filter(self):
self.assertTrue(is_schema_aware(AwareModel()))
self.assertFalse(is_schema_aware(NaiveModel()))
def test_is_shared_model_filter(self):
self.assertFalse(is_shared_model(AwareModel()))
self.assertTrue(is_shared_model(NaiveModel()))
def test_schema_name_filter(self):
Schema.objects.create(name='Schema Name', schema='foo')
self.assertEquals('Schema Name', schema_name('foo'))
self.assertEquals('no schema', schema_name(None))
self.assertEquals('no schema', schema_name(''))
self.assertEquals('no schema', schema_name(False))
self.assertEquals('no schema', schema_name('foobar'))
self.assertEquals('no schema', schema_name('foo_'))
self.assertEquals('no schema', schema_name('foofoo')) | from django.test import TestCase
from .models import AwareModel, NaiveModel
from ..templatetags.boardinghouse import schema_name, is_schema_aware, is_shared_model
from ..models import Schema
class TestTemplateTags(TestCase):
def test_is_schema_aware_filter(self):
self.assertTrue(is_schema_aware(AwareModel()))
self.assertFalse(is_schema_aware(NaiveModel()))
def test_is_shared_model_filter(self):
self.assertFalse(is_shared_model(AwareModel()))
self.assertTrue(is_shared_model(NaiveModel()))
def test_schema_name_filter(self):
Schema.objects.create(name='Schema Name', schema='foo')
self.assertEquals('Schema Name', schema_name('foo'))
self.assertEquals('no schema', schema_name(None))
self.assertEquals('no schema', schema_name(''))
self.assertEquals('no schema', schema_name(False))
self.assertEquals('no schema', schema_name('foobar'))
self.assertEquals('no schema', schema_name('foo_'))
self.assertEquals('no schema', schema_name('foofoo')) | Fix tests since we changed imports. | Fix tests since we changed imports.
| Python | bsd-3-clause | luzfcb/django-boardinghouse,luzfcb/django-boardinghouse,luzfcb/django-boardinghouse | ---
+++
@@ -1,7 +1,8 @@
from django.test import TestCase
from .models import AwareModel, NaiveModel
-from ..templatetags.boardinghouse import *
+from ..templatetags.boardinghouse import schema_name, is_schema_aware, is_shared_model
+from ..models import Schema
class TestTemplateTags(TestCase):
def test_is_schema_aware_filter(self): |
0e69718b24fe24e898c605b1823db1939bcadcd4 | examples/pipes-repl.py | examples/pipes-repl.py | import sys
import code
from diesel import Application, Pipe, until
DEFAULT_PROMPT = '>>> '
def readcb():
print 'Diesel Console'
cmd = ''
prompt = DEFAULT_PROMPT
while 1:
sys.stdout.write(prompt)
sys.stdout.flush()
input = yield until("\n")
cmd += input
if input.lstrip() == input or input == "\n":
ret = code.compile_command(input)
if ret:
out = eval(ret)
if out:
print 'Out: %r' % out
cmd = ''
prompt = DEFAULT_PROMPT
else:
# Start of a block
prompt = '... '
else:
# Continued block
prompt = '... '
a = Application()
a.add_loop(Pipe(sys.stdin, readcb))
a.run()
| import sys
import code
from diesel import Application, Pipe, until
DEFAULT_PROMPT = '>>> '
def readcb():
from diesel.app import current_app
print 'Diesel Console'
cmd = ''
prompt = DEFAULT_PROMPT
interp = code.InteractiveInterpreter(locals={'app':current_app})
while 1:
sys.stdout.write(prompt)
sys.stdout.flush()
input = yield until("\n")
cmd += input
if input.lstrip() == input or input == "\n":
ret = code.compile_command(input)
if ret:
out = interp.runcode(ret)
if out:
print 'Out: %r' % out
cmd = ''
prompt = DEFAULT_PROMPT
else:
# Start of a block
prompt = '... '
else:
# Continued block
prompt = '... '
a = Application()
a.add_loop(Pipe(sys.stdin, readcb))
a.run()
| Switch to using InteractiveInterpreter object instead of eval | Switch to using InteractiveInterpreter object instead of eval
| Python | bsd-3-clause | dieseldev/diesel | ---
+++
@@ -6,9 +6,11 @@
DEFAULT_PROMPT = '>>> '
def readcb():
+ from diesel.app import current_app
print 'Diesel Console'
cmd = ''
prompt = DEFAULT_PROMPT
+ interp = code.InteractiveInterpreter(locals={'app':current_app})
while 1:
sys.stdout.write(prompt)
sys.stdout.flush()
@@ -17,7 +19,7 @@
if input.lstrip() == input or input == "\n":
ret = code.compile_command(input)
if ret:
- out = eval(ret)
+ out = interp.runcode(ret)
if out:
print 'Out: %r' % out
cmd = '' |
0da65e9051ec6bf0c72f8dcc856a76547a1a125d | drf_multiple_model/views.py | drf_multiple_model/views.py | from drf_multiple_model.mixins import FlatMultipleModelMixin, ObjectMultipleModelMixin
from rest_framework.generics import GenericAPIView
class FlatMultipleModelAPIView(FlatMultipleModelMixin, GenericAPIView):
def get(self, request, *args, **kwargs):
return self.list(request, *args, **kwargs)
def initial(self, request, *args, **kwargs):
super().initial(request, *args, **kwargs)
if self.sorting_parameter_name in request.query_params:
self.sorting_field = request.query_params.get(self.sorting_parameter_name)
self.sort_descending = self.sorting_field[0] == '-'
if self.sort_descending:
self.sorting_field = self.sorting_field[1:]
self.sorting_field = self.sorting_fields_map.get(self.sorting_field, self.sorting_field)
def get_queryset(self):
return None
class ObjectMultipleModelAPIView(ObjectMultipleModelMixin, GenericAPIView):
def get(self, request, *args, **kwargs):
return self.list(request, *args, **kwargs)
def get_queryset(self):
return None
| from drf_multiple_model.mixins import FlatMultipleModelMixin, ObjectMultipleModelMixin
from rest_framework.generics import GenericAPIView
class FlatMultipleModelAPIView(FlatMultipleModelMixin, GenericAPIView):
def get(self, request, *args, **kwargs):
return self.list(request, *args, **kwargs)
def initial(self, request, *args, **kwargs):
super(GenericAPIView, self).initial(request, *args, **kwargs)
if self.sorting_parameter_name in request.query_params:
# Extract sorting parameter from query string
self.sorting_field = request.query_params.get(self.sorting_parameter_name)
if self.sorting_field:
# Handle sorting direction and sorting field mapping
self.sort_descending = self.sorting_field[0] == '-'
if self.sort_descending:
self.sorting_field = self.sorting_field[1:]
self.sorting_field = self.sorting_fields_map.get(self.sorting_field, self.sorting_field)
def get_queryset(self):
return None
class ObjectMultipleModelAPIView(ObjectMultipleModelMixin, GenericAPIView):
def get(self, request, *args, **kwargs):
return self.list(request, *args, **kwargs)
def get_queryset(self):
return None
| Fix initialization ofr sorting parameters | Fix initialization ofr sorting parameters
| Python | mit | Axiologue/DjangoRestMultipleModels | ---
+++
@@ -8,9 +8,13 @@
return self.list(request, *args, **kwargs)
def initial(self, request, *args, **kwargs):
- super().initial(request, *args, **kwargs)
+ super(GenericAPIView, self).initial(request, *args, **kwargs)
if self.sorting_parameter_name in request.query_params:
+ # Extract sorting parameter from query string
self.sorting_field = request.query_params.get(self.sorting_parameter_name)
+
+ if self.sorting_field:
+ # Handle sorting direction and sorting field mapping
self.sort_descending = self.sorting_field[0] == '-'
if self.sort_descending:
self.sorting_field = self.sorting_field[1:] |
359c563e200431e7da13766cf106f14f36b29bd4 | shuup_workbench/urls.py | shuup_workbench/urls.py | # This file is part of Shuup.
#
# Copyright (c) 2012-2018, 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.conf import settings
from django.conf.urls import include, url
from django.conf.urls.static import static
from django.contrib import admin
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^sa/', include('shuup.admin.urls', namespace="shuup_admin", app_name="shuup_admin")),
url(r'^api/', include('shuup.api.urls')),
url(r'^', include('shuup.front.urls', namespace="shuup", app_name="shuup")),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
| # This file is part of Shuup.
#
# Copyright (c) 2012-2018, 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.conf import settings
from django.conf.urls import include, url
from django.conf.urls.static import static
urlpatterns = [
url(r'^sa/', include('shuup.admin.urls', namespace="shuup_admin", app_name="shuup_admin")),
url(r'^api/', include('shuup.api.urls')),
url(r'^', include('shuup.front.urls', namespace="shuup", app_name="shuup")),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
| Hide Django admin URLs from the workbench | Hide Django admin URLs from the workbench
Django admin shouldn't be used by default with Shuup. Enabling
this would require some attention towards Django filer in multi
shop situations.
| Python | agpl-3.0 | shoopio/shoop,shoopio/shoop,shoopio/shoop | ---
+++
@@ -7,10 +7,8 @@
from django.conf import settings
from django.conf.urls import include, url
from django.conf.urls.static import static
-from django.contrib import admin
urlpatterns = [
- url(r'^admin/', include(admin.site.urls)),
url(r'^sa/', include('shuup.admin.urls', namespace="shuup_admin", app_name="shuup_admin")),
url(r'^api/', include('shuup.api.urls')),
url(r'^', include('shuup.front.urls', namespace="shuup", app_name="shuup")), |
40c5f5ec789cd820666596244d3e748fa9539732 | currencies/context_processors.py | currencies/context_processors.py | from currencies.models import Currency
def currencies(request):
currencies = Currency.objects.all()
if not request.session.get('currency'):
#request.session['currency'] = Currency.objects.get(code__exact='EUR')
request.session['currency'] = Currency.objects.get(is_default__exact=True)
return {
'CURRENCIES': currencies,
'currency': request.session['currency'], # DEPRECATED
'CURRENCY': request.session['currency']
}
| from currencies.models import Currency
def currencies(request):
currencies = Currency.objects.all()
if not request.session.get('currency'):
request.session['currency'] = Currency.objects.get(is_default__exact=True)
return {
'CURRENCIES': currencies,
'currency': request.session['currency'], # DEPRECATED
'CURRENCY': request.session['currency']
}
| Remove an old debug comment | Remove an old debug comment
| Python | bsd-3-clause | panosl/django-currencies,bashu/django-simple-currencies,barseghyanartur/django-currencies,mysociety/django-currencies,marcosalcazar/django-currencies,pathakamit88/django-currencies,bashu/django-simple-currencies,jmp0xf/django-currencies,pathakamit88/django-currencies,ydaniv/django-currencies,ydaniv/django-currencies,mysociety/django-currencies,racitup/django-currencies,panosl/django-currencies,marcosalcazar/django-currencies,racitup/django-currencies | ---
+++
@@ -5,7 +5,6 @@
currencies = Currency.objects.all()
if not request.session.get('currency'):
- #request.session['currency'] = Currency.objects.get(code__exact='EUR')
request.session['currency'] = Currency.objects.get(is_default__exact=True)
return { |
762147b8660a507ac5db8d0408162e8463b2fe8e | daiquiri/registry/serializers.py | daiquiri/registry/serializers.py | from rest_framework import serializers
from daiquiri.core.serializers import JSONListField, JSONDictField
class DublincoreSerializer(serializers.Serializer):
identifier = serializers.ReadOnlyField()
title = serializers.ReadOnlyField()
description = serializers.SerializerMethodField()
publisher = serializers.SerializerMethodField()
subjects = serializers.ReadOnlyField()
def get_description(self, obj):
return obj['content']['description']
def get_publisher(self, obj):
return obj['curation']['publisher']
class VoresourceSerializer(serializers.Serializer):
identifier = serializers.ReadOnlyField()
title = serializers.ReadOnlyField()
created = serializers.ReadOnlyField()
updated = serializers.ReadOnlyField()
voresource_status = serializers.ReadOnlyField(default='active')
curation = JSONDictField(default={})
content = JSONDictField(default={})
capabilities = JSONListField(default=[])
tableset = JSONListField(default=[])
managed_authority = serializers.ReadOnlyField(default=None)
managing_org = serializers.ReadOnlyField(default=None)
type = serializers.ReadOnlyField()
| from rest_framework import serializers
from daiquiri.core.serializers import JSONDictField, JSONListField
class DublincoreSerializer(serializers.Serializer):
identifier = serializers.ReadOnlyField()
title = serializers.ReadOnlyField()
description = serializers.SerializerMethodField()
publisher = serializers.SerializerMethodField()
subjects = serializers.ReadOnlyField()
def get_description(self, obj):
return obj['content']['description']
def get_publisher(self, obj):
return obj['curation']['publisher']
class VoresourceSerializer(serializers.Serializer):
identifier = serializers.ReadOnlyField()
title = serializers.ReadOnlyField()
created = serializers.ReadOnlyField()
updated = serializers.ReadOnlyField()
type = serializers.ReadOnlyField()
status = serializers.ReadOnlyField()
curation = JSONDictField(default={})
content = JSONDictField(default={})
capabilities = JSONListField(default=[])
tableset = JSONListField(default=[])
managed_authority = serializers.ReadOnlyField(default=None)
managing_org = serializers.ReadOnlyField(default=None)
| Fix status field in OAI-PMH | Fix status field in OAI-PMH
| Python | apache-2.0 | aipescience/django-daiquiri,aipescience/django-daiquiri,aipescience/django-daiquiri | ---
+++
@@ -1,6 +1,6 @@
from rest_framework import serializers
-from daiquiri.core.serializers import JSONListField, JSONDictField
+from daiquiri.core.serializers import JSONDictField, JSONListField
class DublincoreSerializer(serializers.Serializer):
@@ -24,7 +24,8 @@
title = serializers.ReadOnlyField()
created = serializers.ReadOnlyField()
updated = serializers.ReadOnlyField()
- voresource_status = serializers.ReadOnlyField(default='active')
+ type = serializers.ReadOnlyField()
+ status = serializers.ReadOnlyField()
curation = JSONDictField(default={})
content = JSONDictField(default={})
@@ -33,4 +34,3 @@
managed_authority = serializers.ReadOnlyField(default=None)
managing_org = serializers.ReadOnlyField(default=None)
- type = serializers.ReadOnlyField() |
b1deec08fe23eb89dd51471c6f11e2e3da69a563 | aospy/__init__.py | aospy/__init__.py | """aospy: management, analysis, and plotting of gridded climate data."""
from .__config__ import (user_path, LAT_STR, LON_STR, PFULL_STR, PHALF_STR,
PLEVEL_STR, TIME_STR)
from . import constants
from .constants import Constant
from . import numerics
from .numerics import FiniteDiff
from . import utils
from . import io
from . import timedate
from .timedate import TimeManager
from . import units
from .units import Units
from . import operator
from .operator import Operator
#from . import spharm_interface # On hold in python3
#from .spharm_interface import SpharmInterface
from . import var
from .var import Var
from . import region
from .region import Region
from . import run
from .run import Run
from . import model
from .model import Model
from . import proj
from .proj import Proj
from . import calc
from .calc import CalcInterface, Calc
from . import plotting
from .plotting import Fig, Ax, Plot
__all__ = ['Proj', 'Model', 'Run', 'Var', 'Units', 'Constant', 'Region',
'Fig', 'Ax', 'Plot', 'units', 'calc', 'constants', 'utils', 'io',
'plotting']
| """aospy: management, analysis, and plotting of gridded climate data."""
from .__config__ import (user_path, LAT_STR, LON_STR, PFULL_STR, PHALF_STR,
PLEVEL_STR, TIME_STR, TIME_STR_IDEALIZED)
from . import constants
from .constants import Constant
from . import numerics
from .numerics import FiniteDiff
from . import utils
from . import io
from . import timedate
from .timedate import TimeManager
from . import units
from .units import Units
from . import operator
from .operator import Operator
#from . import spharm_interface # On hold in python3
#from .spharm_interface import SpharmInterface
from . import var
from .var import Var
from . import region
from .region import Region
from . import run
from .run import Run
from . import model
from .model import Model
from . import proj
from .proj import Proj
from . import calc
from .calc import CalcInterface, Calc
from . import plotting
from .plotting import Fig, Ax, Plot
__all__ = ['Proj', 'Model', 'Run', 'Var', 'Units', 'Constant', 'Region',
'Fig', 'Ax', 'Plot', 'units', 'calc', 'constants', 'utils', 'io',
'plotting']
| Add TIME_STR_IDEALIZED to string labels | Add TIME_STR_IDEALIZED to string labels
| Python | apache-2.0 | spencerkclark/aospy,spencerahill/aospy | ---
+++
@@ -1,6 +1,6 @@
"""aospy: management, analysis, and plotting of gridded climate data."""
from .__config__ import (user_path, LAT_STR, LON_STR, PFULL_STR, PHALF_STR,
- PLEVEL_STR, TIME_STR)
+ PLEVEL_STR, TIME_STR, TIME_STR_IDEALIZED)
from . import constants
from .constants import Constant
from . import numerics |
e1cfdb6a95e11261755064e52720a38c99f18ddf | SatNOGS/base/api/serializers.py | SatNOGS/base/api/serializers.py | from rest_framework import serializers
from base.models import (Antenna, Data, Observation, Satellite, Station,
Transponder)
class AntennaSerializer(serializers.ModelSerializer):
class Meta:
model = Antenna
fields = ('frequency', 'band', 'antenna_type')
class StationSerializer(serializers.ModelSerializer):
class Meta:
model = Station
fields = ('owner', 'name', 'image', 'alt', 'lat', 'lng',
'antenna', 'featured', 'featured_date')
class SatelliteSerializer(serializers.ModelSerializer):
class Meta:
model = Satellite
fields = ('norad_cat_id', 'name')
class TransponderSerializer(serializers.ModelSerializer):
class Meta:
model = Transponder
fields = ('description', 'alive', 'uplink_low', 'uplink_high',
'downlink_low', 'downlink_high', 'mode', 'invert',
'baud', 'satellite')
class ObservationSerializer(serializers.ModelSerializer):
class Meta:
model = Observation
fields = ('satellite', 'transponder', 'author', 'start', 'end')
class DataSerializer(serializers.ModelSerializer):
class Meta:
model = Data
fields = ('start', 'end', 'observation', 'ground_station', 'payload')
| from django.conf import settings
from django.contrib.sites.models import Site
from rest_framework import serializers
from base.models import (Antenna, Data, Observation, Satellite, Station,
Transponder)
class AntennaSerializer(serializers.ModelSerializer):
class Meta:
model = Antenna
fields = ('frequency', 'band', 'antenna_type')
class StationSerializer(serializers.ModelSerializer):
class Meta:
model = Station
fields = ('owner', 'name', 'image', 'alt', 'lat', 'lng',
'antenna', 'featured', 'featured_date')
image = serializers.SerializerMethodField('image_url')
def image_url(self, obj):
site = Site.objects.get_current()
return '{}{}{}'.format(site, settings.MEDIA_URL, obj.image)
class SatelliteSerializer(serializers.ModelSerializer):
class Meta:
model = Satellite
fields = ('norad_cat_id', 'name')
class TransponderSerializer(serializers.ModelSerializer):
class Meta:
model = Transponder
fields = ('description', 'alive', 'uplink_low', 'uplink_high',
'downlink_low', 'downlink_high', 'mode', 'invert',
'baud', 'satellite')
class ObservationSerializer(serializers.ModelSerializer):
class Meta:
model = Observation
fields = ('satellite', 'transponder', 'author', 'start', 'end')
class DataSerializer(serializers.ModelSerializer):
class Meta:
model = Data
fields = ('start', 'end', 'observation', 'ground_station', 'payload')
| Add full image url to Station serializer | Add full image url to Station serializer
| Python | agpl-3.0 | cshields/satnogs-network,cshields/satnogs-network,cshields/satnogs-network,cshields/satnogs-network | ---
+++
@@ -1,3 +1,5 @@
+from django.conf import settings
+from django.contrib.sites.models import Site
from rest_framework import serializers
from base.models import (Antenna, Data, Observation, Satellite, Station,
@@ -15,6 +17,12 @@
model = Station
fields = ('owner', 'name', 'image', 'alt', 'lat', 'lng',
'antenna', 'featured', 'featured_date')
+
+ image = serializers.SerializerMethodField('image_url')
+
+ def image_url(self, obj):
+ site = Site.objects.get_current()
+ return '{}{}{}'.format(site, settings.MEDIA_URL, obj.image)
class SatelliteSerializer(serializers.ModelSerializer): |
e45f23bbdce002cfbf644f2c91f319127f64b90c | mesa/urls.py | mesa/urls.py | from django.conf.urls import patterns, include, url
from django.contrib import admin
urlpatterns = patterns('',
url(r'^', include('statuses.urls')),
url(r'^admin/', include(admin.site.urls)),
)
| from django.conf.urls import include, url
from django.contrib import admin
urlpatterns = [
url(r'^', include('statuses.urls')),
url(r'^admin/', include(admin.site.urls)),
]
| Change pattern tuple to list | Change pattern tuple to list
| Python | mit | matthewlane/mesa,matthewlane/mesa,matthewlane/mesa,matthewlane/mesa | ---
+++
@@ -1,7 +1,7 @@
-from django.conf.urls import patterns, include, url
+from django.conf.urls import include, url
from django.contrib import admin
-urlpatterns = patterns('',
+urlpatterns = [
url(r'^', include('statuses.urls')),
url(r'^admin/', include(admin.site.urls)),
-)
+] |
a43d461bf2d5c40b8d828873f9fa0b5e2048a0df | SnsManager/google/GoogleBase.py | SnsManager/google/GoogleBase.py | import httplib2
from apiclient.discovery import build
from oauth2client.client import AccessTokenCredentials, AccessTokenCredentialsError
from SnsManager.SnsBase import SnsBase
from SnsManager import ErrorCode
class GoogleBase(SnsBase):
def __init__(self, *args, **kwargs):
super(self.__class__, self).__init__(*args, **kwargs)
self.myId = self.getMyId()
self._userAgent = 'Waveface AOStream/1.0'
def getMyId(self):
try:
http = httplib2.Http()
credentials = AccessTokenCredentials(self._accessToken, self._userAgent)
http = credentials.authorize(http)
userInfo = build('oauth2', 'v2', http=http).userinfo().get().execute()
self.myId = userInfo['email']
except:
return None
return self.myId
def isTokenValid(self):
try:
http = httplib2.Http()
credentials = AccessTokenCredentials(self._accessToken, self._userAgent)
http = credentials.authorize(http)
userInfo = build('oauth2', 'v2', http=http).userinfo().get().execute()
except AccessTokenCredentialsError as e:
return ErrorCode.E_INVALID_TOKEN
except:
self._logger.exception('GoogleBase::isTokenValid() exception')
return ErrorCode.E_FAILED
else:
return ErrorCode.S_OK
| import httplib2
from apiclient.discovery import build
from oauth2client.client import AccessTokenCredentials, AccessTokenCredentialsError
from SnsManager.SnsBase import SnsBase
from SnsManager import ErrorCode
class GoogleBase(SnsBase):
def __init__(self, *args, **kwargs):
super(GoogleBase, self).__init__(*args, **kwargs)
self.myId = self.getMyId()
self._userAgent = 'Waveface AOStream/1.0'
self._http = httplib2.Http()
credentials = AccessTokenCredentials(self._accessToken, self._userAgent)
self._http = credentials.authorize(self._http)
def getMyId(self):
try:
userInfo = build('oauth2', 'v2', http=self._http).userinfo().get().execute()
self.myId = userInfo['email']
except:
return None
return self.myId
def isTokenValid(self):
try:
userInfo = build('oauth2', 'v2', http=self._http).userinfo().get().execute()
except AccessTokenCredentialsError as e:
return ErrorCode.E_INVALID_TOKEN
except:
self._logger.exception('GoogleBase::isTokenValid() exception')
return ErrorCode.E_FAILED
else:
return ErrorCode.S_OK
| Move http object as based object | Move http object as based object
| Python | bsd-3-clause | waveface/SnsManager | ---
+++
@@ -6,16 +6,17 @@
class GoogleBase(SnsBase):
def __init__(self, *args, **kwargs):
- super(self.__class__, self).__init__(*args, **kwargs)
+ super(GoogleBase, self).__init__(*args, **kwargs)
self.myId = self.getMyId()
self._userAgent = 'Waveface AOStream/1.0'
+ self._http = httplib2.Http()
+ credentials = AccessTokenCredentials(self._accessToken, self._userAgent)
+ self._http = credentials.authorize(self._http)
+
def getMyId(self):
try:
- http = httplib2.Http()
- credentials = AccessTokenCredentials(self._accessToken, self._userAgent)
- http = credentials.authorize(http)
- userInfo = build('oauth2', 'v2', http=http).userinfo().get().execute()
+ userInfo = build('oauth2', 'v2', http=self._http).userinfo().get().execute()
self.myId = userInfo['email']
except:
return None
@@ -23,10 +24,7 @@
def isTokenValid(self):
try:
- http = httplib2.Http()
- credentials = AccessTokenCredentials(self._accessToken, self._userAgent)
- http = credentials.authorize(http)
- userInfo = build('oauth2', 'v2', http=http).userinfo().get().execute()
+ userInfo = build('oauth2', 'v2', http=self._http).userinfo().get().execute()
except AccessTokenCredentialsError as e:
return ErrorCode.E_INVALID_TOKEN
except: |
a99d07e02f69961be5096ce8575007cec7ec213d | photoshell/__main__.py | photoshell/__main__.py | import os
from gi.repository import GObject
from photoshell.config import Config
from photoshell.library import Library
from photoshell.views.slideshow import Slideshow
from photoshell.views.window import Window
c = Config({
'library': os.path.join(os.environ['HOME'], 'Pictures/Photoshell'),
'dark_theme': True,
'import_path': '%Y-%m-%d/{original_filename}'
})
# Open photo viewer
library = Library(c)
Window(c, library, Slideshow())
if c.exists():
c.flush()
| import os
import signal
from photoshell.config import Config
from photoshell.library import Library
from photoshell.views.slideshow import Slideshow
from photoshell.views.window import Window
c = Config({
'library': os.path.join(os.environ['HOME'], 'Pictures/Photoshell'),
'dark_theme': True,
'import_path': '%Y-%m-%d/{original_filename}'
})
# Open photo viewer
library = Library(c)
signal.signal(signal.SIGINT, signal.SIG_DFL)
Window(c, library, Slideshow())
if c.exists():
c.flush()
| Add a signal handler to handle SIGINTs | Add a signal handler to handle SIGINTs
Fixes #135
| Python | mit | photoshell/photoshell,SamWhited/photoshell,campaul/photoshell | ---
+++
@@ -1,6 +1,5 @@
import os
-
-from gi.repository import GObject
+import signal
from photoshell.config import Config
from photoshell.library import Library
@@ -15,6 +14,9 @@
# Open photo viewer
library = Library(c)
+
+signal.signal(signal.SIGINT, signal.SIG_DFL)
Window(c, library, Slideshow())
+
if c.exists():
c.flush() |
691bee381bda822a059c5d9fa790feabc7e00a8d | dnsimple2/tests/services/base.py | dnsimple2/tests/services/base.py | import os
from unittest import TestCase
from dnsimple2.client import DNSimple
from dnsimple2.resources import (
AccountResource,
DomainResource
)
from dnsimple2.tests.utils import get_test_domain_name
class BaseServiceTestCase(TestCase):
@classmethod
def setUpClass(cls):
access_token = os.getenv('DNSIMPLE_V2_ACCESS_TOKEN')
cls.client = DNSimple(access_token)
cls.account = AccountResource(id=424)
cls.domain = cls.client.domains.create(
cls.account,
DomainResource(name=get_test_domain_name(), account=cls.account)
)
cls.invalid_domain = DomainResource(
id=1,
name='invalid-domain',
account=cls.account
)
| import os
from unittest import TestCase
from dnsimple2.client import DNSimple
from dnsimple2.resources import (
AccountResource,
DomainResource
)
from dnsimple2.tests.utils import get_test_domain_name
class BaseServiceTestCase(TestCase):
@classmethod
def setUpClass(cls):
access_token = os.getenv('DNSIMPLE_V2_ACCESS_TOKEN')
cls.client = DNSimple(access_token)
account_id = os.getenv('DNSIMPLE_ACCOUNT_ID')
cls.account = AccountResource(id=account_id)
cls.domain = cls.client.domains.create(
cls.account,
DomainResource(name=get_test_domain_name(), account=cls.account)
)
cls.invalid_domain = DomainResource(
id=1,
name='invalid-domain',
account=cls.account
)
| Use env variable for account id in tests. | Use env variable for account id in tests.
| Python | mit | indradhanush/dnsimple2-python | ---
+++
@@ -14,7 +14,9 @@
def setUpClass(cls):
access_token = os.getenv('DNSIMPLE_V2_ACCESS_TOKEN')
cls.client = DNSimple(access_token)
- cls.account = AccountResource(id=424)
+
+ account_id = os.getenv('DNSIMPLE_ACCOUNT_ID')
+ cls.account = AccountResource(id=account_id)
cls.domain = cls.client.domains.create(
cls.account,
DomainResource(name=get_test_domain_name(), account=cls.account) |
1bda8188458b81866c5938529ba85b3913caedc0 | project/api/indexes.py | project/api/indexes.py | from algoliasearch_django import AlgoliaIndex
class ChartIndex(AlgoliaIndex):
fields = [
'title',
'arrangers'
]
settings = {
'searchableAttributes': [
'title',
'arrangers',
]
}
class GroupIndex(AlgoliaIndex):
should_index = 'is_active'
fields = [
'name',
'get_kind_display',
'get_gender_display',
'code',
'image',
'bhs_id',
]
settings = {
'searchableAttributes': [
'name',
'code',
'bhs_id',
'get_kind_display',
]
}
class PersonIndex(AlgoliaIndex):
fields = [
'first_name',
'middle_name',
'last_name',
'nick_name',
'get_gender_display',
'get_part_display',
'email',
'image',
'bhs_id',
'full_name',
'common_name',
]
settings = {
'searchableAttributes': [
'bhs_id,full_name',
'get_gender_display',
'get_part_display',
'email',
]
}
| from algoliasearch_django import AlgoliaIndex
class ChartIndex(AlgoliaIndex):
fields = [
'title',
'arrangers'
]
settings = {
'searchableAttributes': [
'title',
'arrangers',
]
}
class GroupIndex(AlgoliaIndex):
should_index = 'is_active'
fields = [
'name',
'get_kind_display',
'get_gender_display',
'code',
'image',
'bhs_id',
]
settings = {
'searchableAttributes': [
'name',
'code',
'bhs_id',
'get_kind_display',
],
'attributesForFaceting': [
'get_kind_display',
]
}
class PersonIndex(AlgoliaIndex):
fields = [
'first_name',
'middle_name',
'last_name',
'nick_name',
'get_gender_display',
'get_part_display',
'email',
'image',
'bhs_id',
'full_name',
'common_name',
]
settings = {
'searchableAttributes': [
'bhs_id,full_name',
'get_gender_display',
'get_part_display',
'email',
]
}
| Add faceting test to Group index | Add faceting test to Group index
| Python | bsd-2-clause | barberscore/barberscore-api,dbinetti/barberscore-django,dbinetti/barberscore-django,dbinetti/barberscore,barberscore/barberscore-api,dbinetti/barberscore,barberscore/barberscore-api,barberscore/barberscore-api | ---
+++
@@ -30,6 +30,9 @@
'code',
'bhs_id',
'get_kind_display',
+ ],
+ 'attributesForFaceting': [
+ 'get_kind_display',
]
}
|
59c698e5db5c7fb2d537398cdad93215714b21f0 | SimpleLoop.py | SimpleLoop.py | # Copyright 2011 Seppo Yli-Olli
#
# 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.
class EventLoop:
def __init__ (self):
self._queue = []
self._defaultinvocation = None
def queueInvocation(self, function, args):
self._queue.append((function, args))
def defaultInvocation(self, function, args):
self._defaultinvocation = (function, args)
def run(self):
while True:
if len(self._queue) > 0:
(function, args) = self._queue.pop()
function(self, args)
elif self._defaultinvocation:
(function, args) = self._defaultinvocation
function(self, args)
else:
break
| # Copyright 2011 Seppo Yli-Olli
#
# 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.
class EventLoop:
def __init__ (self):
self._queue = []
self._running = False
def queueInvocation(self, function, args):
self._queue.append((function, args))
def defaultInvocation(self, function, args):
self._defaultinvocation = (function, args)
def quit():
self._running = False
def run(self):
self._running = True
while True:
if not self._running:
break
if len(self._queue) > 0:
(function, args) = self._queue.pop()
function(self, args)
elif self._defaultinvocation:
(function, args) = self._defaultinvocation
function(self, args)
else:
break
| Add a way to have the loop quit after current invocation has been processed. | Add a way to have the loop quit after current invocation has been processed.
| Python | apache-2.0 | nanonyme/SimpleLoop,nanonyme/SimpleLoop | ---
+++
@@ -17,7 +17,7 @@
def __init__ (self):
self._queue = []
- self._defaultinvocation = None
+ self._running = False
def queueInvocation(self, function, args):
self._queue.append((function, args))
@@ -25,8 +25,14 @@
def defaultInvocation(self, function, args):
self._defaultinvocation = (function, args)
+ def quit():
+ self._running = False
+
def run(self):
+ self._running = True
while True:
+ if not self._running:
+ break
if len(self._queue) > 0:
(function, args) = self._queue.pop()
function(self, args) |
6b5461955e196ee4a12b708fb6f9bef750d468ad | testcontainers/oracle.py | testcontainers/oracle.py | from testcontainers.core.generic import DbContainer
class OracleDbContainer(DbContainer):
"""
Oracle database container.
Example
-------
::
with OracleDbContainer():
e = sqlalchemy.create_engine(oracle.get_connection_url())
result = e.execute("select 1 from dual")
"""
def __init__(self, image="wnameless/oracle-xe-11g-r2:latest"):
super(OracleDbContainer, self).__init__(image=image)
self.container_port = 1521
self.with_exposed_ports(self.container_port)
self.with_env("ORACLE_ALLOW_REMOTE", "true")
def get_connection_url(self):
return super()._create_connection_url(
dialect="oracle", username="system", password="oracle", port=self.container_port,
db_name="xe"
)
| from testcontainers.core.generic import DbContainer
class OracleDbContainer(DbContainer):
"""
Oracle database container.
Example
-------
::
with OracleDbContainer() as oracle:
e = sqlalchemy.create_engine(oracle.get_connection_url())
result = e.execute("select 1 from dual")
"""
def __init__(self, image="wnameless/oracle-xe-11g-r2:latest"):
super(OracleDbContainer, self).__init__(image=image)
self.container_port = 1521
self.with_exposed_ports(self.container_port)
self.with_env("ORACLE_ALLOW_REMOTE", "true")
def get_connection_url(self):
return super()._create_connection_url(
dialect="oracle", username="system", password="oracle", port=self.container_port,
db_name="xe"
)
def _configure(self):
pass
| Add missing _configure to OracleDbContainer | Add missing _configure to OracleDbContainer
Additionally, fix Oracle example.
| Python | apache-2.0 | SergeyPirogov/testcontainers-python | ---
+++
@@ -9,7 +9,7 @@
-------
::
- with OracleDbContainer():
+ with OracleDbContainer() as oracle:
e = sqlalchemy.create_engine(oracle.get_connection_url())
result = e.execute("select 1 from dual")
"""
@@ -24,3 +24,6 @@
dialect="oracle", username="system", password="oracle", port=self.container_port,
db_name="xe"
)
+
+ def _configure(self):
+ pass |
9b83a9dbfe1cc3dc4e8da3df71b6c414e304f53f | testing/runtests.py | testing/runtests.py | # -*- coding: utf-8 -*-
import os, sys
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings")
from django.core.management import call_command
if __name__ == "__main__":
args = sys.argv[1:]
call_command("test", *args, verbosity=2)
| # -*- coding: utf-8 -*-
import os, sys
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings")
if __name__ == "__main__":
from django.core.management import execute_from_command_line
args = sys.argv
args.insert(1, "test")
args.insert(2, "pg_uuid_fields")
execute_from_command_line(args)
| Fix tests to run with django 1.7 | Fix tests to run with django 1.7
| Python | bsd-3-clause | niwinz/djorm-ext-pguuid | ---
+++
@@ -3,8 +3,11 @@
import os, sys
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings")
-from django.core.management import call_command
+if __name__ == "__main__":
+ from django.core.management import execute_from_command_line
-if __name__ == "__main__":
- args = sys.argv[1:]
- call_command("test", *args, verbosity=2)
+ args = sys.argv
+ args.insert(1, "test")
+ args.insert(2, "pg_uuid_fields")
+
+ execute_from_command_line(args) |
f68139ce9114f260487048716d7430fcb1b3173b | froide/helper/tasks.py | froide/helper/tasks.py | from django.conf import settings
from django.utils import translation
from celery.task import task
from haystack import site
@task
def delayed_update(instance_pk, model):
""" Only index stuff that is known to be public """
translation.activate(settings.LANGUAGE_CODE)
try:
instance = model.published.get(pk=instance_pk)
except (model.DoesNotExist, AttributeError):
return
site.update_object(instance)
@task
def delayed_remove(instance_pk, model):
translation.activate(settings.LANGUAGE_CODE)
# Fake an instance (real one is already gone from the DB)
fake_instance = model()
fake_instance.pk = instance_pk
site.remove_object(fake_instance)
| import logging
from django.conf import settings
from django.utils import translation
from celery.task import task
from celery.signals import task_failure
from haystack import site
from sentry.client.handlers import SentryHandler
# Hook up sentry to celery's logging
# Based on http://www.colinhowe.co.uk/2011/02/08/celery-and-sentry-recording-errors/
logger = logging.getLogger('task')
logger.addHandler(SentryHandler())
def process_failure_signal(exception, traceback, sender, task_id,
signal, args, kwargs, einfo, **kw):
exc_info = (type(exception), exception, traceback)
logger.error(
'Celery job exception: %s(%s)' % (exception.__class__.__name__, exception),
exc_info=exc_info,
extra={
'data': {
'task_id': task_id,
'sender': sender,
'args': args,
'kwargs': kwargs,
}
}
)
task_failure.connect(process_failure_signal)
@task
def delayed_update(instance_pk, model):
""" Only index stuff that is known to be public """
translation.activate(settings.LANGUAGE_CODE)
try:
instance = model.published.get(pk=instance_pk)
except (model.DoesNotExist, AttributeError):
return
site.update_object(instance)
@task
def delayed_remove(instance_pk, model):
translation.activate(settings.LANGUAGE_CODE)
# Fake an instance (real one is already gone from the DB)
fake_instance = model()
fake_instance.pk = instance_pk
site.remove_object(fake_instance)
| Add celery task failure sentry tracking | Add celery task failure sentry tracking | Python | mit | catcosmo/froide,okfse/froide,ryankanno/froide,LilithWittmann/froide,CodeforHawaii/froide,ryankanno/froide,LilithWittmann/froide,LilithWittmann/froide,catcosmo/froide,ryankanno/froide,CodeforHawaii/froide,catcosmo/froide,stefanw/froide,LilithWittmann/froide,CodeforHawaii/froide,CodeforHawaii/froide,ryankanno/froide,okfse/froide,stefanw/froide,CodeforHawaii/froide,ryankanno/froide,stefanw/froide,stefanw/froide,okfse/froide,LilithWittmann/froide,fin/froide,fin/froide,catcosmo/froide,fin/froide,fin/froide,stefanw/froide,okfse/froide,okfse/froide,catcosmo/froide | ---
+++
@@ -1,8 +1,35 @@
+import logging
+
from django.conf import settings
from django.utils import translation
from celery.task import task
+from celery.signals import task_failure
from haystack import site
+from sentry.client.handlers import SentryHandler
+
+
+# Hook up sentry to celery's logging
+# Based on http://www.colinhowe.co.uk/2011/02/08/celery-and-sentry-recording-errors/
+
+logger = logging.getLogger('task')
+logger.addHandler(SentryHandler())
+def process_failure_signal(exception, traceback, sender, task_id,
+ signal, args, kwargs, einfo, **kw):
+ exc_info = (type(exception), exception, traceback)
+ logger.error(
+ 'Celery job exception: %s(%s)' % (exception.__class__.__name__, exception),
+ exc_info=exc_info,
+ extra={
+ 'data': {
+ 'task_id': task_id,
+ 'sender': sender,
+ 'args': args,
+ 'kwargs': kwargs,
+ }
+ }
+ )
+task_failure.connect(process_failure_signal)
@task
def delayed_update(instance_pk, model):
@@ -21,3 +48,4 @@
fake_instance = model()
fake_instance.pk = instance_pk
site.remove_object(fake_instance)
+ |
b9a16863a1baca989ccec66a88b4218aad676160 | utils.py | utils.py | commands = {}
def add_cmd(name, alias=None, owner=False, admin=False):
def real_command(func):
commands[name] = func
if alias:
commands[alias] = func
return real_command
def call_command(bot, event, irc):
command = ' '.join(event.arguments).split(' ')
args = command[1]
name = command[0][1:]
try:
commands[name](bot, event, irc, args)
except KeyError:
irc.reply(event, 'Invalid command {}'.format(name))
except:
irc.reply(event, 'Oops, an error occured')
| commands = {}
def add_cmd(name, alias=None, owner=False, admin=False):
def real_command(func):
commands[name] = func
if alias:
commands[alias] = func
return real_command
def call_command(bot, event, irc):
command = ' '.join(event.arguments).split(' ')
args = command[1:] if len(command) > 1 else None
name = command[0][1:]
try:
commands[name](bot, event, irc, args)
except KeyError:
irc.reply(event, 'Invalid command {}'.format(name))
except:
irc.reply(event, 'Oops, an error occured')
else:
privmsg = event.target == bot.config['nickname']
target = "a private message" if privmsg else event.target
print("{] called {} in {}".format(event.source.nick, name, target))
| Fix a bug and log to the console | Fix a bug and log to the console
Fix a bug where a command is called without any arguments, so no indices will be out-of-range
Log to the console whenever someone calls a command
| Python | mit | wolfy1339/Python-IRC-Bot | ---
+++
@@ -11,7 +11,7 @@
def call_command(bot, event, irc):
command = ' '.join(event.arguments).split(' ')
- args = command[1]
+ args = command[1:] if len(command) > 1 else None
name = command[0][1:]
try:
commands[name](bot, event, irc, args)
@@ -19,4 +19,8 @@
irc.reply(event, 'Invalid command {}'.format(name))
except:
irc.reply(event, 'Oops, an error occured')
+ else:
+ privmsg = event.target == bot.config['nickname']
+ target = "a private message" if privmsg else event.target
+ print("{] called {} in {}".format(event.source.nick, name, target))
|
c65ed9ec976c440b46dedc514daf883bba940282 | myElsClient.py | myElsClient.py | import requests
class myElsClient:
"""A class that implements a Python interface to api.elsevier.com"""
# local variables
__base_url = "http://api.elsevier.com/"
def __init__(self, apiKey):
"""Instantiates a client with a given API Key."""
self.apiKey = apiKey
def getBaseURL(self):
return self.__base_url
| import requests
class myElsClient:
"""A class that implements a Python interface to api.elsevier.com"""
# local variables
__base_url = "http://api.elsevier.com/"
# constructors
def __init__(self, apiKey):
"""Instantiates a client with a given API Key."""
self.apiKey = apiKey
# configuration functions
"""Sets an institutional token for customer authentication"""
def setInstToken(self, instToken):
self.instToken = instToken
# utility access functions
def getBaseURL(self):
"""Returns the base URL currently configured for Elsevier's APIs"""
return self.__base_url
| Add ability to set insttoken | Add ability to set insttoken
| Python | bsd-3-clause | ElsevierDev/elsapy | ---
+++
@@ -6,10 +6,18 @@
# local variables
__base_url = "http://api.elsevier.com/"
-
+
+ # constructors
def __init__(self, apiKey):
"""Instantiates a client with a given API Key."""
self.apiKey = apiKey
+ # configuration functions
+ """Sets an institutional token for customer authentication"""
+ def setInstToken(self, instToken):
+ self.instToken = instToken
+
+ # utility access functions
def getBaseURL(self):
+ """Returns the base URL currently configured for Elsevier's APIs"""
return self.__base_url |
2565724364eac8a548be2f59173e2f0630fa2f5d | music/api.py | music/api.py | from django.conf.urls.defaults import url
from tastypie.resources import ModelResource
from tastypie.constants import ALL
from jmbo.api import ModelBaseResource
from music.models import Track
class TrackResource(ModelBaseResource):
class Meta:
queryset = Track.permitted.all()
resource_name = 'track'
filtering = {
'last_played': ALL
}
ordering = ['last_played']
def override_urls(self):
return [
url(r"^(?P<resource_name>%s)/(?P<slug>[\w-]+)/$" % self._meta.resource_name, self.wrap_view('dispatch_detail'), name="api_dispatch_detail"),
]
| from django.conf.urls.defaults import url
from tastypie.resources import ModelResource
from tastypie.constants import ALL
from tastypie import fields
from jmbo.api import ModelBaseResource
from music.models import Track, TrackContributor
class TrackContributorResource(ModelBaseResource):
class Meta:
queryset = TrackContributor.permitted.all()
resource_name = 'trackcontributor'
def override_urls(self):
return [
url(r"^(?P<resource_name>%s)/(?P<slug>[\w-]+)/$" % self._meta.resource_name, self.wrap_view('dispatch_detail'), name="api_dispatch_detail"),
]
class TrackResource(ModelBaseResource):
contributor = fields.ToManyField(TrackContributorResource, 'contributor', full=True)
class Meta:
queryset = Track.permitted.all()
resource_name = 'track'
filtering = {
'last_played': ALL
}
ordering = ['last_played']
def override_urls(self):
return [
url(r"^(?P<resource_name>%s)/(?P<slug>[\w-]+)/$" % self._meta.resource_name, self.wrap_view('dispatch_detail'), name="api_dispatch_detail"),
]
| Include contributor in track feed | Include contributor in track feed
| Python | bsd-3-clause | praekelt/jmbo-music,praekelt/jmbo-music | ---
+++
@@ -2,12 +2,26 @@
from tastypie.resources import ModelResource
from tastypie.constants import ALL
+from tastypie import fields
from jmbo.api import ModelBaseResource
-from music.models import Track
+from music.models import Track, TrackContributor
+
+
+class TrackContributorResource(ModelBaseResource):
+
+ class Meta:
+ queryset = TrackContributor.permitted.all()
+ resource_name = 'trackcontributor'
+
+ def override_urls(self):
+ return [
+ url(r"^(?P<resource_name>%s)/(?P<slug>[\w-]+)/$" % self._meta.resource_name, self.wrap_view('dispatch_detail'), name="api_dispatch_detail"),
+ ]
class TrackResource(ModelBaseResource):
+ contributor = fields.ToManyField(TrackContributorResource, 'contributor', full=True)
class Meta:
queryset = Track.permitted.all() |
2047d488a451759ebdf2bef508e1dd738d3165da | nazs/common.py | nazs/common.py | from .util import import_module
import logging
def init():
"""
Initialize nazs environment, setup logging, processes and all
needed stuff for running nazs
"""
from django.core import management
# Sync volatile db, TODO set correct permissions
management.call_command('syncdb', database='volatile', interactive=False)
from .sudo import set_euid
set_euid()
# Load all modules
from django.conf import settings
for app in settings.INSTALLED_APPS:
import_module(app + '.module')
def modules():
"""
Return a list of instances of all present modules
"""
from .module import Module
return [cls() for cls in Module.MODULES]
def changed():
"""
Return True if there is any change in any of the available modules
"""
for module in modules():
if module.changed:
return True
return False
def save():
"""
Apply configuration changes on all the modules
"""
from .models import ModuleInfo
logger = logging.getLogger(__name__)
logger.info("Saving changes")
# Save + restart
for module in modules():
if module.enabled:
if module.changed:
module.save()
module.restart()
module.commit()
else:
logger.debug("Not saving unchanged module: %s" % module.name)
else:
logger.debug("Not saving disabled module: %s" % module.name)
# Commit
ModuleInfo.commit()
logger.info("Changes saved")
| from .util import import_module
import logging
def init():
"""
Initialize nazs environment, setup logging, processes and all
needed stuff for running nazs
"""
from django.core import management
# Sync volatile db, TODO set correct permissions
management.call_command('syncdb',
database='volatile',
interactive=False,
verbosity=0)
from .sudo import set_euid
set_euid()
# Load all modules
from django.conf import settings
for app in settings.INSTALLED_APPS:
import_module(app + '.module')
def modules():
"""
Return a list of instances of all present modules
"""
from .module import Module
return [cls() for cls in Module.MODULES]
def changed():
"""
Return True if there is any change in any of the available modules
"""
for module in modules():
if module.changed:
return True
return False
def save():
"""
Apply configuration changes on all the modules
"""
from .models import ModuleInfo
logger = logging.getLogger(__name__)
logger.info("Saving changes")
# Save + restart
for module in modules():
if module.enabled:
if module.changed:
module.save()
module.restart()
module.commit()
else:
logger.debug("Not saving unchanged module: %s" % module.name)
else:
logger.debug("Not saving disabled module: %s" % module.name)
# Commit
ModuleInfo.commit()
logger.info("Changes saved")
| Disable annoying syncdb info for volatile db | Disable annoying syncdb info for volatile db
| Python | agpl-3.0 | exekias/droplet,exekias/droplet,exekias/droplet | ---
+++
@@ -10,7 +10,10 @@
"""
from django.core import management
# Sync volatile db, TODO set correct permissions
- management.call_command('syncdb', database='volatile', interactive=False)
+ management.call_command('syncdb',
+ database='volatile',
+ interactive=False,
+ verbosity=0)
from .sudo import set_euid
set_euid() |
c45c3fa8670ed7030010a255aee0233c8a3c434f | test/assets/test_task_types_for_asset.py | test/assets/test_task_types_for_asset.py | from test.base import ApiDBTestCase
class AssetTaskTypesTestCase(ApiDBTestCase):
def setUp(self):
super(AssetTaskTypesTestCase, self).setUp()
self.generate_fixture_project_status()
self.generate_fixture_project()
self.generate_fixture_entity_type()
self.generate_fixture_sequence()
self.generate_fixture_shot()
self.generate_fixture_entity()
self.generate_fixture_person()
self.generate_fixture_assigner()
self.generate_fixture_task_status()
self.generate_fixture_department()
self.generate_fixture_task_type()
self.generate_fixture_task()
self.asset_id = self.entity.id
self.task_type_dict = self.task_type.serialize()
def test_get_task_types_for_asset(self):
task_types = self.get("data/assets/%s/task-types" % self.asset_id)
self.assertEquals(len(task_types), 1)
self.assertDictEqual(
task_types[0],
self.task_type_dict
)
| from test.base import ApiDBTestCase
class AssetTaskTypesTestCase(ApiDBTestCase):
def setUp(self):
super(AssetTaskTypesTestCase, self).setUp()
self.generate_fixture_project_status()
self.generate_fixture_project()
self.generate_fixture_entity_type()
self.generate_fixture_sequence()
self.generate_fixture_shot()
self.generate_fixture_entity()
self.generate_fixture_person()
self.generate_fixture_assigner()
self.generate_fixture_task_status()
self.generate_fixture_department()
self.generate_fixture_task_type()
self.generate_fixture_task()
self.asset_id = self.entity.id
self.task_type_dict = self.task_type.serialize()
def test_get_task_types_for_asset(self):
task_types = self.get("data/assets/%s/task-types" % self.asset_id)
self.assertEquals(len(task_types), 1)
self.assertDictEqual(
task_types[0],
self.task_type_dict
)
def test_get_task_types_for_asset_not_found(self):
self.get("data/assets/no-asset/task-types", 404)
| Add tests for task types for assets routes | Add tests for task types for assets routes
Add a test to ensure that a 404 is returned when the give id is wrong.
| Python | agpl-3.0 | cgwire/zou | ---
+++
@@ -27,3 +27,6 @@
task_types[0],
self.task_type_dict
)
+
+ def test_get_task_types_for_asset_not_found(self):
+ self.get("data/assets/no-asset/task-types", 404) |
ffb93d2a33d847d5aade8f69db87991b17698613 | tests/main_test.py | tests/main_test.py | import EmpireAPIWrapper
api = EmpireAPIWrapper.empireAPI('10.15.20.157', uname='empireadmin', passwd='Password123!')
# api = EmpireAPIWrapper.empireAPI('10.15.20.157', token='2zqb4bgvoq1jhe9essncl3qa6h9rvbj1jq2p740k')
# api = EmpireAPIWrapper.empireAPI('10.15.20.157', token='yv42s1wlo90ikrzc7pwebgrbpqnzkigqlxbb4cp2')
# print(api.check_version())
# print(api.shutdownServer())
# print(api.restartServer())
# print(api.getMap())
# print(api.getConfig())
# print(api.getPermToken())
| Test harness for all working end points | Test harness for all working end points
| Python | apache-2.0 | radioboyQ/EmpireAPIWrapper | ---
+++
@@ -0,0 +1,12 @@
+import EmpireAPIWrapper
+
+api = EmpireAPIWrapper.empireAPI('10.15.20.157', uname='empireadmin', passwd='Password123!')
+# api = EmpireAPIWrapper.empireAPI('10.15.20.157', token='2zqb4bgvoq1jhe9essncl3qa6h9rvbj1jq2p740k')
+# api = EmpireAPIWrapper.empireAPI('10.15.20.157', token='yv42s1wlo90ikrzc7pwebgrbpqnzkigqlxbb4cp2')
+
+# print(api.check_version())
+# print(api.shutdownServer())
+# print(api.restartServer())
+# print(api.getMap())
+# print(api.getConfig())
+# print(api.getPermToken()) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.