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
|
|---|---|---|---|---|---|---|---|---|---|---|
ddbce972db10ce92a79982161355ed978fb0c554
|
web/extras/contentment/components/event/model.py
|
web/extras/contentment/components/event/model.py
|
# encoding: utf-8
"""Event model."""
import mongoengine as db
from web.extras.contentment.components.page.model import Page
from widgets import fields
log = __import__('logging').getLogger(__name__)
__all__ = ['EventContact', 'Event']
class EventContact(db.EmbeddedDocument):
name = db.StringField(max_length=250)
email = db.StringField(max_length=250)
phone = db.StringField(max_length=64)
class Event(Page):
_widgets = fields
default = db.StringField(default="view:event", max_length=128)
organizer = db.StringField(max_length=250)
location = db.StringField(max_length=250)
starts = db.DateTimeField()
stops = db.DateTimeField()
allday = db.BooleanField(default=False)
contact = db.EmbeddedDocumentField(EventContact)
|
# encoding: utf-8
"""Event model."""
import mongoengine as db
from web.extras.contentment.components.page.model import Page
from widgets import fields
log = __import__('logging').getLogger(__name__)
__all__ = ['EventContact', 'Event']
class EventContact(db.EmbeddedDocument):
name = db.StringField(max_length=250)
email = db.StringField(max_length=250)
phone = db.StringField(max_length=64)
class Event(Page):
_widgets = fields
default = db.StringField(default="view:event", max_length=128)
organizer = db.StringField(max_length=250)
location = db.StringField(max_length=250)
starts = db.DateTimeField()
stops = db.DateTimeField()
allday = db.BooleanField(default=False)
contact = db.EmbeddedDocumentField(EventContact)
def process(self, formdata):
formdata = super(Event, self).process(formdata)
contact = EventContact()
for field in 'name', 'email', 'phone':
combined = 'contact.' + field
if combined in formdata:
setattr(contact, field, formdata[combined])
del formdata[combined]
formdata['contact'] = contact
return formdata
|
Fix for inability to define contact information.
|
Fix for inability to define contact information.
|
Python
|
mit
|
marrow/contentment,marrow/contentment
|
---
+++
@@ -30,3 +30,19 @@
stops = db.DateTimeField()
allday = db.BooleanField(default=False)
contact = db.EmbeddedDocumentField(EventContact)
+
+ def process(self, formdata):
+ formdata = super(Event, self).process(formdata)
+
+ contact = EventContact()
+
+ for field in 'name', 'email', 'phone':
+ combined = 'contact.' + field
+ if combined in formdata:
+ setattr(contact, field, formdata[combined])
+ del formdata[combined]
+
+ formdata['contact'] = contact
+
+ return formdata
+
|
6206edd72ffb4d742f1466a5e60283b01ecca4ca
|
tests/sample_script.py
|
tests/sample_script.py
|
#!/usr/bin/env python2
import os
import time
from expjobs.helpers import run_class
class DummyWorker(object):
param = 2
def set_out_path_and_name(self, path, name):
self.out_path = path
self.out_name = name
def run(self):
print('Running {}...'.format(self.param))
time.sleep(.01)
out_file = os.path.join(self.out_path, self.out_name + '.result')
with open(out_file, 'w+') as f:
f.write('Done.')
@classmethod
def load_from_serialized(cls, cfg):
worker = cls()
with open(cfg, 'r+') as f:
cls.param = int(f.read())
return worker
run_class(DummyWorker)
|
#!/usr/bin/env python
import os
import time
from expjobs.helpers import run_class
class DummyWorker(object):
param = 2
def set_out_path_and_name(self, path, name):
self.out_path = path
self.out_name = name
def run(self):
print('Running {}...'.format(self.param))
time.sleep(.01)
out_file = os.path.join(self.out_path, self.out_name + '.result')
with open(out_file, 'w+') as f:
f.write('Done.')
@classmethod
def load_from_serialized(cls, cfg):
worker = cls()
with open(cfg, 'r+') as f:
cls.param = int(f.read())
return worker
run_class(DummyWorker)
|
Test script now against default python version.
|
Test script now against default python version.
|
Python
|
bsd-3-clause
|
omangin/expjobs
|
---
+++
@@ -1,4 +1,4 @@
-#!/usr/bin/env python2
+#!/usr/bin/env python
import os
|
0ea9fedf3eac7d8b6a7a85bd0b08fb30f35e4f4d
|
tests/test_analysis.py
|
tests/test_analysis.py
|
from sharepa.analysis import merge_dataframes
import pandas as pd
def test_merge_dataframes():
dream = pd.DataFrame({'Rhodes': 'Dusty'}, index=['Rhodes'])
stardust = pd.DataFrame({'Rhodes': 'Cody'}, index=['Rhodes'])
family = merge_dataframes(dream, stardust)
assert isinstance(family, pd.core.frame.DataFrame)
assert family.columns.values.tolist() == ['Rhodes', 'Rhodes']
|
from sharepa.analysis import merge_dataframes
import pandas as pd
def test_merge_dataframes():
dream = pd.DataFrame({'Rhodes': 'Dusty'}, index=['Rhodes'])
stardust = pd.DataFrame({'Rhodes': 'Cody'}, index=['Rhodes'])
family = merge_dataframes(dream, stardust)
assert isinstance(family, pd.core.frame.DataFrame)
assert family.columns.values.tolist() == ['Rhodes', 'Rhodes']
assert family.index.item() == 'Rhodes'
|
Check index on merge datadrame test
|
Check index on merge datadrame test
|
Python
|
mit
|
CenterForOpenScience/sharepa,samanehsan/sharepa,erinspace/sharepa,fabianvf/sharepa
|
---
+++
@@ -11,3 +11,4 @@
assert isinstance(family, pd.core.frame.DataFrame)
assert family.columns.values.tolist() == ['Rhodes', 'Rhodes']
+ assert family.index.item() == 'Rhodes'
|
c2a9c8ddc7294dcb0ff94c0b369c0f67c3d97f19
|
ureport/stats/tasks.py
|
ureport/stats/tasks.py
|
import logging
import time
from dash.orgs.tasks import org_task
logger = logging.getLogger(__name__)
@org_task("refresh-engagement-data", 60 * 60)
def refresh_engagement_data(org, since, until):
from .models import PollStats
start = time.time()
time_filters = list(PollStats.DATA_TIME_FILTERS.keys())
segments = list(PollStats.DATA_SEGMENTS.keys())
metrics = list(PollStats.DATA_METRICS.keys())
for time_filter in time_filters:
for segment in segments:
for metric in metrics:
PollStats.refresh_engagement_data(org, metric, segment, time_filter)
logger.info(
f"Task: refresh_engagement_data org {org.id} in progress for {time.time() - start}s, for time_filter - {time_filter}, segment - {segment}, metric - {metric}"
)
PollStats.calculate_average_response_rate(org)
logger.info(f"Task: refresh_engagement_data org {org.id} finished in {time.time() - start}s")
|
import logging
import time
from dash.orgs.tasks import org_task
logger = logging.getLogger(__name__)
@org_task("refresh-engagement-data", 60 * 60 * 4)
def refresh_engagement_data(org, since, until):
from .models import PollStats
start = time.time()
time_filters = list(PollStats.DATA_TIME_FILTERS.keys())
segments = list(PollStats.DATA_SEGMENTS.keys())
metrics = list(PollStats.DATA_METRICS.keys())
for time_filter in time_filters:
for segment in segments:
for metric in metrics:
PollStats.refresh_engagement_data(org, metric, segment, time_filter)
logger.info(
f"Task: refresh_engagement_data org {org.id} in progress for {time.time() - start}s, for time_filter - {time_filter}, segment - {segment}, metric - {metric}"
)
PollStats.calculate_average_response_rate(org)
logger.info(f"Task: refresh_engagement_data org {org.id} finished in {time.time() - start}s")
|
Increase lock timeout for refreshing engagement data task
|
Increase lock timeout for refreshing engagement data task
|
Python
|
agpl-3.0
|
Ilhasoft/ureport,rapidpro/ureport,rapidpro/ureport,Ilhasoft/ureport,rapidpro/ureport,Ilhasoft/ureport,Ilhasoft/ureport,rapidpro/ureport
|
---
+++
@@ -6,7 +6,7 @@
logger = logging.getLogger(__name__)
-@org_task("refresh-engagement-data", 60 * 60)
+@org_task("refresh-engagement-data", 60 * 60 * 4)
def refresh_engagement_data(org, since, until):
from .models import PollStats
|
1d0da246b5340b4822d2c47c79519edd7b9ed7e4
|
turbo_hipster/task_plugins/shell_script/task.py
|
turbo_hipster/task_plugins/shell_script/task.py
|
# Copyright 2013 Rackspace Australia
#
# 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 logging
from turbo_hipster.lib import models
class Runner(models.ShellTask):
""" This thread handles the actual sql-migration tests.
It pulls in a gearman job from the build:gate-real-db-upgrade
queue and runs it through _handle_patchset"""
log = logging.getLogger("task_plugins.gate_real_db_upgrade.task.Runner")
|
# Copyright 2013 Rackspace Australia
#
# 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 logging
from turbo_hipster.lib import models
class Runner(models.ShellTask):
"""A plugin to run any shell script as defined in the config. Based on
models.ShellTask the steps can be overwritten."""
log = logging.getLogger("task_plugins.gate_real_db_upgrade.task.Runner")
|
Fix docstring on shell_script plugin
|
Fix docstring on shell_script plugin
Change-Id: I6e92a00c72d5ee054186f93cf344df98930cdd13
|
Python
|
apache-2.0
|
stackforge/turbo-hipster,matthewoliver/turbo-hipster,matthewoliver/turbo-hipster,stackforge/turbo-hipster
|
---
+++
@@ -20,8 +20,7 @@
class Runner(models.ShellTask):
- """ This thread handles the actual sql-migration tests.
- It pulls in a gearman job from the build:gate-real-db-upgrade
- queue and runs it through _handle_patchset"""
+ """A plugin to run any shell script as defined in the config. Based on
+ models.ShellTask the steps can be overwritten."""
log = logging.getLogger("task_plugins.gate_real_db_upgrade.task.Runner")
|
62f842d91b5819e24b0be71743953d7607cf99c1
|
test_algebra_initialisation.py
|
test_algebra_initialisation.py
|
from __future__ import absolute_import, division
from __future__ import print_function, unicode_literals
from past.builtins import range
from clifford import Cl, randomMV, Frame, get_mult_function, conformalize, grade_obj
from clifford.tools import orthoFrames2Verser as of2v
import numpy as np
from numpy import exp, float64, testing
import unittest
import itertools
import time
from nose.plugins.skip import SkipTest
class InitialisationSpeedTests(unittest.TestCase):
def test_speed(self):
algebras = [2,3,4,5,6,7,8]
t_start = time.time()
for i in algebras:
Cl(i)
print(time.time() - t_start)
if __name__ == '__main__':
unittest.main()
|
from __future__ import absolute_import, division
from __future__ import print_function, unicode_literals
from past.builtins import range
from clifford import Cl, randomMV, Frame, get_mult_function, conformalize, grade_obj
from clifford.tools import orthoFrames2Verser as of2v
import numpy as np
from numpy import exp, float64, testing
import unittest
import itertools
import time
from nose.plugins.skip import SkipTest
class InitialisationSpeedTests(unittest.TestCase):
def test_speed(self):
algebras = range(2,9)
print() # So that the first number is on a new line
for i in algebras:
t_start = time.time()
Cl(i)
t_end = time.time()
print(i, t_end - t_start)
if __name__ == '__main__':
unittest.main()
|
Move start-time calculation so it measures each initialization
|
Move start-time calculation so it measures each initialization
|
Python
|
bsd-3-clause
|
arsenovic/clifford,arsenovic/clifford
|
---
+++
@@ -17,11 +17,13 @@
class InitialisationSpeedTests(unittest.TestCase):
def test_speed(self):
- algebras = [2,3,4,5,6,7,8]
- t_start = time.time()
+ algebras = range(2,9)
+ print() # So that the first number is on a new line
for i in algebras:
+ t_start = time.time()
Cl(i)
- print(time.time() - t_start)
+ t_end = time.time()
+ print(i, t_end - t_start)
if __name__ == '__main__':
unittest.main()
|
1db07b9a534e533200f83de4f86d854d0bcda087
|
examples/exotica_examples/tests/runtest.py
|
examples/exotica_examples/tests/runtest.py
|
#!/usr/bin/env python
# This is a workaround for liburdf.so throwing an exception and killing
# the process on exit in ROS Indigo.
import subprocess
import os
import sys
cpptests = ['test_initializers',
'test_maps'
]
pytests = ['core.py',
'valkyrie_com.py',
'valkyrie_collision_check_fcl_default.py',
'valkyrie_collision_check_fcl_latest.py'
]
for test in cpptests:
process=subprocess.Popen(['rosrun', 'exotica_examples', test],stdout=subprocess.PIPE, stderr=subprocess.PIPE)
output = process.stdout.readlines()
print(''.join(output))
if process.wait()!=0:
print('Test '+test+' failed\n'+process.stderr.read())
os._exit(1)
for test in pytests:
process=subprocess.Popen(['rosrun', 'exotica_examples', test],stdout=subprocess.PIPE, stderr=subprocess.PIPE)
output = process.stdout.readlines()
print(''.join(output))
if output[-1][0:11]!='>>SUCCESS<<':
print('Test '+test+' failed\n'+process.stderr.read())
os._exit(1)
|
#!/usr/bin/env python
# This is a workaround for liburdf.so throwing an exception and killing
# the process on exit in ROS Indigo.
import subprocess
import os
import sys
cpptests = ['test_initializers',
'test_maps'
]
pytests = ['core.py',
'valkyrie_com.py',
'valkyrie_collision_check_fcl_default.py',
'valkyrie_collision_check_fcl_latest.py',
'collision_scene_distances.py'
]
for test in cpptests:
process=subprocess.Popen(['rosrun', 'exotica_examples', test],stdout=subprocess.PIPE, stderr=subprocess.PIPE)
output = process.stdout.readlines()
print(''.join(output))
if process.wait()!=0:
print('Test '+test+' failed\n'+process.stderr.read())
os._exit(1)
for test in pytests:
process=subprocess.Popen(['rosrun', 'exotica_examples', test],stdout=subprocess.PIPE, stderr=subprocess.PIPE)
output = process.stdout.readlines()
print(''.join(output))
if output[-1][0:11]!='>>SUCCESS<<':
print('Test '+test+' failed\n'+process.stderr.read())
os._exit(1)
|
Add collision_scene_distances to set of tests to run
|
Add collision_scene_distances to set of tests to run
|
Python
|
bsd-3-clause
|
openhumanoids/exotica,openhumanoids/exotica,openhumanoids/exotica,openhumanoids/exotica
|
---
+++
@@ -13,7 +13,8 @@
pytests = ['core.py',
'valkyrie_com.py',
'valkyrie_collision_check_fcl_default.py',
- 'valkyrie_collision_check_fcl_latest.py'
+ 'valkyrie_collision_check_fcl_latest.py',
+ 'collision_scene_distances.py'
]
for test in cpptests:
|
66db08483faa1ca2b32a7349dafa94acb89b059c
|
locations/pipelines.py
|
locations/pipelines.py
|
# -*- coding: utf-8 -*-
# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html
from scrapy.exceptions import DropItem
class DuplicatesPipeline(object):
def __init__(self):
self.ids_seen = set()
def process_item(self, item, spider):
ref = item['ref']
if ref in self.ids_seen:
raise DropItem("Duplicate item found: %s" % item)
else:
self.ids_seen.add(ref)
return item
|
# -*- coding: utf-8 -*-
# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html
from scrapy.exceptions import DropItem
class DuplicatesPipeline(object):
def __init__(self):
self.ids_seen = set()
def process_item(self, item, spider):
ref = item['ref']
if ref in self.ids_seen:
raise DropItem("Duplicate item found: %s" % item)
else:
self.ids_seen.add(ref)
return item
class ApplySpiderNamePipeline(object):
def process_item(self, item, spider):
existing_extras = item.get('extras', {})
existing_extras['@spider'] = spider.name
item['extras'] = existing_extras
return item
|
Add pipeline step that adds spider name to properties
|
Add pipeline step that adds spider name to properties
|
Python
|
mit
|
iandees/all-the-places,iandees/all-the-places,iandees/all-the-places
|
---
+++
@@ -19,3 +19,13 @@
else:
self.ids_seen.add(ref)
return item
+
+
+class ApplySpiderNamePipeline(object):
+
+ def process_item(self, item, spider):
+ existing_extras = item.get('extras', {})
+ existing_extras['@spider'] = spider.name
+ item['extras'] = existing_extras
+
+ return item
|
74506160831ec44f29b82ca02ff131b00ce91847
|
masters/master.chromiumos.tryserver/master_site_config.py
|
masters/master.chromiumos.tryserver/master_site_config.py
|
# Copyright 2014 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.
"""ActiveMaster definition."""
from config_bootstrap import Master
class ChromiumOSTryServer(Master.ChromiumOSBase):
project_name = 'ChromiumOS Try Server'
master_port = 8049
slave_port = 8149
master_port_alt = 8249
try_job_port = 8349
buildbot_url = 'http://chromegw/p/tryserver.chromiumos/'
repo_url_ext = 'https://chromium.googlesource.com/chromiumos/tryjobs.git'
repo_url_int = 'https://chrome-internal.googlesource.com/chromeos/tryjobs.git'
from_address = 'cros.tryserver@chromium.org'
# The reply-to address to set for emails sent from the server.
reply_to = 'chromeos-build@google.com'
# Select tree status urls and codereview location.
base_app_url = 'https://chromiumos-status.appspot.com'
tree_status_url = base_app_url + '/status'
|
# Copyright 2014 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.
"""ActiveMaster definition."""
from config_bootstrap import Master
class ChromiumOSTryServer(Master.ChromiumOSBase):
project_name = 'ChromiumOS Try Server'
master_port = 8049
slave_port = 8149
master_port_alt = 8249
try_job_port = 8349
buildbot_url = 'https://uberchromegw.corp.google.com/p/tryserver.chromiumos/'
repo_url_ext = 'https://chromium.googlesource.com/chromiumos/tryjobs.git'
repo_url_int = 'https://chrome-internal.googlesource.com/chromeos/tryjobs.git'
from_address = 'cros.tryserver@chromium.org'
# The reply-to address to set for emails sent from the server.
reply_to = 'chromeos-build@google.com'
# Select tree status urls and codereview location.
base_app_url = 'https://chromiumos-status.appspot.com'
tree_status_url = base_app_url + '/status'
|
Use UberProxy URL for 'tryserver.chromiumos'
|
Use UberProxy URL for 'tryserver.chromiumos'
BUG=352897
TEST=None
Review URL: https://codereview.chromium.org/554383002
git-svn-id: 239fca9b83025a0b6f823aeeca02ba5be3d9fd76@291886 0039d316-1c4b-4281-b951-d872f2087c98
|
Python
|
bsd-3-clause
|
eunchong/build,eunchong/build,eunchong/build,eunchong/build
|
---
+++
@@ -12,7 +12,7 @@
slave_port = 8149
master_port_alt = 8249
try_job_port = 8349
- buildbot_url = 'http://chromegw/p/tryserver.chromiumos/'
+ buildbot_url = 'https://uberchromegw.corp.google.com/p/tryserver.chromiumos/'
repo_url_ext = 'https://chromium.googlesource.com/chromiumos/tryjobs.git'
repo_url_int = 'https://chrome-internal.googlesource.com/chromeos/tryjobs.git'
from_address = 'cros.tryserver@chromium.org'
|
7c9ed9fbdc1b16ae1d59c1099e7190e6297bf584
|
util/chplenv/chpl_tasks.py
|
util/chplenv/chpl_tasks.py
|
#!/usr/bin/env python
import sys, os
import chpl_arch, chpl_platform, chpl_compiler
from utils import memoize
import utils
@memoize
def get():
tasks_val = os.environ.get('CHPL_TASKS')
if not tasks_val:
arch_val = chpl_arch.get('target', get_lcd=True)
platform_val = chpl_platform.get()
compiler_val = chpl_compiler.get('target')
# use muxed on cray-x* machines using the module and supported compiler
if (platform_val.startswith('cray-x') and
utils.using_chapel_module() and
compiler_val in ('cray-prgenv-gnu', 'cray-prgenv-intel') and
arch_val != 'knc'):
tasks_val = 'muxed'
elif (arch_val == 'knc' or
platform_val.startswith('cygwin') or
platform_val.startswith('netbsd') or
compiler_val == 'cray-prgenv-cray'):
tasks_val = 'fifo'
else:
tasks_val = 'qthreads'
return tasks_val
def _main():
tasks_val = get()
sys.stdout.write("{0}\n".format(tasks_val))
if __name__ == '__main__':
_main()
|
#!/usr/bin/env python
import sys, os
import chpl_arch, chpl_platform, chpl_compiler, chpl_comm
from utils import memoize
import utils
@memoize
def get():
tasks_val = os.environ.get('CHPL_TASKS')
if not tasks_val:
arch_val = chpl_arch.get('target', get_lcd=True)
platform_val = chpl_platform.get()
compiler_val = chpl_compiler.get('target')
comm_val = chpl_comm.get()
# use muxed on cray-x* machines using the module and supported compiler
if (comm_val == 'ugni' and
platform_val.startswith('cray-x') and
utils.using_chapel_module() and
compiler_val in ('cray-prgenv-gnu', 'cray-prgenv-intel') and
arch_val != 'knc'):
tasks_val = 'muxed'
elif (arch_val == 'knc' or
platform_val.startswith('cygwin') or
platform_val.startswith('netbsd') or
compiler_val == 'cray-prgenv-cray'):
tasks_val = 'fifo'
else:
tasks_val = 'qthreads'
return tasks_val
def _main():
tasks_val = get()
sys.stdout.write("{0}\n".format(tasks_val))
if __name__ == '__main__':
_main()
|
Update chpl_task to only default to muxed when ugni comm is used.
|
Update chpl_task to only default to muxed when ugni comm is used.
This expands upon (and fixes) #1640 and #1635.
* [ ] Run printchplenv on mac and confirm it still works.
* [ ] Emulate cray-x* with module and confirm comm, tasks are ugni, muxed.
```bash
(
export CHPL_MODULE_HOME=$CHPL_HOME
export CHPL_HOST_PLATFORM=cray-xc
export CHPL_TARGET_COMPILER=cray-prgenv-gnu
printchplenv
)
```
* [ ] Emulate cray-x* with module but not supported compiler and confirm comm, tasks are gasnet, default tasks.
```bash
(
export CHPL_MODULE_HOME=$CHPL_HOME
export CHPL_HOST_PLATFORM=cray-xc
export CHPL_TARGET_COMPILER=cray-prgenv-cray
printchplenv
)
```
* [ ] Emulate cray-x* without module and confirm comm, tasks settings are gasnet, default tasks.
```bash
(
export CHPL_HOST_PLATFORM=cray-xc
export CHPL_TARGET_COMPILER=cray-prgenv-gnu
printchplenv
)
```
* [ ] Emulate cray-x* with module and intel compiler, but knc target arch and confirm comm, tasks are gasnet, default tasks.
```bash
(
export CHPL_MODULE_HOME=$CHPL_HOME
export CHPL_HOST_PLATFORM=cray-xc
export CHPL_TARGET_COMPILER=cray-prgenv-intel
export CRAY_CPU_TARGET=knc
printchplenv
)
```
* [ ] Emulate cray-x* with module, supported compiler, but none ugni comm and confirm tasks are default tasks.
```bash
(
export CHPL_MODULE_HOME=$CHPL_HOME
export CHPL_HOST_PLATFORM=cray-xc
export CHPL_TARGET_COMPILER=cray-prgenv-gnu
export CHPL_COMM=none
printchplenv
)
```
|
Python
|
apache-2.0
|
CoryMcCartan/chapel,chizarlicious/chapel,chizarlicious/chapel,hildeth/chapel,CoryMcCartan/chapel,chizarlicious/chapel,CoryMcCartan/chapel,chizarlicious/chapel,chizarlicious/chapel,CoryMcCartan/chapel,hildeth/chapel,CoryMcCartan/chapel,chizarlicious/chapel,hildeth/chapel,hildeth/chapel,hildeth/chapel,hildeth/chapel,hildeth/chapel,chizarlicious/chapel,CoryMcCartan/chapel,CoryMcCartan/chapel
|
---
+++
@@ -1,7 +1,7 @@
#!/usr/bin/env python
import sys, os
-import chpl_arch, chpl_platform, chpl_compiler
+import chpl_arch, chpl_platform, chpl_compiler, chpl_comm
from utils import memoize
import utils
@@ -12,9 +12,11 @@
arch_val = chpl_arch.get('target', get_lcd=True)
platform_val = chpl_platform.get()
compiler_val = chpl_compiler.get('target')
+ comm_val = chpl_comm.get()
# use muxed on cray-x* machines using the module and supported compiler
- if (platform_val.startswith('cray-x') and
+ if (comm_val == 'ugni' and
+ platform_val.startswith('cray-x') and
utils.using_chapel_module() and
compiler_val in ('cray-prgenv-gnu', 'cray-prgenv-intel') and
arch_val != 'knc'):
|
88242d5949dd799b03375834b5583a0c6b405f81
|
nofu.py
|
nofu.py
|
import random
from flask import Flask, render_template, abort, redirect, request
app = Flask(__name__)
questions = [{
'question': 'How many shillings were there in a pre-decimalisation pound?',
'answer': '20',
'red_herrings': [
'5',
'10',
'12',
'25',
'50',
'120',
]
}]
@app.route('/')
def index():
q = random.randint(0, len(questions) - 1)
return redirect('/q/%d/' % q)
@app.route('/a/<int:id>/')
def answer(id):
try:
question = questions[id]
except IndexError:
abort(404)
answer = request.args['a']
return render_template(
'answer.html', question=question,
given=answer,
is_correct=(answer == question['answer'])
)
@app.route('/q/<int:id>/')
def question(id):
try:
question = questions[id]
except IndexError:
abort(404)
red_herrings = random.sample(question['red_herrings'], 3)
answers = red_herrings + [question['answer']]
random.shuffle(answers)
return render_template(
'question.html',
id=id,
question=question['question'],
answers=answers
)
if __name__ == '__main__':
app.run(debug=True)
|
import random
import json
from flask import Flask, render_template, abort, redirect, request
app = Flask(__name__)
questions = [{
'question': 'How many shillings were there in a pre-decimalisation pound?',
'answer': '20',
'red_herrings': [
'5',
'10',
'12',
'25',
'50',
'120',
]
}] + json.load(open('disney_answers.json'))
@app.route('/')
def index():
q = random.randint(0, len(questions) - 1)
return redirect('/q/%d/' % q)
@app.route('/a/<int:id>/')
def answer(id):
try:
question = questions[id]
except IndexError:
abort(404)
answer = request.args['a']
return render_template(
'answer.html', question=question,
given=answer,
is_correct=(answer == question['answer'])
)
@app.route('/q/<int:id>/')
def question(id):
try:
question = questions[id]
except IndexError:
abort(404)
red_herrings = random.sample(question['red_herrings'], 3)
answers = red_herrings + [question['answer']]
random.shuffle(answers)
return render_template(
'question.html',
id=id,
question=question['question'],
answers=answers
)
if __name__ == '__main__':
app.run(debug=True)
|
Integrate answers with Flask frontend
|
Integrate answers with Flask frontend
|
Python
|
mit
|
lordmauve/nofu,lordmauve/nofu
|
---
+++
@@ -1,4 +1,5 @@
import random
+import json
from flask import Flask, render_template, abort, redirect, request
@@ -16,7 +17,7 @@
'50',
'120',
]
-}]
+}] + json.load(open('disney_answers.json'))
@app.route('/')
|
4223ad57994fe87fe0be9b80c8070c3f4b77a071
|
contrib/hooks/post-receive/mail_notifications.py
|
contrib/hooks/post-receive/mail_notifications.py
|
#! /usr/bin/env python3
import sys
import os
import git_multimail
# It is possible to modify the output templates here; e.g.:
git_multimail.FOOTER_TEMPLATE = """\
-- \n\
This email was generated by the wonderful git-multimail tool from JBox Web.
"""
# Specify which "git config" section contains the configuration for
# git-multimail:
config = git_multimail.Config('multimailhook')
# check if hook is enabled
enabled = config.get_bool('enabled')
if enabled:
# Select the type of environment:
environment = git_multimail.GitoliteEnvironment(config=config)
# Choose the method of sending emails based on the git config:
mailer = git_multimail.choose_mailer(config, environment)
# Read changes from stdin and send notification emails:
git_multimail.run_as_post_receive_hook(environment, mailer)
else:
print(" multimailhook is disabled")
|
#! /usr/bin/env python
import sys
import os
import git_multimail
# It is possible to modify the output templates here; e.g.:
git_multimail.FOOTER_TEMPLATE = """\
-- \n\
This email was generated by the wonderful git-multimail tool from JBox Web.
"""
# Specify which "git config" section contains the configuration for
# git-multimail:
config = git_multimail.Config('multimailhook')
# check if hook is enabled
enabled = config.get_bool('enabled')
if enabled:
# Select the type of environment:
environment = git_multimail.GitoliteEnvironment(config=config)
# Choose the method of sending emails based on the git config:
mailer = git_multimail.choose_mailer(config, environment)
# Read changes from stdin and send notification emails:
git_multimail.run_as_post_receive_hook(environment, mailer)
else:
print(" multimailhook is disabled")
|
Support both python 2 and 3
|
Support both python 2 and 3
|
Python
|
mit
|
jbox-web/redmine_git_hosting,jbox-web/redmine_git_hosting,jbox-web/redmine_git_hosting,jbox-web/redmine_git_hosting
|
---
+++
@@ -1,4 +1,4 @@
-#! /usr/bin/env python3
+#! /usr/bin/env python
import sys
import os
|
31eb2bd7dee5a28f181d3eb8f923a9cdda198a47
|
flocker/__init__.py
|
flocker/__init__.py
|
# Copyright Hybrid Logic Ltd. See LICENSE file for details.
# -*- test-case-name: flocker.test -*-
"""
Flocker is a hypervisor that provides ZFS-based replication and fail-over
functionality to a Linux-based user-space operating system.
"""
import sys
import os
def _logEliotMessage(data):
"""
Route a serialized Eliot log message to the Twisted log.
:param data: ``bytes``, a serialized message.
"""
from twisted.python.log import msg
from json import loads
msg("ELIOT: " + data)
if "eliot:traceback" in data:
# Don't bother decoding every single log message...
decoded = loads(data)
if decoded.get(u"message_type") == u"eliot:traceback":
msg("ELIOT Extracted Traceback:\n" + decoded["traceback"])
# Ugly but convenient. There should be some better way to do this...
if sys.argv and os.path.basename(sys.argv[0]) == 'trial':
from eliot import addDestination
addDestination(_logEliotMessage)
del addDestination
|
# Copyright Hybrid Logic Ltd. See LICENSE file for details.
# -*- test-case-name: flocker.test -*-
"""
Flocker is a hypervisor that provides ZFS-based replication and fail-over
functionality to a Linux-based user-space operating system.
"""
import sys
import os
def _logEliotMessage(data):
"""
Route a serialized Eliot log message to the Twisted log.
:param data: ``bytes``, a serialized message.
"""
from twisted.python.log import msg
from json import loads
msg("ELIOT: " + data)
if "eliot:traceback" in data:
# Don't bother decoding every single log message...
decoded = loads(data)
if decoded.get(u"message_type") == u"eliot:traceback":
msg("ELIOT Extracted Traceback:\n" + decoded["traceback"])
# Ugly but convenient. There should be some better way to do this...
# See https://twistedmatrix.com/trac/ticket/6939
if sys.argv and os.path.basename(sys.argv[0]) == 'trial':
from eliot import addDestination
addDestination(_logEliotMessage)
del addDestination
|
Address review comment: Add link to upstream ticket.
|
Address review comment: Add link to upstream ticket.
|
Python
|
apache-2.0
|
hackday-profilers/flocker,LaynePeng/flocker,wallnerryan/flocker-profiles,runcom/flocker,AndyHuu/flocker,achanda/flocker,wallnerryan/flocker-profiles,hackday-profilers/flocker,lukemarsden/flocker,runcom/flocker,moypray/flocker,moypray/flocker,moypray/flocker,LaynePeng/flocker,agonzalezro/flocker,adamtheturtle/flocker,lukemarsden/flocker,w4ngyi/flocker,adamtheturtle/flocker,w4ngyi/flocker,adamtheturtle/flocker,jml/flocker,jml/flocker,AndyHuu/flocker,Azulinho/flocker,Azulinho/flocker,beni55/flocker,1d4Nf6/flocker,achanda/flocker,agonzalezro/flocker,hackday-profilers/flocker,beni55/flocker,wallnerryan/flocker-profiles,mbrukman/flocker,1d4Nf6/flocker,achanda/flocker,agonzalezro/flocker,runcom/flocker,jml/flocker,beni55/flocker,lukemarsden/flocker,w4ngyi/flocker,mbrukman/flocker,1d4Nf6/flocker,AndyHuu/flocker,mbrukman/flocker,LaynePeng/flocker,Azulinho/flocker
|
---
+++
@@ -28,6 +28,7 @@
# Ugly but convenient. There should be some better way to do this...
+# See https://twistedmatrix.com/trac/ticket/6939
if sys.argv and os.path.basename(sys.argv[0]) == 'trial':
from eliot import addDestination
addDestination(_logEliotMessage)
|
ae3a61b88c032c9188324bb17128fd060ac1ac2a
|
magazine/utils.py
|
magazine/utils.py
|
import bleach
from lxml.html.clean import Cleaner
allowed_tags = bleach.ALLOWED_TAGS + ['p', 'h1', 'h2', 'h3', 'h4', 'h5',]
allowed_attributes = bleach.ALLOWED_ATTRIBUTES.copy()
allowed_attributes['a'] = bleach.ALLOWED_ATTRIBUTES['a'] + ['name']
def clean_word_text(text):
# The only thing I need Cleaner for is to clear out the contents of
# <style>...</style> tags
cleaner = Cleaner(style = True)
text = cleaner.clean_html(text)
text = bleach.clean(text, tags = allowed_tags, strip = True, attributes = allowed_attributes)
return text
|
import bleach
try:
from lxml.html.clean import Cleaner
HAS_LXML = True
except ImportError:
HAS_LXML = False
allowed_tags = bleach.ALLOWED_TAGS + ['p', 'h1', 'h2', 'h3', 'h4', 'h5',]
allowed_attributes = bleach.ALLOWED_ATTRIBUTES.copy()
allowed_attributes['a'] = bleach.ALLOWED_ATTRIBUTES['a'] + ['name']
def clean_word_text(text):
if HAS_LXML:
# The only thing I need Cleaner for is to clear out the contents of
# <style>...</style> tags
cleaner = Cleaner(style = True)
text = cleaner.clean_html(text)
text = bleach.clean(text, tags = allowed_tags, strip = True, attributes = allowed_attributes)
return text
|
Make the dependency on lxml optional.
|
Make the dependency on lxml optional.
|
Python
|
mit
|
dominicrodger/django-magazine,dominicrodger/django-magazine
|
---
+++
@@ -1,15 +1,20 @@
import bleach
-from lxml.html.clean import Cleaner
+try:
+ from lxml.html.clean import Cleaner
+ HAS_LXML = True
+except ImportError:
+ HAS_LXML = False
allowed_tags = bleach.ALLOWED_TAGS + ['p', 'h1', 'h2', 'h3', 'h4', 'h5',]
allowed_attributes = bleach.ALLOWED_ATTRIBUTES.copy()
allowed_attributes['a'] = bleach.ALLOWED_ATTRIBUTES['a'] + ['name']
def clean_word_text(text):
- # The only thing I need Cleaner for is to clear out the contents of
- # <style>...</style> tags
- cleaner = Cleaner(style = True)
- text = cleaner.clean_html(text)
+ if HAS_LXML:
+ # The only thing I need Cleaner for is to clear out the contents of
+ # <style>...</style> tags
+ cleaner = Cleaner(style = True)
+ text = cleaner.clean_html(text)
text = bleach.clean(text, tags = allowed_tags, strip = True, attributes = allowed_attributes)
|
66cda3c9248c04850e89a2937a2f1457ac538bd4
|
vumi/middleware/__init__.py
|
vumi/middleware/__init__.py
|
"""Middleware classes to process messages on their way in and out of workers.
"""
from vumi.middleware.base import (
BaseMiddleware, TransportMiddleware, ApplicationMiddleware,
MiddlewareStack, create_middlewares_from_config,
setup_middlewares_from_config)
from vumi.middleware.logging import LoggingMiddleware
from vumi.middleware.tagger import TaggingMiddleware
from vumi.middleware.message_storing import StoringMiddleware
from vumi.middleware.address_translator import AddressTranslationMiddleware
__all__ = [
'BaseMiddleware', 'TransportMiddleware', 'ApplicationMiddleware',
'MiddlewareStack', 'create_middlewares_from_config',
'setup_middlewares_from_config',
'LoggingMiddleware', 'TaggingMiddleware', 'StoringMiddleware',
'AddressTranslationMiddleware']
|
"""Middleware classes to process messages on their way in and out of workers.
"""
from vumi.middleware.base import (
BaseMiddleware, TransportMiddleware, ApplicationMiddleware,
MiddlewareStack, create_middlewares_from_config,
setup_middlewares_from_config)
__all__ = [
'BaseMiddleware', 'TransportMiddleware', 'ApplicationMiddleware',
'MiddlewareStack', 'create_middlewares_from_config',
'setup_middlewares_from_config']
|
Remove package-level imports of middleware classes. This will break some configs, but they should never have been there in the first place.
|
Remove package-level imports of middleware classes. This will break some configs, but they should never have been there in the first place.
|
Python
|
bsd-3-clause
|
harrissoerja/vumi,TouK/vumi,harrissoerja/vumi,TouK/vumi,vishwaprakashmishra/xmatrix,harrissoerja/vumi,vishwaprakashmishra/xmatrix,vishwaprakashmishra/xmatrix,TouK/vumi
|
---
+++
@@ -6,14 +6,7 @@
MiddlewareStack, create_middlewares_from_config,
setup_middlewares_from_config)
-from vumi.middleware.logging import LoggingMiddleware
-from vumi.middleware.tagger import TaggingMiddleware
-from vumi.middleware.message_storing import StoringMiddleware
-from vumi.middleware.address_translator import AddressTranslationMiddleware
-
__all__ = [
'BaseMiddleware', 'TransportMiddleware', 'ApplicationMiddleware',
'MiddlewareStack', 'create_middlewares_from_config',
- 'setup_middlewares_from_config',
- 'LoggingMiddleware', 'TaggingMiddleware', 'StoringMiddleware',
- 'AddressTranslationMiddleware']
+ 'setup_middlewares_from_config']
|
19a698c9440e36e8cac80d16b295d41eb4cb05f3
|
wdbc/structures/__init__.py
|
wdbc/structures/__init__.py
|
# -*- coding: utf-8 -*-
from pywow.structures import Structure, Skeleton
from .fields import *
from .main import *
from .custom import *
from .generated import GeneratedStructure
class StructureNotFound(Exception):
pass
class StructureLoader():
wowfiles = None
@classmethod
def setup(cls):
if cls.wowfiles is None:
cls.wowfiles = {}
for name in globals():
try:
if not issubclass(globals()[name], Structure):
continue
except TypeError:
continue
cls.wowfiles[name.lower()] = globals()[name]
@classmethod
def getstructure(cls, name, build=0, parent=None):
if name in cls.wowfiles:
return cls.wowfiles[name](build, parent)
raise StructureNotFound("Structure not found for file %r" % (name))
StructureLoader.setup()
getstructure = StructureLoader.getstructure
def __update_locales(self, locales):
updated = False
for field in self:
if isinstance(field, LocalizedFields):
field.update_locales(locales)
updated = True
if not updated:
raise StructureError("No locales to update for update_locales")
Skeleton.update_locales = __update_locales
|
# -*- coding: utf-8 -*-
from pywow.structures import Structure, Skeleton
from .fields import *
from .main import *
from .custom import *
from .generated import GeneratedStructure
class StructureNotFound(Exception):
pass
class StructureLoader():
wowfiles = None
@classmethod
def setup(cls):
if cls.wowfiles is None:
cls.wowfiles = {}
for name in globals():
try:
if not issubclass(globals()[name], Structure):
continue
except TypeError:
continue
cls.wowfiles[name.lower()] = globals()[name]
@classmethod
def getstructure(cls, name, build=0, parent=None):
if name in cls.wowfiles:
return cls.wowfiles[name](build, parent)
raise StructureNotFound("Structure not found for file %r" % (name))
StructureLoader.setup()
getstructure = StructureLoader.getstructure
def __update_locales(self, locales):
updated = False
for field in self:
if isinstance(field, LocalizedFields):
field.update_locales(locales)
updated = True
if not updated:
raise StructureError("No locales to update for update_locales")
def __update_locales_cataclysm(self):
updated = False
for field in self:
if isinstance(field, LocalizedFields):
field.update_locales(("enus", ))
field.delete_locflags()
updated = True
if not updated:
raise StructureError("No locales to update for update_locales")
Skeleton.update_locales = __update_locales
Skeleton.update_locales_cataclysm = __update_locales_cataclysm
|
Add a hacky update_cataclysm_locales method to Skeleton
|
structures: Add a hacky update_cataclysm_locales method to Skeleton
|
Python
|
cc0-1.0
|
jleclanche/pywow,jleclanche/pywow,jleclanche/pywow,jleclanche/pywow,jleclanche/pywow,jleclanche/pywow
|
---
+++
@@ -44,4 +44,17 @@
if not updated:
raise StructureError("No locales to update for update_locales")
+def __update_locales_cataclysm(self):
+ updated = False
+ for field in self:
+ if isinstance(field, LocalizedFields):
+ field.update_locales(("enus", ))
+ field.delete_locflags()
+ updated = True
+
+ if not updated:
+ raise StructureError("No locales to update for update_locales")
+
+
Skeleton.update_locales = __update_locales
+Skeleton.update_locales_cataclysm = __update_locales_cataclysm
|
e7b853c667b5785355214380954c83b843c46f05
|
tests/modules/contrib/test_publicip.py
|
tests/modules/contrib/test_publicip.py
|
import pytest
from unittest import TestCase, mock
import core.config
import core.widget
import modules.contrib.publicip
def build_module():
config = core.config.Config([])
return modules.contrib.publicip.Module(config=config, theme=None)
def widget(module):
return module.widgets()[0]
class PublicIPTest(TestCase):
def test_load_module(self):
__import__("modules.contrib.publicip")
@mock.patch('util.location.public_ip')
def test_public_ip(self, public_ip_mock):
public_ip_mock.return_value = '5.12.220.2'
module = build_module()
module.update()
assert widget(module).full_text() == '5.12.220.2'
@mock.patch('util.location.public_ip')
def test_public_ip_with_exception(self, public_ip_mock):
public_ip_mock.side_effect = Exception
module = build_module()
module.update()
assert widget(module).full_text() == 'n/a'
@mock.patch('util.location.public_ip')
def test_interval_seconds(self, public_ip_mock):
public_ip_mock.side_effect = Exception
module = build_module()
assert module.parameter('interval') == 3600
|
import pytest
from unittest import TestCase, mock
import core.config
import core.widget
import modules.contrib.publicip
def build_module():
config = core.config.Config([])
return modules.contrib.publicip.Module(config=config, theme=None)
def widget(module):
return module.widgets()[0]
class PublicIPTest(TestCase):
def test_load_module(self):
__import__("modules.contrib.publicip")
@mock.patch('util.location.public_ip')
def test_public_ip(self, public_ip_mock):
public_ip_mock.return_value = '5.12.220.2'
module = build_module()
module.update()
assert widget(module).full_text() == '5.12.220.2'
@mock.patch('util.location.public_ip')
def test_public_ip_with_exception(self, public_ip_mock):
public_ip_mock.side_effect = Exception
module = build_module()
module.update()
assert widget(module).full_text() == 'n/a'
def test_interval_seconds(self):
module = build_module()
assert module.parameter('interval') == 3600
|
Remove useless mock side effect
|
Remove useless mock side effect
|
Python
|
mit
|
tobi-wan-kenobi/bumblebee-status,tobi-wan-kenobi/bumblebee-status
|
---
+++
@@ -35,10 +35,7 @@
assert widget(module).full_text() == 'n/a'
- @mock.patch('util.location.public_ip')
- def test_interval_seconds(self, public_ip_mock):
- public_ip_mock.side_effect = Exception
-
+ def test_interval_seconds(self):
module = build_module()
assert module.parameter('interval') == 3600
|
9f598b0163a7ef6392b1ea67bde43f84fd9efbb8
|
myflaskapp/tests/functional_tests.py
|
myflaskapp/tests/functional_tests.py
|
from selenium import webdriver
browser = webdriver.Chrome()
browser.get('http://localhost:5000')
assert 'tdd_with_python' in browser.title
|
from selenium import webdriver
browser = webdriver.Chrome()
# Edith has heard about a cool new online to-do app. She goes # to check out
#its homepage
browser.get('http://localhost:5000')
# She notices the page title and header mention to-do lists
assert 'To-Do' in browser.title
# She is invited to enter a to-do item straight away
# She types "Buy peacock feathers" into a text box (Edith's hobby
# is tying fly-fishing lures)
# When she hits enter, the page updates, and now the page lists
# "1: Buy peacock feathers" as an item in a to-do list
# There is still a text box inviting her to add another item. She
# enters "Use peacock feathers to make a fly" (Edith is very methodical)
# The page updates again, and now shows both items on her list
# Edith wonders whether the site will remember her list. Then she sees
# that the site has generated a unique URL for her -- there is some
# explanatory text to that effect.
# She visits that URL - her to-do list is still there.
# Satisfied, she goes back to sleep
browser.quit()
|
Change title test, add comments of To-do user story
|
Change title test, add comments of To-do user story
|
Python
|
mit
|
terryjbates/test-driven-development-with-python,terryjbates/test-driven-development-with-python,terryjbates/test-driven-development-with-python,terryjbates/test-driven-development-with-python,terryjbates/test-driven-development-with-python
|
---
+++
@@ -1,4 +1,30 @@
from selenium import webdriver
browser = webdriver.Chrome()
-browser.get('http://localhost:5000')
-assert 'tdd_with_python' in browser.title
+# Edith has heard about a cool new online to-do app. She goes # to check out
+#its homepage
+browser.get('http://localhost:5000')
+
+# She notices the page title and header mention to-do lists
+assert 'To-Do' in browser.title
+
+
+# She is invited to enter a to-do item straight away
+
+# She types "Buy peacock feathers" into a text box (Edith's hobby
+# is tying fly-fishing lures)
+
+# When she hits enter, the page updates, and now the page lists
+# "1: Buy peacock feathers" as an item in a to-do list
+
+# There is still a text box inviting her to add another item. She
+# enters "Use peacock feathers to make a fly" (Edith is very methodical)
+
+# The page updates again, and now shows both items on her list
+# Edith wonders whether the site will remember her list. Then she sees
+# that the site has generated a unique URL for her -- there is some
+# explanatory text to that effect.
+
+# She visits that URL - her to-do list is still there.
+
+# Satisfied, she goes back to sleep
+browser.quit()
|
6dc0300a35b46ba649ff655e6cb62aa57c843cff
|
navigation/templatetags/paginator.py
|
navigation/templatetags/paginator.py
|
from django import template
register = template.Library()
def paginator(context, adjacent_pages=4):
"""
To be used in conjunction with the object_list generic view.
Adds pagination context variables for use in displaying first, adjacent and
last page links in addition to those created by the object_list generic
view.
"""
page_numbers = [n for n in range(context["page"] - adjacent_pages, context["page"] + adjacent_pages + 1) if n > 0 and n <= context["pages"]]
return {
"hits": context["hits"],
"results_per_page": context["results_per_page"],
"page": context["page"],
"pages": context["pages"],
"page_numbers": page_numbers,
"next": context["next"],
"previous": context["previous"],
"has_next": context["has_next"],
"has_previous": context["has_previous"],
"show_first": 1 not in page_numbers,
"show_last": context["pages"] not in page_numbers,
}
register.inclusion_tag("navigation/paginator.html", takes_context=True)(paginator)
|
from django import template
register = template.Library()
def paginator(context, adjacent_pages=4):
"""
To be used in conjunction with the object_list generic view.
Adds pagination context variables for use in displaying first, adjacent and
last page links in addition to those created by the object_list generic
view.
"""
paginator = context["paginator"]
page_obj = context["page_obj"]
page_numbers = [n for n in range(context["page"] - adjacent_pages, context["page"] + adjacent_pages + 1) if n > 0 and n <= paginator.num_pages]
return {
"hits": paginator.count,
"page": context["page"],
"pages": paginator.num_pages,
"page_numbers": page_numbers,
"next": page_obj.next_page_number,
"previous": page_obj.previous_page_number,
"has_next": page_obj.has_next,
"has_previous": page_obj.has_previous,
"show_first": 1 not in page_numbers,
"show_last": paginator.num_pages not in page_numbers,
}
register.inclusion_tag("navigation/paginator.html", takes_context=True)(paginator)
|
Update after forum views now is class based
|
Update after forum views now is class based
|
Python
|
agpl-3.0
|
sigurdga/nidarholm,sigurdga/nidarholm,sigurdga/nidarholm
|
---
+++
@@ -10,19 +10,20 @@
last page links in addition to those created by the object_list generic
view.
"""
- page_numbers = [n for n in range(context["page"] - adjacent_pages, context["page"] + adjacent_pages + 1) if n > 0 and n <= context["pages"]]
+ paginator = context["paginator"]
+ page_obj = context["page_obj"]
+ page_numbers = [n for n in range(context["page"] - adjacent_pages, context["page"] + adjacent_pages + 1) if n > 0 and n <= paginator.num_pages]
return {
- "hits": context["hits"],
- "results_per_page": context["results_per_page"],
+ "hits": paginator.count,
"page": context["page"],
- "pages": context["pages"],
+ "pages": paginator.num_pages,
"page_numbers": page_numbers,
- "next": context["next"],
- "previous": context["previous"],
- "has_next": context["has_next"],
- "has_previous": context["has_previous"],
+ "next": page_obj.next_page_number,
+ "previous": page_obj.previous_page_number,
+ "has_next": page_obj.has_next,
+ "has_previous": page_obj.has_previous,
"show_first": 1 not in page_numbers,
- "show_last": context["pages"] not in page_numbers,
+ "show_last": paginator.num_pages not in page_numbers,
}
register.inclusion_tag("navigation/paginator.html", takes_context=True)(paginator)
|
2e78bf754b1fc1d84086e127a2dd8ae7947fbaa8
|
eva/layers/color_extract.py
|
eva/layers/color_extract.py
|
from keras import backend as K
from keras.layers import Layer
class ColorExtract(Layer):
""" TODO: Make is scalable to any amount of channels. """
def __init__(self, channel, **kwargs):
super().__init__(**kwargs)
assert channel in (0, 1, 2)
self.channel = channel
def call(self, x, mask=None):
return x[:, :, :, (self.channel*256):(self.channel+1)*256]
def get_output_shape_for(self, input_shape):
output = list(input_shape)
return (output[0], output[1], output[2], 256)
def get_config(self):
return dict(list(super().get_config().items()) + list({'channel': self.channel}.items()))
|
from keras import backend as K
from keras.layers import Layer
# TODO REMOVE
class ColorExtract(Layer):
""" TODO: Make is scalable to any amount of channels. """
def __init__(self, channel, **kwargs):
super().__init__(**kwargs)
assert channel in (0, 1, 2)
self.channel = channel
def call(self, x, mask=None):
return x[:, :, :, (self.channel*256):(self.channel+1)*256]
def get_output_shape_for(self, input_shape):
output = list(input_shape)
return (output[0], output[1], output[2], 256)
def get_config(self):
return dict(list(super().get_config().items()) + list({'channel': self.channel}.items()))
|
Add todo for color extract
|
Add todo for color extract
|
Python
|
apache-2.0
|
israelg99/eva
|
---
+++
@@ -1,7 +1,7 @@
from keras import backend as K
from keras.layers import Layer
-
+# TODO REMOVE
class ColorExtract(Layer):
""" TODO: Make is scalable to any amount of channels. """
def __init__(self, channel, **kwargs):
|
6823b063444dc6853ed524d2aad913fc0ba6c965
|
towel/templatetags/towel_batch_tags.py
|
towel/templatetags/towel_batch_tags.py
|
from django import template
register = template.Library()
@register.simple_tag
def batch_checkbox(form, id):
"""
Checkbox which allows selecting objects for batch processing::
{% for object in object_list %}
{% batch_checkbox batch_form object.id %}
{{ object }} etc...
{% endfor %}
"""
cb = u'<input type="checkbox" name="batch_%s" value="%s" class="batch" %s/>'
if id in form.ids:
return cb % (id, id, 'checked="checked" ')
return cb % (id, id, '')
|
from django import template
register = template.Library()
@register.simple_tag
def batch_checkbox(form, id):
"""
Checkbox which allows selecting objects for batch processing::
{% for object in object_list %}
{% batch_checkbox batch_form object.id %}
{{ object }} etc...
{% endfor %}
"""
cb = u'<input type="checkbox" name="batch_%s" value="%s" class="batch" %s/>'
if id in getattr(form, 'ids', []):
return cb % (id, id, 'checked="checked" ')
return cb % (id, id, '')
|
Make batch_checkbox a bit more resilient against problems with context variables
|
Make batch_checkbox a bit more resilient against problems with context variables
|
Python
|
bsd-3-clause
|
matthiask/towel,matthiask/towel,matthiask/towel,matthiask/towel
|
---
+++
@@ -17,7 +17,7 @@
cb = u'<input type="checkbox" name="batch_%s" value="%s" class="batch" %s/>'
- if id in form.ids:
+ if id in getattr(form, 'ids', []):
return cb % (id, id, 'checked="checked" ')
return cb % (id, id, '')
|
bae36d9124efcc205db7c5738c528088ff8a02ca
|
bluebottle/auth/tests/test_middleware.py
|
bluebottle/auth/tests/test_middleware.py
|
from django.test.client import RequestFactory
from bluebottle.auth.middleware import LockdownMiddleware
from bluebottle.test.utils import BluebottleTestCase
class LockdownTestCase(BluebottleTestCase):
def setUp(self):
super(LockdownTestCase, self).setUp()
def test_lockdown_page(self):
mw = LockdownMiddleware()
rf = RequestFactory()
request = rf.get('/')
request.META = {'HTTP_X_LOCKDOWN': 'sssht'}
# Mock a session
request.session = type("MockSession", (object, ), {"get": lambda self, prop: "bla"})()
response = mw.process_request(request)
self.assertEqual(response.status_code, 401)
self.assertTrue('<style>' in response.content)
|
Test lockdown and make sure it has style.
|
Test lockdown and make sure it has style.
|
Python
|
bsd-3-clause
|
onepercentclub/bluebottle,onepercentclub/bluebottle,onepercentclub/bluebottle,onepercentclub/bluebottle,onepercentclub/bluebottle
|
---
+++
@@ -0,0 +1,20 @@
+from django.test.client import RequestFactory
+
+from bluebottle.auth.middleware import LockdownMiddleware
+from bluebottle.test.utils import BluebottleTestCase
+
+
+class LockdownTestCase(BluebottleTestCase):
+ def setUp(self):
+ super(LockdownTestCase, self).setUp()
+
+ def test_lockdown_page(self):
+ mw = LockdownMiddleware()
+ rf = RequestFactory()
+ request = rf.get('/')
+ request.META = {'HTTP_X_LOCKDOWN': 'sssht'}
+ # Mock a session
+ request.session = type("MockSession", (object, ), {"get": lambda self, prop: "bla"})()
+ response = mw.process_request(request)
+ self.assertEqual(response.status_code, 401)
+ self.assertTrue('<style>' in response.content)
|
|
5872282aa73bb53fd1a91174828d82b3a5d4233a
|
roushagent/plugins/output/plugin_chef.py
|
roushagent/plugins/output/plugin_chef.py
|
#!/usr/bin/env python
import sys
from bashscriptrunner import BashScriptRunner
name = "chef"
script = BashScriptRunner(script_path=["roushagent/plugins/lib/%s" % name])
def setup(config):
LOG.debug('Doing setup in test.py')
register_action('install_chef', install_chef)
register_action('run_chef', run_chef)
def install_chef(input_data):
payload = input_data['payload']
action = input_data['action']
required = ["CHEF_SERVER", "CHEF_VALIDATOR"]
optional = ["CHEF_RUNLIST", "CHEF_ENVIRONMENT", "CHEF_VALIDATION_NAME"]
env = dict([(k, v) for k, v in payload.iteritems()
if k in required + optional])
for r in required:
if not r in env:
return {'result_code': 22,
'result_str': 'Bad Request (missing %s)' % r,
'result_data': None}
return script.run_env("install-chef.sh", env, "")
def run_chef(input_data):
payload = input_data['payload']
action = input_data['action']
return script.run("run-chef.sh")
|
#!/usr/bin/env python
import sys
import os
from bashscriptrunner import BashScriptRunner
name = "chef"
def setup(config={}):
LOG.debug('Doing setup in test.py')
plugin_dir = config.get("plugin_dir", "roushagent/plugins")
script_path = [os.path.join(plugin_dir, "lib", name)]
script = BashScriptRunner(script_path=script_path)
register_action('install_chef', lambda x: install_chef(x, script))
register_action('run_chef', lambda x: run_chef(x, script))
def install_chef(input_data, script):
payload = input_data['payload']
action = input_data['action']
required = ["CHEF_SERVER", "CHEF_VALIDATOR"]
optional = ["CHEF_RUNLIST", "CHEF_ENVIRONMENT", "CHEF_VALIDATION_NAME"]
env = dict([(k, v) for k, v in payload.iteritems()
if k in required + optional])
for r in required:
if not r in env:
return {'result_code': 22,
'result_str': 'Bad Request (missing %s)' % r,
'result_data': None}
return script.run_env("install-chef.sh", env, "")
def run_chef(input_data, script):
payload = input_data['payload']
action = input_data['action']
return script.run("run-chef.sh")
|
Use plugin_dir as base for script_path
|
Use plugin_dir as base for script_path
|
Python
|
apache-2.0
|
rcbops/opencenter-agent,rcbops/opencenter-agent
|
---
+++
@@ -1,19 +1,21 @@
#!/usr/bin/env python
import sys
+import os
from bashscriptrunner import BashScriptRunner
name = "chef"
-script = BashScriptRunner(script_path=["roushagent/plugins/lib/%s" % name])
+
+def setup(config={}):
+ LOG.debug('Doing setup in test.py')
+ plugin_dir = config.get("plugin_dir", "roushagent/plugins")
+ script_path = [os.path.join(plugin_dir, "lib", name)]
+ script = BashScriptRunner(script_path=script_path)
+ register_action('install_chef', lambda x: install_chef(x, script))
+ register_action('run_chef', lambda x: run_chef(x, script))
-def setup(config):
- LOG.debug('Doing setup in test.py')
- register_action('install_chef', install_chef)
- register_action('run_chef', run_chef)
-
-
-def install_chef(input_data):
+def install_chef(input_data, script):
payload = input_data['payload']
action = input_data['action']
required = ["CHEF_SERVER", "CHEF_VALIDATOR"]
@@ -28,7 +30,7 @@
return script.run_env("install-chef.sh", env, "")
-def run_chef(input_data):
+def run_chef(input_data, script):
payload = input_data['payload']
action = input_data['action']
return script.run("run-chef.sh")
|
a7e7320967e52f532b684ec4cb488f0d28f29038
|
citrination_client/views/model_report.py
|
citrination_client/views/model_report.py
|
from copy import deepcopy
class ModelReport(object):
"""
An abstraction of a model report that wraps access to various sections
of the report.
"""
"""
:param raw_report: the dict representation of model report JSON
:type: dict
"""
def __init__(self, raw_report):
self._raw_report = raw_report
@property
def model_name(self):
return self._raw_report['model_name']
@property
def performance(self):
return self._raw_report['error_metrics']
@property
def feature_importances(self):
return self._raw_report['feature_importances']
@property
def model_settings(self):
return self._raw_report['model_settings']
"""
WARNING - the dict format returned is unstable and may change over time.
:return: a copy of the raw report that backs the instance.
:rtype: dict
"""
def to_json(self):
return deepcopy(self._raw_report)
|
from copy import deepcopy
class ModelReport(object):
"""
An abstraction of a model report that wraps access to various sections
of the report.
"""
"""
:param raw_report: the dict representation of model report JSON
:type: dict
"""
def __init__(self, raw_report):
self._raw_report = raw_report
@property
def model_name(self):
"""
:rtype: str
"""
return self._raw_report['model_name']
@property
def performance(self):
"""
:rtype: dict
"""
return self._raw_report['error_metrics']
@property
def feature_importances(self):
"""
:rtype: list of dict
"""
return self._raw_report['feature_importances']
@property
def model_settings(self):
"""
:rtype: dict
"""
return self._raw_report['model_settings']
"""
WARNING - the dict format returned is unstable and may change over time.
:return: a copy of the raw report that backs the instance.
:rtype: dict
"""
def to_json(self):
return deepcopy(self._raw_report)
|
Add basic documentation to ModelReport
|
Add basic documentation to ModelReport
|
Python
|
apache-2.0
|
CitrineInformatics/python-citrination-client
|
---
+++
@@ -15,18 +15,30 @@
@property
def model_name(self):
+ """
+ :rtype: str
+ """
return self._raw_report['model_name']
@property
def performance(self):
+ """
+ :rtype: dict
+ """
return self._raw_report['error_metrics']
@property
def feature_importances(self):
+ """
+ :rtype: list of dict
+ """
return self._raw_report['feature_importances']
@property
def model_settings(self):
+ """
+ :rtype: dict
+ """
return self._raw_report['model_settings']
"""
|
7302cb5ca42a75ed7830327f175dba3abb75ab74
|
tests/runner.py
|
tests/runner.py
|
import sys
import pstats
import cProfile
import unittest
from django.test.simple import DjangoTestSuiteRunner
class ProfilingTestRunner(DjangoTestSuiteRunner):
def run_suite(self, suite, **kwargs):
stream = open('profiled_tests.txt', 'w')
# failfast keyword was added in Python 2.7 so we need to leave it out
# when creating the runner if we are running an older python version.
if sys.hexversion >= 0x02070000:
runner = unittest.TextTestRunner(verbosity=self.verbosity, failfast=self.failfast).run
else:
runner = unittest.TextTestRunner(verbosity=self.verbosity).run
profile = cProfile.Profile()
profile.runctx('result = run_tests(suite)', {
'run_tests': runner,
'suite': suite,
}, locals())
profile.create_stats()
stats = pstats.Stats(profile, stream=stream)
stats.sort_stats('time')
stats.print_stats()
return locals()['result']
|
import sys
import pstats
import cProfile
import unittest
from django.test.simple import DjangoTestSuiteRunner
class ProfilingTestRunner(DjangoTestSuiteRunner):
def run_suite(self, suite, **kwargs):
stream = open('profiled_tests.txt', 'w')
# failfast keyword was added in Python 2.7 so we need to leave it out
# when creating the runner if we are running an older python version.
if sys.version_info >= (2, 7):
runner = unittest.TextTestRunner(verbosity=self.verbosity, failfast=self.failfast).run
else:
runner = unittest.TextTestRunner(verbosity=self.verbosity).run
profile = cProfile.Profile()
profile.runctx('result = run_tests(suite)', {
'run_tests': runner,
'suite': suite,
}, locals())
profile.create_stats()
stats = pstats.Stats(profile, stream=stream)
stats.sort_stats('time')
stats.print_stats()
return locals()['result']
|
Use more readable version comparision
|
Use more readable version comparision
|
Python
|
bsd-2-clause
|
murphyke/avocado,murphyke/avocado,murphyke/avocado,murphyke/avocado
|
---
+++
@@ -11,7 +11,7 @@
# failfast keyword was added in Python 2.7 so we need to leave it out
# when creating the runner if we are running an older python version.
- if sys.hexversion >= 0x02070000:
+ if sys.version_info >= (2, 7):
runner = unittest.TextTestRunner(verbosity=self.verbosity, failfast=self.failfast).run
else:
runner = unittest.TextTestRunner(verbosity=self.verbosity).run
|
fc5e34aca23d219dd55ee4cfa0776ac47a4252db
|
dynamic_forms/__init__.py
|
dynamic_forms/__init__.py
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
__author__ = 'Markus Holtermann'
__email__ = 'info@sinnwerkstatt.com'
__version__ = '0.3.2'
default_app_config = 'dynamic_forms.apps.DynamicFormsConfig'
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
__author__ = 'Markus Holtermann'
__email__ = 'info@markusholtermann.eu'
__version__ = '0.3.2'
default_app_config = 'dynamic_forms.apps.DynamicFormsConfig'
|
Fix email in package init
|
Fix email in package init
|
Python
|
bsd-3-clause
|
MotherNatureNetwork/django-dynamic-forms,MotherNatureNetwork/django-dynamic-forms,wangjiaxi/django-dynamic-forms,wangjiaxi/django-dynamic-forms,MotherNatureNetwork/django-dynamic-forms,uhuramedia/django-dynamic-forms,uhuramedia/django-dynamic-forms,uhuramedia/django-dynamic-forms,wangjiaxi/django-dynamic-forms
|
---
+++
@@ -3,7 +3,7 @@
__author__ = 'Markus Holtermann'
-__email__ = 'info@sinnwerkstatt.com'
+__email__ = 'info@markusholtermann.eu'
__version__ = '0.3.2'
default_app_config = 'dynamic_forms.apps.DynamicFormsConfig'
|
7c2a75906338e0670d0f75b4e06fc9ae775f3142
|
custom/opm/migrations/0001_drop_old_fluff_tables.py
|
custom/opm/migrations/0001_drop_old_fluff_tables.py
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import logging
from sqlalchemy import Table, MetaData
from corehq.db import connection_manager
from django.db import migrations
def drop_tables(apps, schema_editor):
# show SQL commands
logging.getLogger('sqlalchemy.engine').setLevel(logging.INFO)
metadata = MetaData(bind=connection_manager.get_engine())
for table_name in [
'fluff_OPMHierarchyFluff',
'fluff_OpmCaseFluff',
'fluff_OpmFormFluff',
'fluff_OpmHealthStatusAllInfoFluff',
'fluff_VhndAvailabilityFluff',
]:
Table(table_name, metadata).drop(checkfirst=True)
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.RunPython(drop_tables),
]
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import logging
from sqlalchemy import Table, MetaData
from corehq.db import connection_manager
from corehq.util.decorators import change_log_level
from django.db import migrations
@change_log_level('sqlalchemy.engine', logging.INFO) # show SQL commands
def drop_tables(apps, schema_editor):
metadata = MetaData(bind=connection_manager.get_engine())
for table_name in [
'fluff_OPMHierarchyFluff',
'fluff_OpmCaseFluff',
'fluff_OpmFormFluff',
'fluff_OpmHealthStatusAllInfoFluff',
'fluff_VhndAvailabilityFluff',
]:
Table(table_name, metadata).drop(checkfirst=True)
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.RunPython(drop_tables),
]
|
Make sure log level gets reset afterwards
|
Make sure log level gets reset afterwards
|
Python
|
bsd-3-clause
|
dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,qedsoftware/commcare-hq,qedsoftware/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,qedsoftware/commcare-hq,qedsoftware/commcare-hq,qedsoftware/commcare-hq
|
---
+++
@@ -5,13 +5,12 @@
from sqlalchemy import Table, MetaData
from corehq.db import connection_manager
+from corehq.util.decorators import change_log_level
from django.db import migrations
+@change_log_level('sqlalchemy.engine', logging.INFO) # show SQL commands
def drop_tables(apps, schema_editor):
- # show SQL commands
- logging.getLogger('sqlalchemy.engine').setLevel(logging.INFO)
-
metadata = MetaData(bind=connection_manager.get_engine())
for table_name in [
|
38a2f6999ae0fb956303599ca8cf860c759c1ea8
|
xml_json_import/__init__.py
|
xml_json_import/__init__.py
|
from django.conf import settings
from os import path, listdir
from lxml import etree
class XmlJsonImportModuleException(Exception):
pass
if not hasattr(settings, 'XSLT_FILES_DIR'):
raise XmlJsonImportModuleException('Settings must contain XSLT_FILES_DIR parameter')
if not path.exists(settings.XSLT_FILES_DIR):
raise XmlJsonImportModuleException('Directory specified by XSLT_FILES_DIR does not exist')
for filename in listdir(settings.XSLT_FILES_DIR):
filepath = path.join(settings.XSLT_FILES_DIR, filename)
if path.isfile(filepath):
try:
xslt_etree = etree.parse(filepath)
except etree.XMLSyntaxError as er:
raise XmlJsonImportModuleException('File ' + filepath + ' is not a valid XML file: ' + str(er))
try:
transform = etree.XSLT(xslt_etree)
except etree.XSLTParseError as er:
raise XmlJsonImportModuleException('File ' + filepath + ' is not a valid XSLT file: ' + str(er))
|
from django.conf import settings
from os import path, listdir
from lxml import etree
class XmlJsonImportModuleException(Exception):
pass
if not hasattr(settings, 'XSLT_FILES_DIR'):
raise XmlJsonImportModuleException('Settings must contain XSLT_FILES_DIR parameter')
if not path.exists(settings.XSLT_FILES_DIR):
raise XmlJsonImportModuleException('Directory specified by XSLT_FILES_DIR does not exist')
for filename in listdir(settings.XSLT_FILES_DIR):
filepath = path.join(settings.XSLT_FILES_DIR, filename)
if path.isfile(filepath):
try:
xslt_etree = etree.parse(filepath)
except etree.XMLSyntaxError as er:
raise XmlJsonImportModuleException('File ' + filepath + ' is not a valid XML file: ' + str(er))
try:
transform = etree.XSLT(xslt_etree)
except etree.XSLTParseError as er:
raise XmlJsonImportModuleException('File ' + filepath + ' is not a valid XSLT file: ' + str(er))
|
Change line end characters to UNIX (\r\n -> \n)
|
Change line end characters to UNIX (\r\n -> \n)
|
Python
|
mit
|
lev-veshnyakov/django-import-data,lev-veshnyakov/django-import-data
| |
e3bd01b70939555feb89c373d2e156104f1dd02b
|
daemon/__init__.py
|
daemon/__init__.py
|
# -*- coding: utf-8 -*-
# Copyright © 2009 Ben Finney <ben+python@benfinney.id.au>
# Copyright © 2006 Robert Niederreiter
#
# This is free software: you may copy, modify, and/or distribute this work
# under the terms of the Python Software Foundation License, version 2 or
# later as published by the Python Software Foundation.
# No warranty expressed or implied. See the file LICENSE.PSF-2 for details.
""" Library to implement a well-behaved Unix daemon process
This library implements PEP 3143: Standard daemon process library.
A well-behaved Unix daemon process is tricky to get right, but the
required steps are much the same for every daemon program. A
`DaemonContext` instance holds the behaviour and configured
process environment for the program; use the instance as a context
manager to enter a daemon state.
Simple example of usage::
import daemon
from spam import do_main_program
with daemon.DaemonContext():
do_main_program()
"""
from daemon import DaemonContext
version = "1.4.4"
|
# -*- coding: utf-8 -*-
# Copyright © 2009 Ben Finney <ben+python@benfinney.id.au>
# Copyright © 2006 Robert Niederreiter
#
# This is free software: you may copy, modify, and/or distribute this work
# under the terms of the Python Software Foundation License, version 2 or
# later as published by the Python Software Foundation.
# No warranty expressed or implied. See the file LICENSE.PSF-2 for details.
""" Library to implement a well-behaved Unix daemon process
This library implements PEP 3143: Standard daemon process library.
A well-behaved Unix daemon process is tricky to get right, but the
required steps are much the same for every daemon program. A
`DaemonContext` instance holds the behaviour and configured
process environment for the program; use the instance as a context
manager to enter a daemon state.
Simple example of usage::
import daemon
from spam import do_main_program
with daemon.DaemonContext():
do_main_program()
"""
from daemon import DaemonContext
version = "1.4.5"
|
Prepare development of new version.
|
Prepare development of new version.
|
Python
|
apache-2.0
|
wting/python-daemon,eaufavor/python-daemon
|
---
+++
@@ -33,4 +33,4 @@
-version = "1.4.4"
+version = "1.4.5"
|
cdee49a0ed600a72955d844abf5e4b5b2f9970cc
|
cookielaw/templatetags/cookielaw_tags.py
|
cookielaw/templatetags/cookielaw_tags.py
|
# -*- coding: utf-8 -*-
from django import template
from django.template.loader import render_to_string
register = template.Library()
@register.simple_tag(takes_context=True)
def cookielaw_banner(context):
if context['request'].COOKIES.get('cookielaw_accepted', False):
return ''
return render_to_string('cookielaw/banner.html', context)
|
# -*- coding: utf-8 -*-
from django import template
from django.template.loader import render_to_string
register = template.Library()
@register.simple_tag(takes_context=True)
def cookielaw_banner(context):
if context['request'].COOKIES.get('cookielaw_accepted', False):
return ''
request = context.get('request', None)
data = self.get_context(context, **kwargs)
if django.VERSION[:2] < (1, 10):
return render_to_string(
'cookielaw/banner.html', data, context_instance=context
)
else:
return render_to_string('cookielaw/banner.html', data, request)
|
Fix required for Django 1.11
|
Fix required for Django 1.11
Update to fix "context must be a dict rather than RequestContext" error in Django 1.11
|
Python
|
bsd-2-clause
|
juan-cb/django-cookie-law,juan-cb/django-cookie-law,juan-cb/django-cookie-law
|
---
+++
@@ -9,7 +9,18 @@
@register.simple_tag(takes_context=True)
def cookielaw_banner(context):
+
if context['request'].COOKIES.get('cookielaw_accepted', False):
return ''
- return render_to_string('cookielaw/banner.html', context)
-
+
+ request = context.get('request', None)
+
+ data = self.get_context(context, **kwargs)
+
+
+ if django.VERSION[:2] < (1, 10):
+ return render_to_string(
+ 'cookielaw/banner.html', data, context_instance=context
+ )
+ else:
+ return render_to_string('cookielaw/banner.html', data, request)
|
1e0d3c0d0b20f92fd901163a4f2b41627f9e931e
|
oonib/handlers.py
|
oonib/handlers.py
|
from cyclone import web
class OONIBHandler(web.RequestHandler):
pass
class OONIBError(web.HTTPError):
pass
|
import types
from cyclone import escape
from cyclone import web
class OONIBHandler(web.RequestHandler):
def write(self, chunk):
"""
This is a monkey patch to RequestHandler to allow us to serialize also
json list objects.
"""
if isinstance(chunk, types.ListType):
chunk = escape.json_encode(chunk)
web.RequestHandler.write(self, chunk)
self.set_header("Content-Type", "application/json")
else:
web.RequestHandler.write(self, chunk)
class OONIBError(web.HTTPError):
pass
|
Add support for serializing lists to json via self.write()
|
Add support for serializing lists to json via self.write()
|
Python
|
bsd-2-clause
|
DoNotUseThisCodeJUSTFORKS/ooni-backend,dstufft/ooni-backend,DoNotUseThisCodeJUSTFORKS/ooni-backend,dstufft/ooni-backend
|
---
+++
@@ -1,7 +1,20 @@
+import types
+
+from cyclone import escape
from cyclone import web
class OONIBHandler(web.RequestHandler):
- pass
+ def write(self, chunk):
+ """
+ This is a monkey patch to RequestHandler to allow us to serialize also
+ json list objects.
+ """
+ if isinstance(chunk, types.ListType):
+ chunk = escape.json_encode(chunk)
+ web.RequestHandler.write(self, chunk)
+ self.set_header("Content-Type", "application/json")
+ else:
+ web.RequestHandler.write(self, chunk)
class OONIBError(web.HTTPError):
pass
|
b24aca6da2513aff7e07ce97715a36eb8e9eff2c
|
var/spack/packages/ravel/package.py
|
var/spack/packages/ravel/package.py
|
from spack import *
class Ravel(Package):
"""Ravel is a parallel communication trace visualization tool that
orders events according to logical time."""
homepage = "https://github.com/scalability-llnl/ravel"
version('1.0', git="ssh://git@cz-stash.llnl.gov:7999/pave/ravel.git",
branch='features/otf2export')
depends_on('cmake@2.8.9:')
depends_on('muster@1.0.1:')
depends_on('otf')
depends_on('otf2')
depends_on('qt@5:')
def install(self, spec, prefix):
cmake(*std_cmake_args)
make()
make("install")
|
from spack import *
class Ravel(Package):
"""Ravel is a parallel communication trace visualization tool that
orders events according to logical time."""
homepage = "https://github.com/scalability-llnl/ravel"
version('1.0.0', git="https://github.com/scalability-llnl/ravel.git",
branch='master')
depends_on('cmake@2.8.9:')
depends_on('muster@1.0.1:')
depends_on('otf')
depends_on('otf2')
depends_on('qt@5:')
def install(self, spec, prefix):
cmake('-Wno-dev', *std_cmake_args)
make()
make("install")
|
Add -Wno-dev to avoid cmake policy warnings.
|
Add -Wno-dev to avoid cmake policy warnings.
|
Python
|
lgpl-2.1
|
lgarren/spack,krafczyk/spack,LLNL/spack,mfherbst/spack,tmerrick1/spack,mfherbst/spack,EmreAtes/spack,TheTimmy/spack,mfherbst/spack,EmreAtes/spack,tmerrick1/spack,krafczyk/spack,krafczyk/spack,iulian787/spack,TheTimmy/spack,krafczyk/spack,EmreAtes/spack,EmreAtes/spack,EmreAtes/spack,TheTimmy/spack,iulian787/spack,matthiasdiener/spack,skosukhin/spack,lgarren/spack,lgarren/spack,tmerrick1/spack,LLNL/spack,skosukhin/spack,mfherbst/spack,TheTimmy/spack,tmerrick1/spack,TheTimmy/spack,iulian787/spack,LLNL/spack,LLNL/spack,matthiasdiener/spack,lgarren/spack,tmerrick1/spack,iulian787/spack,lgarren/spack,mfherbst/spack,LLNL/spack,iulian787/spack,krafczyk/spack,matthiasdiener/spack,skosukhin/spack,matthiasdiener/spack,skosukhin/spack,matthiasdiener/spack,skosukhin/spack
|
---
+++
@@ -6,9 +6,8 @@
homepage = "https://github.com/scalability-llnl/ravel"
-
- version('1.0', git="ssh://git@cz-stash.llnl.gov:7999/pave/ravel.git",
- branch='features/otf2export')
+ version('1.0.0', git="https://github.com/scalability-llnl/ravel.git",
+ branch='master')
depends_on('cmake@2.8.9:')
@@ -18,6 +17,6 @@
depends_on('qt@5:')
def install(self, spec, prefix):
- cmake(*std_cmake_args)
+ cmake('-Wno-dev', *std_cmake_args)
make()
make("install")
|
c25ec6bb7d06446ca6dee78e53b5a414791451e5
|
modelview/urls.py
|
modelview/urls.py
|
from django.conf.urls import url
from modelview import views
from oeplatform import settings
from django.conf.urls.static import static
urlpatterns = [
url(r'^(?P<sheettype>[\w\d_]+)s/$', views.listsheets, {}, name='modellist'),
url(r'^overview/$', views.overview, {}),
url(r'^(?P<sheettype>[\w\d_]+)s/add/$', views.FSAdd.as_view(), {'method':'add'}, name='modellist'),
url(r'^(?P<sheettype>[\w\d_]+)s/download/$', views.model_to_csv, {}, name='index'),
url(r'^(?P<sheettype>[\w\d_]+)s/(?P<model_name>[\w\d_]+)/$', views.show, {}, name='index'),
url(r'^(?P<sheettype>[\w\d_]+)s/(?P<model_name>[\w\d_]+)/edit/$', views.editModel, {}, name='index'),
url(r'^(?P<sheettype>[\w\d_]+)s/(?P<pk>[\w\d_]+)/update/$', views.FSAdd.as_view(), {'method':'update'}, name='index'),
]
|
from django.conf.urls import url
from modelview import views
from oeplatform import settings
from django.conf.urls.static import static
urlpatterns = [
url(r'^(?P<sheettype>[\w\d_]+)s/$', views.listsheets, {}, name='modellist'),
url(r'^overview/$', views.overview, {}),
url(r'^(?P<sheettype>[\w\d_]+)s/add/$', views.FSAdd.as_view(), {'method':'add'}, name='modellist'),
url(r'^(?P<sheettype>[\w\d_]+)s/download/$', views.model_to_csv, {}, name='index'),
url(r'^(?P<sheettype>[\w\d_]+)s/(?P<model_name>[\d]+)/$', views.show, {}, name='index'),
url(r'^(?P<sheettype>[\w\d_]+)s/(?P<model_name>[\d]+)/edit/$', views.editModel, {}, name='index'),
url(r'^(?P<sheettype>[\w\d_]+)s/(?P<pk>[\d]+)/update/$', views.FSAdd.as_view(), {'method':'update'}, name='index'),
]
|
Simplify regex in url matching
|
Simplify regex in url matching
|
Python
|
agpl-3.0
|
openego/oeplatform,openego/oeplatform,openego/oeplatform,openego/oeplatform
|
---
+++
@@ -9,8 +9,8 @@
url(r'^overview/$', views.overview, {}),
url(r'^(?P<sheettype>[\w\d_]+)s/add/$', views.FSAdd.as_view(), {'method':'add'}, name='modellist'),
url(r'^(?P<sheettype>[\w\d_]+)s/download/$', views.model_to_csv, {}, name='index'),
- url(r'^(?P<sheettype>[\w\d_]+)s/(?P<model_name>[\w\d_]+)/$', views.show, {}, name='index'),
- url(r'^(?P<sheettype>[\w\d_]+)s/(?P<model_name>[\w\d_]+)/edit/$', views.editModel, {}, name='index'),
- url(r'^(?P<sheettype>[\w\d_]+)s/(?P<pk>[\w\d_]+)/update/$', views.FSAdd.as_view(), {'method':'update'}, name='index'),
+ url(r'^(?P<sheettype>[\w\d_]+)s/(?P<model_name>[\d]+)/$', views.show, {}, name='index'),
+ url(r'^(?P<sheettype>[\w\d_]+)s/(?P<model_name>[\d]+)/edit/$', views.editModel, {}, name='index'),
+ url(r'^(?P<sheettype>[\w\d_]+)s/(?P<pk>[\d]+)/update/$', views.FSAdd.as_view(), {'method':'update'}, name='index'),
]
|
c707242bc535411fe84232ca765a87ed2ef7fc22
|
magicembed/templatetags/magicembed_tags.py
|
magicembed/templatetags/magicembed_tags.py
|
# -*- coding: utf-8 -*-
from django import template
from django.utils.safestring import mark_safe
from magicembed.providers import get_provider
register = template.Library()
@register.filter(is_safe=True)
def magicembed(value, arg=None):
'''value is the url and arg the size tuple
ussage: {% http://myurl.com/|magicembed:"640x480" %}'''
arg = [int(item) for item in arg.split('x')]
provider = get_provider(value, arg)
return mark_safe(provider.render_video())
@register.filter
def magicthumbnail(value):
'''value is the url and arg the link_to another url
ussage: {% http://myurl.com/|magicthumbnail: '/some/url' %}'''
provider = get_provider(value)
return provider.render_thumbnail()
|
# -*- coding: utf-8 -*-
from django import template
from django.utils.safestring import mark_safe
from magicembed.providers import get_provider
register = template.Library()
@register.filter(is_safe=True)
def magicembed(value, arg=None):
'''value is the url and arg the size tuple
usage: {% http://myurl.com/|magicembed:"640x480" %}'''
arg = [int(item) for item in arg.split('x')]
provider = get_provider(value, arg)
return mark_safe(provider.render_video())
@register.filter
def magicthumbnail(value):
'''value is the url and arg the link_to another url
usage: {% http://myurl.com/|magicthumbnail: '/some/url' %}'''
provider = get_provider(value)
return provider.render_thumbnail()
|
Fix simple typo, ussage -> usage
|
docs: Fix simple typo, ussage -> usage
There is a small typo in magicembed/templatetags/magicembed_tags.py.
Should read `usage` rather than `ussage`.
|
Python
|
mit
|
kronoscode/django-magicembed,kronoscode/django-magicembed
|
---
+++
@@ -10,7 +10,7 @@
@register.filter(is_safe=True)
def magicembed(value, arg=None):
'''value is the url and arg the size tuple
- ussage: {% http://myurl.com/|magicembed:"640x480" %}'''
+ usage: {% http://myurl.com/|magicembed:"640x480" %}'''
arg = [int(item) for item in arg.split('x')]
provider = get_provider(value, arg)
@@ -20,6 +20,6 @@
@register.filter
def magicthumbnail(value):
'''value is the url and arg the link_to another url
- ussage: {% http://myurl.com/|magicthumbnail: '/some/url' %}'''
+ usage: {% http://myurl.com/|magicthumbnail: '/some/url' %}'''
provider = get_provider(value)
return provider.render_thumbnail()
|
f4841c1b0ddecd27544e2fd36429fd72c102d162
|
Lib/fontTools/help/__main__.py
|
Lib/fontTools/help/__main__.py
|
"""Show this help"""
import pkgutil
import sys
from setuptools import find_packages
from pkgutil import iter_modules
import fontTools
import importlib
def get_description(pkg):
try:
return __import__(pkg+".__main__",globals(),locals(),["__doc__"]).__doc__
except Exception as e:
return None
def show_help_list():
path = fontTools.__path__[0]
for pkg in find_packages(path):
qualifiedPkg = "fontTools."+pkg
description = get_description(qualifiedPkg)
if description:
print("fontools %-10s %s" % (pkg, description))
pkgpath = path + '/' + qualifiedPkg.replace('.', '/')
if (sys.version_info.major == 3 and sys.version_info.minor < 6):
for _, name, ispkg in iter_modules([pkgpath]):
if get_description(pkg+ '.' + name):
modules.add(pkg + '.' + name)
else:
for info in iter_modules([pkgpath]):
if get_description(pkg+ '.' + info.name):
modules.add(pkg + '.' + info.name)
if __name__ == '__main__':
print("fonttools v%s\n" % fontTools.__version__)
show_help_list()
|
"""Show this help"""
import pkgutil
import sys
from setuptools import find_packages
from pkgutil import iter_modules
import fontTools
import importlib
def describe(pkg):
try:
description = __import__(
"fontTools." + pkg + ".__main__", globals(), locals(), ["__doc__"]
).__doc__
print("fonttools %-10s %s" % (pkg, description), file=sys.stderr)
except Exception as e:
return None
def show_help_list():
path = fontTools.__path__[0]
for pkg in find_packages(path):
qualifiedPkg = "fontTools." + pkg
describe(pkg)
pkgpath = path + "/" + qualifiedPkg.replace(".", "/")
for info in iter_modules([pkgpath]):
describe(pkg + "." + info.name)
if __name__ == "__main__":
print("fonttools v%s\n" % fontTools.__version__, file=sys.stderr)
show_help_list()
|
Address feedback, reformat, simplify, fix bugs and typo
|
Address feedback, reformat, simplify, fix bugs and typo
|
Python
|
mit
|
googlefonts/fonttools,fonttools/fonttools
|
---
+++
@@ -7,29 +7,26 @@
import importlib
-def get_description(pkg):
- try:
- return __import__(pkg+".__main__",globals(),locals(),["__doc__"]).__doc__
- except Exception as e:
- return None
+def describe(pkg):
+ try:
+ description = __import__(
+ "fontTools." + pkg + ".__main__", globals(), locals(), ["__doc__"]
+ ).__doc__
+ print("fonttools %-10s %s" % (pkg, description), file=sys.stderr)
+ except Exception as e:
+ return None
+
def show_help_list():
- path = fontTools.__path__[0]
- for pkg in find_packages(path):
- qualifiedPkg = "fontTools."+pkg
- description = get_description(qualifiedPkg)
- if description:
- print("fontools %-10s %s" % (pkg, description))
- pkgpath = path + '/' + qualifiedPkg.replace('.', '/')
- if (sys.version_info.major == 3 and sys.version_info.minor < 6):
- for _, name, ispkg in iter_modules([pkgpath]):
- if get_description(pkg+ '.' + name):
- modules.add(pkg + '.' + name)
- else:
- for info in iter_modules([pkgpath]):
- if get_description(pkg+ '.' + info.name):
- modules.add(pkg + '.' + info.name)
+ path = fontTools.__path__[0]
+ for pkg in find_packages(path):
+ qualifiedPkg = "fontTools." + pkg
+ describe(pkg)
+ pkgpath = path + "/" + qualifiedPkg.replace(".", "/")
+ for info in iter_modules([pkgpath]):
+ describe(pkg + "." + info.name)
-if __name__ == '__main__':
- print("fonttools v%s\n" % fontTools.__version__)
- show_help_list()
+
+if __name__ == "__main__":
+ print("fonttools v%s\n" % fontTools.__version__, file=sys.stderr)
+ show_help_list()
|
67aa75b51249c8557f4fd4fd98b4dc6901b9cf49
|
great_expectations/datasource/generator/__init__.py
|
great_expectations/datasource/generator/__init__.py
|
from .databricks_generator import DatabricksTableGenerator
from .glob_reader_generator import GlobReaderGenerator
from .subdir_reader_generator import SubdirReaderGenerator
from .in_memory_generator import InMemoryGenerator
from .query_generator import QueryGenerator
from .table_generator import TableGenerator
|
from .databricks_generator import DatabricksTableGenerator
from .glob_reader_generator import GlobReaderGenerator
from .subdir_reader_generator import SubdirReaderGenerator
from .in_memory_generator import InMemoryGenerator
from .query_generator import QueryGenerator
from .table_generator import TableGenerator
from .s3_generator import S3Generator
|
Add S3 Generator to generators module
|
Add S3 Generator to generators module
|
Python
|
apache-2.0
|
great-expectations/great_expectations,great-expectations/great_expectations,great-expectations/great_expectations,great-expectations/great_expectations
|
---
+++
@@ -4,3 +4,4 @@
from .in_memory_generator import InMemoryGenerator
from .query_generator import QueryGenerator
from .table_generator import TableGenerator
+from .s3_generator import S3Generator
|
0aa757955d631df9fb8e6cbe3e372dcae56e2255
|
django_mailbox/transports/imap.py
|
django_mailbox/transports/imap.py
|
from imaplib import IMAP4, IMAP4_SSL
from .base import EmailTransport, MessageParseError
class ImapTransport(EmailTransport):
def __init__(self, hostname, port=None, ssl=False, archive=''):
self.hostname = hostname
self.port = port
self.archive = archive
if ssl:
self.transport = IMAP4_SSL
if not self.port:
self.port = 993
else:
self.transport = IMAP4
if not self.port:
self.port = 143
def connect(self, username, password):
self.server = self.transport(self.hostname, self.port)
typ, msg = self.server.login(username, password)
self.server.select()
def get_message(self):
typ, inbox = self.server.search(None, 'ALL')
if not inbox[0]:
return
if self.archive:
typ, folders = self.server.list(pattern=self.archive)
if folders[0] == None:
self.archive = False
for key in inbox[0].split():
try:
typ, msg_contents = self.server.fetch(key, '(RFC822)')
message = self.get_email_from_bytes(msg_contents[0][1])
yield message
except MessageParseError:
continue
if self.archive:
self.server.copy(key, self.archive)
self.server.store(key, "+FLAGS", "\\Deleted")
self.server.expunge()
return
|
from imaplib import IMAP4, IMAP4_SSL
from .base import EmailTransport, MessageParseError
class ImapTransport(EmailTransport):
def __init__(self, hostname, port=None, ssl=False, archive=''):
self.hostname = hostname
self.port = port
self.archive = archive
if ssl:
self.transport = IMAP4_SSL
if not self.port:
self.port = 993
else:
self.transport = IMAP4
if not self.port:
self.port = 143
def connect(self, username, password):
self.server = self.transport(self.hostname, self.port)
typ, msg = self.server.login(username, password)
self.server.select()
def get_message(self):
typ, inbox = self.server.search(None, 'ALL')
if not inbox[0]:
return
if self.archive:
typ, folders = self.server.list(pattern=self.archive)
if folders[0] is None:
# If the archive folder does not exist, create it
self.server.create(self.archive)
for key in inbox[0].split():
try:
typ, msg_contents = self.server.fetch(key, '(RFC822)')
message = self.get_email_from_bytes(msg_contents[0][1])
yield message
except MessageParseError:
continue
if self.archive:
self.server.copy(key, self.archive)
self.server.store(key, "+FLAGS", "\\Deleted")
self.server.expunge()
return
|
Create archive folder if it does not exist.
|
Create archive folder if it does not exist.
|
Python
|
mit
|
coddingtonbear/django-mailbox,ad-m/django-mailbox,Shekharrajak/django-mailbox,leifurhauks/django-mailbox
|
---
+++
@@ -30,8 +30,9 @@
if self.archive:
typ, folders = self.server.list(pattern=self.archive)
- if folders[0] == None:
- self.archive = False
+ if folders[0] is None:
+ # If the archive folder does not exist, create it
+ self.server.create(self.archive)
for key in inbox[0].split():
try:
|
d2d4f127a797ad6e82d41de10edd0e70f1626df8
|
virtualfish/__main__.py
|
virtualfish/__main__.py
|
from __future__ import print_function
import os
import sys
import pkg_resources
if __name__ == "__main__":
version = pkg_resources.get_distribution('virtualfish').version
base_path = os.path.dirname(os.path.abspath(__file__))
commands = [
'set -g VIRTUALFISH_VERSION {}'.format(version),
'set -g VIRTUALFISH_PYTHON_EXEC {}'.format(sys.executable),
'. {}'.format(os.path.join(base_path, 'virtual.fish')),
]
for plugin in sys.argv[1:]:
path = os.path.join(base_path, plugin + '.fish')
if os.path.exists(path):
commands.append('. {}'.format(path))
else:
print('virtualfish loader error: plugin {} does not exist!'.format(plugin), file=sys.stderr)
commands.append('emit virtualfish_did_setup_plugins')
print(';'.join(commands))
|
from __future__ import print_function
import os
import sys
import pkg_resources
if __name__ == "__main__":
version = pkg_resources.get_distribution('virtualfish').version
base_path = os.path.dirname(os.path.abspath(__file__))
commands = [
'set -g VIRTUALFISH_VERSION {}'.format(version),
'set -g VIRTUALFISH_PYTHON_EXEC {}'.format(sys.executable),
'source {}'.format(os.path.join(base_path, 'virtual.fish')),
]
for plugin in sys.argv[1:]:
path = os.path.join(base_path, plugin + '.fish')
if os.path.exists(path):
commands.append('source {}'.format(path))
else:
print('virtualfish loader error: plugin {} does not exist!'.format(plugin), file=sys.stderr)
commands.append('emit virtualfish_did_setup_plugins')
print(';'.join(commands))
|
Use 'source' command instead of deprecated '.' alias
|
Use 'source' command instead of deprecated '.' alias
Closes #125
|
Python
|
mit
|
adambrenecki/virtualfish,adambrenecki/virtualfish
|
---
+++
@@ -10,13 +10,13 @@
commands = [
'set -g VIRTUALFISH_VERSION {}'.format(version),
'set -g VIRTUALFISH_PYTHON_EXEC {}'.format(sys.executable),
- '. {}'.format(os.path.join(base_path, 'virtual.fish')),
+ 'source {}'.format(os.path.join(base_path, 'virtual.fish')),
]
for plugin in sys.argv[1:]:
path = os.path.join(base_path, plugin + '.fish')
if os.path.exists(path):
- commands.append('. {}'.format(path))
+ commands.append('source {}'.format(path))
else:
print('virtualfish loader error: plugin {} does not exist!'.format(plugin), file=sys.stderr)
|
2ab4cd4bbc01f3625708b725f1465cb9fb0cdf1b
|
scripts/showbb.py
|
scripts/showbb.py
|
'''
Pretty prints a bitboard to the console given its hex or decimal value.
'''
import sys, textwrap
if len(sys.argv) == 1:
print 'Syntax: showbb.py <bitboard>'
sys.exit(1)
# Handle hex/decimal bitboards
if sys.argv[1].startswith('0x'):
bb = bin(int(sys.argv[1], 16))
else:
bb = bin(int(sys.argv[1], 10))
# Slice off the '0b'
bb = bb[2:]
if len(bb) < 64:
bb = '0' * (64-len(bb)) + bb
print '\n'.join([line[::-1] for line in textwrap.wrap(bb, 8)])
|
'''
Pretty prints a bitboard to the console given its hex or decimal value.b
'''
import sys, textwrap
if len(sys.argv) == 1:
print 'Syntax: showbb.py <bitboard>'
sys.exit(1)
# Handle hex/decimal bitboards
if sys.argv[1].startswith('0x'):
bb = bin(int(sys.argv[1], 16))
else:
bb = bin(int(sys.argv[1], 10))
# Slice off the '0b'
bb = bb[2:]
bb = bb.replace('0', '.')
bb = bb.replace('1', '#')
if len(bb) < 64:
bb = '0' * (64-len(bb)) + bb
print '\n'.join([' '.join(line[::-1]) for line in textwrap.wrap(bb, 8)])
|
Make bitboard script output easier to read
|
Make bitboard script output easier to read
|
Python
|
mit
|
GunshipPenguin/shallow-blue,GunshipPenguin/shallow-blue,GunshipPenguin/shallow-blue,GunshipPenguin/shallow-blue
|
---
+++
@@ -1,5 +1,5 @@
'''
-Pretty prints a bitboard to the console given its hex or decimal value.
+Pretty prints a bitboard to the console given its hex or decimal value.b
'''
import sys, textwrap
@@ -16,7 +16,10 @@
# Slice off the '0b'
bb = bb[2:]
+bb = bb.replace('0', '.')
+bb = bb.replace('1', '#')
+
if len(bb) < 64:
bb = '0' * (64-len(bb)) + bb
-print '\n'.join([line[::-1] for line in textwrap.wrap(bb, 8)])
+print '\n'.join([' '.join(line[::-1]) for line in textwrap.wrap(bb, 8)])
|
003c3049f84634f650a9ddff7dbee09ceefbe47f
|
version.py
|
version.py
|
major = 0
minor=0
patch=13
branch="master"
timestamp=1376507610.99
|
major = 0
minor=0
patch=14
branch="master"
timestamp=1376507766.02
|
Tag commit for v0.0.14-master generated by gitmake.py
|
Tag commit for v0.0.14-master generated by gitmake.py
|
Python
|
mit
|
ryansturmer/gitmake
|
---
+++
@@ -1,5 +1,5 @@
major = 0
minor=0
-patch=13
+patch=14
branch="master"
-timestamp=1376507610.99
+timestamp=1376507766.02
|
a34fac317c9b09c3d516238cabda5e99a8cec907
|
sciunit/unit_test/validator_tests.py
|
sciunit/unit_test/validator_tests.py
|
import unittest
import quantities as pq
class ValidatorTestCase(unittest.TestCase):
def register_test(self):
class TestClass():
intValue = 0
def getIntValue(self):
return self.intValue
from sciunit.validators import register_quantity, register_type
register_type(TestClass, "TestType1")
q = pq.Quantity([1,2,3], 'J')
register_quantity(q, "TestType2")
|
import unittest
import quantities as pq
class ValidatorTestCase(unittest.TestCase):
def test1(self):
self.assertEqual(1, 1)
def register_test(self):
class TestClass():
intValue = 0
def getIntValue(self):
return self.intValue
from sciunit.validators import register_quantity, register_type
from cerberus import TypeDefinition, Validator
register_type(TestClass, "TestType1")
q = pq.Quantity([1,2,3], 'J')
register_quantity(q, "TestType2")
self.assertTrue(isinstance(Validator.types_mapping['TestType1'], TypeDefinition))
self.assertTrue(isinstance(Validator.types_mapping['TestType2'], TypeDefinition))
if __name__ == '__main__':
unittest.main()
|
Add assert to validator test cases
|
Add assert to validator test cases
|
Python
|
mit
|
scidash/sciunit,scidash/sciunit
|
---
+++
@@ -1,12 +1,26 @@
import unittest
import quantities as pq
+
class ValidatorTestCase(unittest.TestCase):
+
+ def test1(self):
+ self.assertEqual(1, 1)
+
def register_test(self):
+
class TestClass():
intValue = 0
def getIntValue(self):
return self.intValue
+
from sciunit.validators import register_quantity, register_type
+ from cerberus import TypeDefinition, Validator
+
register_type(TestClass, "TestType1")
q = pq.Quantity([1,2,3], 'J')
register_quantity(q, "TestType2")
+ self.assertTrue(isinstance(Validator.types_mapping['TestType1'], TypeDefinition))
+ self.assertTrue(isinstance(Validator.types_mapping['TestType2'], TypeDefinition))
+
+if __name__ == '__main__':
+ unittest.main()
|
c94e3cb0f82430811f7e8cc53d29433448395f70
|
favicon/urls.py
|
favicon/urls.py
|
from django.conf.urls import patterns, url
from django.views.generic import TemplateView, RedirectView
import conf
urlpatterns = patterns('',
url(r'^favicon\.ico$', 'django.views.generic.simple.redirect_to', {'url': conf.FAVICON_PATH}, name='favicon'),
)
|
from django.conf.urls import patterns, url
from django.views.generic import TemplateView, RedirectView
import conf
urlpatterns = patterns('',
url(r'^favicon\.ico$', RedirectView.as_view(url=conf.FAVICON_PATH}), name='favicon'),
)
|
Use RedirectView in urlpatterns (needed for Django 1.5)
|
Use RedirectView in urlpatterns (needed for Django 1.5)
'django.views.generic.simple.redirect_to' is not supported in Django 1.5
Use RedirectView.as_view instead.
The existing code was already importing RedirectView but still using the old 'django.views.generic.simple.redirect_to' in the url patterns.
|
Python
|
bsd-3-clause
|
littlepea/django-favicon
|
---
+++
@@ -3,5 +3,5 @@
import conf
urlpatterns = patterns('',
- url(r'^favicon\.ico$', 'django.views.generic.simple.redirect_to', {'url': conf.FAVICON_PATH}, name='favicon'),
+ url(r'^favicon\.ico$', RedirectView.as_view(url=conf.FAVICON_PATH}), name='favicon'),
)
|
917cd9330f572bc2ec601a7555122b59507f6429
|
payments/management/commands/init_plans.py
|
payments/management/commands/init_plans.py
|
from django.conf import settings
from django.core.management.base import BaseCommand
import stripe
class Command(BaseCommand):
help = "Make sure your Stripe account has the plans"
def handle(self, *args, **options):
stripe.api_key = settings.STRIPE_SECRET_KEY
for plan in settings.PAYMENTS_PLANS:
if settings.PAYMENTS_PLANS[plan].get("stripe_plan_id"):
stripe.Plan.create(
amount=100 * settings.PAYMENTS_PLANS[plan]["price"],
interval=settings.PAYMENTS_PLANS[plan]["interval"],
name=settings.PAYMENTS_PLANS[plan]["description"],
currency="usd",
id=settings.PAYMENTS_PLANS[plan].get("stripe_plan_id")
)
print "Plan created for %s" % plan
|
from django.conf import settings
from django.core.management.base import BaseCommand
import stripe
class Command(BaseCommand):
help = "Make sure your Stripe account has the plans"
def handle(self, *args, **options):
stripe.api_key = settings.STRIPE_SECRET_KEY
for plan in settings.PAYMENTS_PLANS:
if settings.PAYMENTS_PLANS[plan].get("stripe_plan_id"):
stripe.Plan.create(
amount=100 * settings.PAYMENTS_PLANS[plan]["price"],
interval=settings.PAYMENTS_PLANS[plan]["interval"],
name=settings.PAYMENTS_PLANS[plan]["name"],
currency="usd",
id=settings.PAYMENTS_PLANS[plan].get("stripe_plan_id")
)
print "Plan created for %s" % plan
|
Use plan name instead of description
|
Use plan name instead of description
|
Python
|
mit
|
aibon/django-stripe-payments,crehana/django-stripe-payments,crehana/django-stripe-payments,jamespacileo/django-stripe-payments,alexhayes/django-stripe-payments,ZeevG/django-stripe-payments,jamespacileo/django-stripe-payments,grue/django-stripe-payments,wahuneke/django-stripe-payments,adi-li/django-stripe-payments,alexhayes/django-stripe-payments,wahuneke/django-stripe-payments,jawed123/django-stripe-payments,pinax/django-stripe-payments,jawed123/django-stripe-payments,wahuneke/django-stripe-payments,aibon/django-stripe-payments,boxysean/django-stripe-payments,adi-li/django-stripe-payments,boxysean/django-stripe-payments,ZeevG/django-stripe-payments,grue/django-stripe-payments
|
---
+++
@@ -15,7 +15,7 @@
stripe.Plan.create(
amount=100 * settings.PAYMENTS_PLANS[plan]["price"],
interval=settings.PAYMENTS_PLANS[plan]["interval"],
- name=settings.PAYMENTS_PLANS[plan]["description"],
+ name=settings.PAYMENTS_PLANS[plan]["name"],
currency="usd",
id=settings.PAYMENTS_PLANS[plan].get("stripe_plan_id")
)
|
b2018bcf9274e0e641e132fe866ef630f99d98a3
|
profiles/modules/codes/extensions/codes.py
|
profiles/modules/codes/extensions/codes.py
|
from django.db import models
from django.utils.translation import ugettext_lazy as _
def register(cls, admin_cls):
cls.add_to_class('code', models.ForeignKey('profiles.Code',
verbose_name=_('Registration code'), null=True, blank=True))
if admin_cls:
admin_cls.list_display_filter += ['code', ]
if admin_cls.fieldsets:
admin_cls.fieldsets.append((_('Registration code'), {
'fields': ['code',],
'classes': ('collapse',),
}))
admin_cls.filter_horizontal = admin_cls.filter_horizontal + ('code',)
|
from django.db import models
from django.utils.translation import ugettext_lazy as _
def register(cls, admin_cls):
cls.add_to_class('code', models.ForeignKey('profiles.Code',
verbose_name=_('Registration code'), null=True, blank=True))
if admin_cls:
admin_cls.list_display_filter += ['code', ]
if admin_cls.fieldsets:
admin_cls.fieldsets.append((_('Registration code'), {
'fields': ['code',],
'classes': ('collapse',),
}))
if admin_cls.filter_horizontal:
admin_cls.filter_horizontal = admin_cls.filter_horizontal + ('code',)
|
Fix terrible error when filter_horizontal of admin class has not existed.
|
Fix terrible error when filter_horizontal of admin class has not existed.
|
Python
|
bsd-2-clause
|
incuna/django-extensible-profiles
|
---
+++
@@ -13,4 +13,6 @@
'fields': ['code',],
'classes': ('collapse',),
}))
+
+ if admin_cls.filter_horizontal:
admin_cls.filter_horizontal = admin_cls.filter_horizontal + ('code',)
|
cd010c4a3fd6418f3ab6789da7fdcfb65ef37dc1
|
setup.py
|
setup.py
|
import setuptools
setuptools.setup(name='pytest-cov',
version='1.6',
description='py.test plugin for coverage reporting with '
'support for both centralised and distributed testing, '
'including subprocesses and multiprocessing',
long_description=open('README.rst').read().strip(),
author='Marc Schlaich',
author_email='marc.schlaich@gmail.com',
url='https://github.com/schlamar/pytest-cov',
py_modules=['pytest_cov'],
install_requires=['pytest>=2.5.2',
'cov-core>=1.11'],
entry_points={'pytest11': ['pytest_cov = pytest_cov']},
license='MIT License',
zip_safe=False,
keywords='py.test pytest cover coverage distributed parallel',
classifiers=['Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2.4',
'Programming Language :: Python :: 2.5',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.0',
'Programming Language :: Python :: 3.1',
'Topic :: Software Development :: Testing'])
|
import setuptools
setuptools.setup(name='pytest-cov',
version='1.6',
description='py.test plugin for coverage reporting with '
'support for both centralised and distributed testing, '
'including subprocesses and multiprocessing',
long_description=open('README.rst').read().strip(),
author='Marc Schlaich',
author_email='marc.schlaich@gmail.com',
url='https://github.com/schlamar/pytest-cov',
py_modules=['pytest_cov'],
install_requires=['pytest>=2.5.2',
'cov-core>=1.12'],
entry_points={'pytest11': ['pytest_cov = pytest_cov']},
license='MIT License',
zip_safe=False,
keywords='py.test pytest cover coverage distributed parallel',
classifiers=['Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2.4',
'Programming Language :: Python :: 2.5',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.0',
'Programming Language :: Python :: 3.1',
'Topic :: Software Development :: Testing'])
|
Set cov-core dependency to 1.12
|
Set cov-core dependency to 1.12
|
Python
|
mit
|
wushaobo/pytest-cov,ionelmc/pytest-cover,opoplawski/pytest-cov,moreati/pytest-cov,schlamar/pytest-cov,pytest-dev/pytest-cov
|
---
+++
@@ -11,7 +11,7 @@
url='https://github.com/schlamar/pytest-cov',
py_modules=['pytest_cov'],
install_requires=['pytest>=2.5.2',
- 'cov-core>=1.11'],
+ 'cov-core>=1.12'],
entry_points={'pytest11': ['pytest_cov = pytest_cov']},
license='MIT License',
zip_safe=False,
|
7fa83928d0dae14fca556ef91a9c3c544aac24d6
|
apps/package/templatetags/package_tags.py
|
apps/package/templatetags/package_tags.py
|
from datetime import timedelta
from datetime import datetime
from django import template
from github2.client import Github
from package.models import Package, Commit
register = template.Library()
github = Github()
@register.filter
def commits_over_52(package):
current = datetime.now()
weeks = []
commits = [x.commit_date for x in Commit.objects.filter(package=package)]
for week in range(52):
weeks.append(len([x for x in commits if x < current and x > (current - timedelta(7))]))
current -= timedelta(7)
weeks.reverse()
weeks = [str(x) for x in weeks]
return ','.join(weeks)
@register.inclusion_tag('package/templatetags/usage.html')
def usage(user, package):
using = package.usage.filter(username=user) or False
count = 0
if using:
count = package.usage.count() - 1
return {
"using": using,
"count": count,
"package": package,
"show_count": True
}
@register.inclusion_tag('package/templatetags/usage.html')
def usage_no_count(user, package):
using = package.usage.filter(username=user) or False
count = 0
return {
"using": using,
"count": count,
"package": package,
"show_count": False
}
|
from datetime import timedelta
from datetime import datetime
from django import template
from github2.client import Github
from package.models import Package, Commit
register = template.Library()
github = Github()
@register.filter
def commits_over_52(package):
current = datetime.now()
weeks = []
commits = Commit.objects.filter(package=package).values_list('commit_date', flat=True)
for week in range(52):
weeks.append(len([x for x in commits if x < current and x > (current - timedelta(7))]))
current -= timedelta(7)
weeks.reverse()
weeks = map(str, weeks)
return ','.join(weeks)
@register.inclusion_tag('package/templatetags/usage.html')
def usage(user, package):
using = package.usage.filter(username=user) or False
count = 0
if using:
count = package.usage.count() - 1
return {
"using": using,
"count": count,
"package": package,
"show_count": True
}
@register.inclusion_tag('package/templatetags/usage.html')
def usage_no_count(user, package):
using = package.usage.filter(username=user) or False
count = 0
return {
"using": using,
"count": count,
"package": package,
"show_count": False
}
|
Update the commit_over_52 template tag to be more efficient.
|
Update the commit_over_52 template tag to be more efficient.
Replaced several list comprehensions with in-database operations and map calls for significantly improved performance.
|
Python
|
mit
|
QLGu/djangopackages,cartwheelweb/packaginator,cartwheelweb/packaginator,nanuxbe/djangopackages,pydanny/djangopackages,QLGu/djangopackages,QLGu/djangopackages,pydanny/djangopackages,audreyr/opencomparison,nanuxbe/djangopackages,miketheman/opencomparison,benracine/opencomparison,miketheman/opencomparison,benracine/opencomparison,cartwheelweb/packaginator,pydanny/djangopackages,audreyr/opencomparison,nanuxbe/djangopackages
|
---
+++
@@ -16,13 +16,13 @@
current = datetime.now()
weeks = []
- commits = [x.commit_date for x in Commit.objects.filter(package=package)]
+ commits = Commit.objects.filter(package=package).values_list('commit_date', flat=True)
for week in range(52):
weeks.append(len([x for x in commits if x < current and x > (current - timedelta(7))]))
current -= timedelta(7)
weeks.reverse()
- weeks = [str(x) for x in weeks]
+ weeks = map(str, weeks)
return ','.join(weeks)
@register.inclusion_tag('package/templatetags/usage.html')
|
6c8638c6e5801701d598509bb95036837ccd4a02
|
setup.py
|
setup.py
|
import setuptools
setuptools.setup(
name='mailcap-fix',
version='0.1.1',
description='A patched mailcap module that conforms to RFC 1524',
long_description=open('README.rst').read(),
url='https://github.com/michael-lazar/mailcap_fix',
author='Michael Lazar',
author_email='lazar.michael22@gmail.com',
license='UNLICENSE',
keywords='mailcap 1524',
packages=['mailcap_fix'],
)
|
import setuptools
setuptools.setup(
name='mailcap-fix',
version='0.1.1',
description='A patched mailcap module that conforms to RFC 1524',
long_description=open('README.rst', encoding='utf-8').read(),
url='https://github.com/michael-lazar/mailcap_fix',
author='Michael Lazar',
author_email='lazar.michael22@gmail.com',
license='UNLICENSE',
keywords='mailcap 1524',
packages=['mailcap_fix'],
)
|
Fix if encoding is not utf-8
|
Fix if encoding is not utf-8
|
Python
|
unlicense
|
michael-lazar/mailcap_fix
|
---
+++
@@ -4,7 +4,7 @@
name='mailcap-fix',
version='0.1.1',
description='A patched mailcap module that conforms to RFC 1524',
- long_description=open('README.rst').read(),
+ long_description=open('README.rst', encoding='utf-8').read(),
url='https://github.com/michael-lazar/mailcap_fix',
author='Michael Lazar',
author_email='lazar.michael22@gmail.com',
|
81ce1495687b55307bfbb4ba67cab1fe1dea1e9a
|
setup.py
|
setup.py
|
# -*- coding: utf-8 -*-
from __future__ import print_function
from setuptools import setup
try:
from ipythonpip import cmdclass
except:
cmdclass = lambda *args: None
setup(
name='d3networkx',
version='0.1',
description='Visualize networkx graphs using D3.js in the IPython notebook.',
author='Jonathan Frederic',
author_email='jon.freder@gmail.com',
license='MIT License',
url='https://github.com/jdfreder/ipython-d3networkx',
keywords='python ipython javascript d3 networkx d3networkx widget',
classifiers=['Development Status :: 4 - Beta',
'Programming Language :: Python',
'License :: OSI Approved :: MIT License'],
packages=['d3networkx'],
include_package_data=True,
install_requires=["ipython-pip"],
cmdclass=cmdclass('d3networkx'),
)
|
# -*- coding: utf-8 -*-
from __future__ import print_function
from setuptools import setup
try:
from ipythonpip import cmdclass
except:
import pip, importlib
pip.main(['install', 'ipython-pip']); cmdclass = importlib.import_module('ipythonpip').cmdclass
setup(
name='d3networkx',
version='0.1',
description='Visualize networkx graphs using D3.js in the IPython notebook.',
author='Jonathan Frederic',
author_email='jon.freder@gmail.com',
license='MIT License',
url='https://github.com/jdfreder/ipython-d3networkx',
keywords='python ipython javascript d3 networkx d3networkx widget',
classifiers=['Development Status :: 4 - Beta',
'Programming Language :: Python',
'License :: OSI Approved :: MIT License'],
packages=['d3networkx'],
include_package_data=True,
install_requires=["ipython-pip"],
cmdclass=cmdclass('d3networkx'),
)
|
Fix bug where installer wasn't working on non ipython-pip machines.
|
Fix bug where installer wasn't working on non ipython-pip machines.
|
Python
|
mit
|
jdfreder/ipython-d3networkx,exe0cdc/ipython-d3networkx,exe0cdc/ipython-d3networkx,joshainglis/ipython-d3networkx
|
---
+++
@@ -4,7 +4,8 @@
try:
from ipythonpip import cmdclass
except:
- cmdclass = lambda *args: None
+ import pip, importlib
+ pip.main(['install', 'ipython-pip']); cmdclass = importlib.import_module('ipythonpip').cmdclass
setup(
name='d3networkx',
|
d26e7264066d0ae475edf55b533fa44276775fac
|
setup.py
|
setup.py
|
#!/usr/bin/env python
from setuptools import setup, find_packages
import os
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name='cb-response-surveyor',
author='Keith McCammon',
author_email='keith@redcanary.co',
url='https://github.com/redcanaryco/cb-response-surveyor',
license='MIT',
packages=find_packages(),
description='Extracts summarized process data from Cb Enterprise Response ',
version='0.1',
classifiers=[
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'License :: Freely Distributable',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
],
install_requires=[
'cbapi'
]
)
|
#!/usr/bin/env python
from setuptools import setup, find_packages
import os
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name='cb-response-surveyor',
author='Keith McCammon',
author_email='keith@redcanary.com',
url='https://github.com/redcanaryco/cb-response-surveyor',
license='MIT',
packages=find_packages(),
description='Extracts summarized process data from Cb Enterprise Response ',
version='0.1',
classifiers=[
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'License :: Freely Distributable',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
],
install_requires=[
'cbapi'
]
)
|
Change my email. Very important.
|
Change my email. Very important.
Not actually important at all.
|
Python
|
mit
|
redcanaryco/cb-response-surveyor
|
---
+++
@@ -10,7 +10,7 @@
setup(
name='cb-response-surveyor',
author='Keith McCammon',
- author_email='keith@redcanary.co',
+ author_email='keith@redcanary.com',
url='https://github.com/redcanaryco/cb-response-surveyor',
license='MIT',
packages=find_packages(),
|
e90cc08b755b96ef892e4fb25d43f3b25d89fae8
|
_tests/python_check_version.py
|
_tests/python_check_version.py
|
import os
import sys
current_version = list(sys.version_info[:3])
print("current_version: %s" % str(current_version))
expected_version = map(int, os.environ["EXPECTED_PYTHON_VERSION"].split("."))
print("expected_version: %s" % str(expected_version))
assert current_version == expected_version
|
import os
import sys
current_version = list(sys.version_info[:3])
print("current_version: %s" % str(current_version))
expected_version = list(
map(int, os.environ["EXPECTED_PYTHON_VERSION"].split(".")))
print("expected_version: %s" % str(expected_version))
assert current_version == expected_version
|
Fix python_version_check on python 3
|
tests: Fix python_version_check on python 3
|
Python
|
apache-2.0
|
scikit-build/scikit-ci-addons,scikit-build/scikit-ci-addons
|
---
+++
@@ -5,7 +5,8 @@
current_version = list(sys.version_info[:3])
print("current_version: %s" % str(current_version))
-expected_version = map(int, os.environ["EXPECTED_PYTHON_VERSION"].split("."))
+expected_version = list(
+ map(int, os.environ["EXPECTED_PYTHON_VERSION"].split(".")))
print("expected_version: %s" % str(expected_version))
assert current_version == expected_version
|
f3883a6536498fe0ce981a612a4ff1998e430fa8
|
setup.py
|
setup.py
|
from setuptools import setup, find_packages
with open('README.rst') as readme:
next(readme)
long_description = ''.join(readme).strip()
setup(
name='pytest-xpara',
version='0.0.0',
description='An extended parametrizing plugin of pytest.',
url='https://github.com/tonyseek/pytest-xpara',
long_description=long_description,
keywords=['pytest', 'parametrize', 'yaml'],
author='Jiangge Zhang',
author_email='tonyseek@gmail.com',
license='MIT',
packages=find_packages(),
zip_safe=False,
platforms=['any'],
install_requires=[
'pytest',
],
extras_require={
'yaml': ['PyYAML'],
'toml': ['toml'],
},
entry_points={
'pytest11': [
'xpara = pytest_xpara.plugin',
],
},
classifiers=[
'Development Status :: 1 - Planning',
'Environment :: Plugins',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Topic :: Software Development :: Testing',
'Topic :: Software Development :: Libraries :: Python Modules',
],
)
|
from setuptools import setup, find_packages
with open('README.rst') as readme:
next(readme)
long_description = ''.join(readme).strip()
setup(
name='pytest-xpara',
version='0.0.0',
description='An extended parametrizing plugin of pytest.',
url='https://github.com/tonyseek/pytest-xpara',
long_description=long_description,
keywords=['pytest', 'parametrize', 'yaml'],
author='Jiangge Zhang',
author_email='tonyseek@gmail.com',
license='MIT',
packages=find_packages(),
zip_safe=False,
platforms=['any'],
install_requires=[
'pytest',
],
extras_require={
'yaml': ['PyYAML'],
'toml': ['toml'],
},
entry_points={
'pytest11': [
'xpara = pytest_xpara.plugin',
],
},
classifiers=[
'Development Status :: 3 - Alpha',
'Environment :: Plugins',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Topic :: Software Development :: Testing',
'Topic :: Software Development :: Libraries :: Python Modules',
],
)
|
Update PyPI status to alpha
|
Update PyPI status to alpha
|
Python
|
mit
|
tonyseek/pytest-xpara
|
---
+++
@@ -30,7 +30,7 @@
],
},
classifiers=[
- 'Development Status :: 1 - Planning',
+ 'Development Status :: 3 - Alpha',
'Environment :: Plugins',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
|
fba24207cc48aee53e023992be67ced518dc3e9d
|
utils.py
|
utils.py
|
import os
import boto
import boto.s3
from boto.s3.key import Key
import requests
import uuid
# http://stackoverflow.com/a/42493144
def upload_url_to_s3(image_url):
image_res = requests.get(image_url, stream=True)
image = image_res.raw
image_data = image.read()
fname = '{}.jpg'.format(str(uuid.uuid4()))
conn = boto.connect_s3(os.environ['AWS_ACCESS_KEY_ID_DIVERSEUI'],
os.environ['AWS_SECRET_KEY_DIVERSEUI'])
bucket = conn.get_bucket('diverse-ui')
k = Key(bucket, 'faces/{}'.format(fname))
k.set_contents_from_string(image_data)
k.make_public()
return 'https://d3iw72m71ie81c.cloudfront.net/{}'.format(fname)
|
import os
import boto
import boto.s3
from boto.s3.key import Key
import requests
import uuid
# http://stackoverflow.com/a/42493144
def upload_url_to_s3(image_url):
image_res = requests.get(image_url, stream=True)
image = image_res.raw
image_data = image.read()
fname = str(uuid.uuid4())
conn = boto.connect_s3(os.environ['AWS_ACCESS_KEY_ID_DIVERSEUI'],
os.environ['AWS_SECRET_KEY_DIVERSEUI'])
bucket = conn.get_bucket('diverse-ui')
k = Key(bucket, 'faces/{}'.format(fname))
k.set_contents_from_string(image_data)
k.make_public()
return 'https://d3iw72m71ie81c.cloudfront.net/{}'.format(fname)
|
Use uuid as file name
|
Use uuid as file name
|
Python
|
mit
|
reneepadgham/diverseui,reneepadgham/diverseui,reneepadgham/diverseui
|
---
+++
@@ -12,7 +12,7 @@
image = image_res.raw
image_data = image.read()
- fname = '{}.jpg'.format(str(uuid.uuid4()))
+ fname = str(uuid.uuid4())
conn = boto.connect_s3(os.environ['AWS_ACCESS_KEY_ID_DIVERSEUI'],
os.environ['AWS_SECRET_KEY_DIVERSEUI'])
|
7632acdf82a6aecc28341087195934ae97675e0e
|
bayesian_jobs/handlers/sync_to_graph.py
|
bayesian_jobs/handlers/sync_to_graph.py
|
import datetime
from cucoslib.models import Analysis, Package, Version, Ecosystem
from cucoslib.workers import GraphImporterTask
from .base import BaseHandler
class SyncToGraph(BaseHandler):
""" Sync all finished analyses to Graph DB """
def execute(self):
start = 0
while True:
results = self.postgres.session.query(Analysis).\
join(Version).\
join(Package).\
join(Ecosystem).\
filter(Analysis.finished_at != None).\
slice(start, start + 100).all()
if not results:
self.log.info("Syncing to GraphDB finished")
break
self.log.info("Updating results, slice offset is %s", start)
start += 100
for entry in results:
arguments = {'ecosystem': entry.version.package.ecosystem.name,
'name': entry.version.package.name,
'version': entry.version.identifier}
try:
log.info('Synchronizing {ecosystem}/{name}/{version} ...'.format(**arguments))
GraphImporterTask.create_test_instance().execute(arguments)
except Exception as e:
self.log.exception('Failed to synchronize {ecosystem}/{name}/{version}'.
format(**arguments))
del entry
|
import datetime
from cucoslib.models import Analysis, Package, Version, Ecosystem
from cucoslib.workers import GraphImporterTask
from .base import BaseHandler
class SyncToGraph(BaseHandler):
""" Sync all finished analyses to Graph DB """
def execute(self):
start = 0
while True:
results = self.postgres.session.query(Analysis).\
join(Version).\
join(Package).\
join(Ecosystem).\
filter(Analysis.finished_at != None).\
slice(start, start + 100).all()
if not results:
self.log.info("Syncing to GraphDB finished")
break
self.log.info("Updating results, slice offset is %s", start)
start += 100
for entry in results:
arguments = {'ecosystem': entry.version.package.ecosystem.name,
'name': entry.version.package.name,
'version': entry.version.identifier}
try:
self.log.info('Synchronizing {ecosystem}/{name}/{version} ...'.format(**arguments))
GraphImporterTask.create_test_instance().execute(arguments)
except Exception as e:
self.log.exception('Failed to synchronize {ecosystem}/{name}/{version}'.
format(**arguments))
del entry
|
Fix instance variable in graph sync job
|
Fix instance variable in graph sync job
|
Python
|
apache-2.0
|
fabric8-analytics/fabric8-analytics-jobs,fabric8-analytics/fabric8-analytics-jobs
|
---
+++
@@ -29,7 +29,7 @@
'name': entry.version.package.name,
'version': entry.version.identifier}
try:
- log.info('Synchronizing {ecosystem}/{name}/{version} ...'.format(**arguments))
+ self.log.info('Synchronizing {ecosystem}/{name}/{version} ...'.format(**arguments))
GraphImporterTask.create_test_instance().execute(arguments)
except Exception as e:
self.log.exception('Failed to synchronize {ecosystem}/{name}/{version}'.
|
ca5d96b1253d4a2046b30086ad9ae11822a6fcf8
|
doc/conf.py
|
doc/conf.py
|
import os
import sys
import qiprofile_rest
extensions = ['sphinx.ext.autodoc', 'sphinx.ext.intersphinx', 'sphinx.ext.todo']
autoclass_content = "both"
autodoc_default_flags= ['members', 'show-inheritance']
source_suffix = '.rst'
master_doc = 'index'
project = u'qiprofile-rest'
copyright = u'2014, OHSU Knight Cancer Institute'
pygments_style = 'sphinx'
htmlhelp_basename = 'qiprofilerestdoc'
html_title = "qiprofile-rest"
def skip(app, what, name, obj, skip, options):
return False if name == "__init__" else skip
def setup(app):
app.connect("autodoc-skip-member", skip)
|
import os
import sys
import qiprofile_rest
extensions = ['sphinx.ext.autodoc', 'sphinx.ext.intersphinx', 'sphinx.ext.todo']
autoclass_content = "both"
autodoc_default_flags= ['members', 'show-inheritance']
source_suffix = '.rst'
master_doc = 'index'
project = u'qiprofile-rest'
copyright = u'2014, OHSU Knight Cancer Institute. This software is not intended for clinical use'
pygments_style = 'sphinx'
htmlhelp_basename = 'qiprofilerestdoc'
html_title = "qiprofile-rest"
def skip(app, what, name, obj, skip, options):
return False if name == "__init__" else skip
def setup(app):
app.connect("autodoc-skip-member", skip)
|
Move clinical disclaimer to doc.
|
Move clinical disclaimer to doc.
|
Python
|
bsd-2-clause
|
ohsu-qin/qirest,ohsu-qin/qiprofile-rest
|
---
+++
@@ -8,7 +8,7 @@
source_suffix = '.rst'
master_doc = 'index'
project = u'qiprofile-rest'
-copyright = u'2014, OHSU Knight Cancer Institute'
+copyright = u'2014, OHSU Knight Cancer Institute. This software is not intended for clinical use'
pygments_style = 'sphinx'
htmlhelp_basename = 'qiprofilerestdoc'
html_title = "qiprofile-rest"
|
d5f02b13db9b6d23e15bc07a985b8c67644ffb44
|
pyclibrary/__init__.py
|
pyclibrary/__init__.py
|
# -*- coding: utf-8 -*-
# -----------------------------------------------------------------------------
# Copyright 2015 by PyCLibrary Authors, see AUTHORS for more details.
#
# Distributed under the terms of the MIT/X11 license.
#
# The full license is in the file LICENCE, distributed with this software.
# -----------------------------------------------------------------------------
from __future__ import (division, unicode_literals, print_function,
absolute_import)
from .c_parser import win_defs, CParser
from .c_library import CLibrary, address_of, build_array
from .errors import DefinitionError
from .init import init, auto_init
|
# -*- coding: utf-8 -*-
# -----------------------------------------------------------------------------
# Copyright 2015 by PyCLibrary Authors, see AUTHORS for more details.
#
# Distributed under the terms of the MIT/X11 license.
#
# The full license is in the file LICENCE, distributed with this software.
# -----------------------------------------------------------------------------
from __future__ import (division, unicode_literals, print_function,
absolute_import)
import logging
logging.getLogger('pyclibrary').addHandler(logging.NullHandler())
from .c_parser import win_defs, CParser
from .c_library import CLibrary, address_of, build_array
from .errors import DefinitionError
from .init import init, auto_init
|
Add NullHandler to avoid logging complaining for nothing.
|
Add NullHandler to avoid logging complaining for nothing.
|
Python
|
mit
|
MatthieuDartiailh/pyclibrary,mrh1997/pyclibrary,mrh1997/pyclibrary,MatthieuDartiailh/pyclibrary,mrh1997/pyclibrary,duguxy/pyclibrary,duguxy/pyclibrary,duguxy/pyclibrary
|
---
+++
@@ -8,6 +8,8 @@
# -----------------------------------------------------------------------------
from __future__ import (division, unicode_literals, print_function,
absolute_import)
+import logging
+logging.getLogger('pyclibrary').addHandler(logging.NullHandler())
from .c_parser import win_defs, CParser
from .c_library import CLibrary, address_of, build_array
|
b0c217acb04d377bdd0d37ce8fc61a88bd97ae77
|
pyelevator/elevator.py
|
pyelevator/elevator.py
|
from .base import Client
class RangeIter(object):
def __init__(self, range_datas):
self._container = range_datas if self._valid_range(range_datas) else None
def _valid_range(self, range_datas):
if (not isinstance(range_datas, tuple) or
any(not isinstance(pair, tuple) for pair in range_datas)):
raise ValueError("Range datas format not recognized")
return True
def __iter__(self):
return self.forward()
def forward(self):
current_item = 0
while (current_item < len(self._container)):
container = self._container[current_item]
current_item += 1
yield container
class Elevator(Client):
def Get(self, key):
return self.send(self.db_uid, 'GET', [key])
def MGet(self, keys):
return self.send(self.db_uid, 'MGET', [keys])
def Put(self, key, value):
return self.send(self.db_uid, 'PUT', [key, value])
def Delete(self, key):
return self.send(self.db_uid, 'DELETE', [key])
def Range(self, start=None, limit=None):
return self.send(self.db_uid, 'RANGE', [start, limit])
def RangeIter(self, start=None, limit=None):
range_datas = self.Range(start, limit)
return RangeIter(range_datas)
|
from .base import Client
class RangeIter(object):
def __init__(self, range_datas):
self._container = range_datas if self._valid_range(range_datas) else None
def _valid_range(self, range_datas):
if (not isinstance(range_datas, tuple) or
any(not isinstance(pair, tuple) for pair in range_datas)):
raise ValueError("Range datas format not recognized")
return True
def __iter__(self):
return self.forward()
def forward(self):
current_item = 0
while (current_item < len(self._container)):
container = self._container[current_item]
current_item += 1
yield container
class Elevator(Client):
def Get(self, key):
return self.send(self.db_uid, 'GET', [key])
def MGet(self, keys):
return self.send(self.db_uid, 'MGET', [keys])
def Put(self, key, value):
return self.send(self.db_uid, 'PUT', [key, value])
def Delete(self, key):
return self.send(self.db_uid, 'DELETE', [key])
def Range(self, start=None, limit=None):
return self.send(self.db_uid, 'RANGE', [start, limit])
def RangeIter(self, key_from=None, key_to=None):
range_datas = self.Range(key_from, key_to)
return RangeIter(range_datas)
|
Update : RangeIter args name changed
|
Update : RangeIter args name changed
|
Python
|
mit
|
oleiade/py-elevator
|
---
+++
@@ -38,7 +38,7 @@
def Range(self, start=None, limit=None):
return self.send(self.db_uid, 'RANGE', [start, limit])
- def RangeIter(self, start=None, limit=None):
- range_datas = self.Range(start, limit)
+ def RangeIter(self, key_from=None, key_to=None):
+ range_datas = self.Range(key_from, key_to)
return RangeIter(range_datas)
|
71dca4da0aa7a0415cc7248f0f4ee33ab3aa550e
|
setup.py
|
setup.py
|
#!/usr/bin/env python
import os
from setuptools import setup, find_packages
README = os.path.join(os.path.dirname(__file__), 'README.rst')
# when running tests using tox, README.md is not found
try:
with open(README) as file:
long_description = file.read()
except Exception:
long_description = ''
setup(
name='python-resize-image',
version='1.1.10',
description='A Small python package to easily resize images',
long_description=long_description,
url='https://github.com/VingtCinq/python-resize-image',
author='Charles TISSIER',
author_email='charles@vingtcinq.io',
license='MIT',
classifiers=[
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'Topic :: Software Development :: Libraries :: Python Modules',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 2.7',
],
keywords='image resize resizing python',
packages=find_packages(),
install_requires=['pillow', 'requests'],
test_suite='tests',
)
|
#!/usr/bin/env python
import os
from setuptools import setup, find_packages
README = os.path.join(os.path.dirname(__file__), 'README.rst')
# when running tests using tox, README.md is not found
try:
with open(README) as file:
long_description = file.read()
except Exception:
long_description = ''
setup(
name='python-resize-image',
version='1.1.10',
description='A Small python package to easily resize images',
long_description=long_description,
url='https://github.com/VingtCinq/python-resize-image',
author='Charles TISSIER',
author_email='charles@vingtcinq.io',
license='MIT',
classifiers=[
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'Topic :: Software Development :: Libraries :: Python Modules',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.4',
],
keywords='image resize resizing python',
packages=find_packages(),
install_requires=['pillow', 'requests'],
test_suite='tests',
)
|
Add use with python3 in the classifiers
|
Add use with python3 in the classifiers
|
Python
|
mit
|
VingtCinq/python-resize-image,charlesthk/python-resize-image,charlesthk/python-resize-image,VingtCinq/python-resize-image
|
---
+++
@@ -28,6 +28,8 @@
'Topic :: Software Development :: Libraries :: Python Modules',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 2.7',
+ 'Programming Language :: Python :: 3',
+ 'Programming Language :: Python :: 3.4',
],
keywords='image resize resizing python',
packages=find_packages(),
|
8f87749e5c7373015290306677fe9651cc5e54c1
|
ibmcnx/doc/DataSources.py
|
ibmcnx/doc/DataSources.py
|
######
# Check ExId (GUID) by Email through JDBC
#
# Author: Christoph Stoettner
# Mail: christoph.stoettner@stoeps.de
# Documentation: http://scripting101.stoeps.de
#
# Version: 2.0
# Date: 2014-06-04
#
# License: Apache 2.0
#
# Check ExId of a User in all Connections Applications
import ibmcnx.functions
cell = AdminControl.getCell()
cellname = "/Cell:" + cell + "/"
# Get a list of all databases except DefaultEJBTimerDataSource and OTiSDataSource
dbs = AdminConfig.list('DataSource',AdminConfig.getid(cellname)).splitlines()
dblist = []
for db in dbs:
db = db.split('(')
n = 0
for i in db:
if n == 0 and i != "DefaultEJBTimerDataSource" and i != 'OTiSDataSource':
dblist.append(str(i).replace('"',''))
n += 1
print dblist
for db in dblist:
print db
# for db in dbs:
# t1 = ibmcnx.functions.getDSId( db )
# AdminConfig.show( t1 )
# print '\n\n'
# AdminConfig.showall( t1 )
# AdminConfig.showAttribute(t1,'statementCacheSize' )
# AdminConfig.showAttribute(t1,'[statementCacheSize]' )
|
######
# Check ExId (GUID) by Email through JDBC
#
# Author: Christoph Stoettner
# Mail: christoph.stoettner@stoeps.de
# Documentation: http://scripting101.stoeps.de
#
# Version: 2.0
# Date: 2014-06-04
#
# License: Apache 2.0
#
# Check ExId of a User in all Connections Applications
import ibmcnx.functions
cell = AdminControl.getCell()
cellname = "/Cell:" + cell + "/"
# Get a list of all databases except DefaultEJBTimerDataSource and OTiSDataSource
dbs = AdminConfig.list('DataSource',AdminConfig.getid(cellname)).splitlines()
dblist = []
for db in dbs:
db = db.split('(')
n = 0
for i in db:
if n == 0 and i != "DefaultEJBTimerDataSource" and i != 'OTiSDataSource':
dblist.append(str(i).replace('"',''))
n += 1
dblist.sort()
for db in dblist:
print db
# for db in dbs:
# t1 = ibmcnx.functions.getDSId( db )
# AdminConfig.show( t1 )
# print '\n\n'
# AdminConfig.showall( t1 )
# AdminConfig.showAttribute(t1,'statementCacheSize' )
# AdminConfig.showAttribute(t1,'[statementCacheSize]' )
|
Create documentation of DataSource Settings
|
8: Create documentation of DataSource Settings
Task-Url: http://github.com/stoeps13/ibmcnx2/issues/issue/8
|
Python
|
apache-2.0
|
stoeps13/ibmcnx2,stoeps13/ibmcnx2
|
---
+++
@@ -27,7 +27,8 @@
if n == 0 and i != "DefaultEJBTimerDataSource" and i != 'OTiSDataSource':
dblist.append(str(i).replace('"',''))
n += 1
-print dblist
+
+dblist.sort()
for db in dblist:
print db
|
6a2ab522c07a274920144f93f26361843d61c868
|
setup.py
|
setup.py
|
from setuptools import setup, find_packages
import os
version = '0.1.1'
LONG_DESCRIPTION = """
===============
django-helpdesk
===============
This is a Django-powered helpdesk ticket tracker, designed to
plug into an existing Django website and provide you with
internal (or, perhaps, external) helpdesk management.
"""
setup(
name='django-helpdesk',
version=version,
description="Django-powered ticket tracker for your helpdesk",
long_description=LONG_DESCRIPTION,
classifiers=[
"Programming Language :: Python",
"Topic :: Software Development :: Libraries :: Python Modules",
"Framework :: Django",
"Environment :: Web Environment",
"Operating System :: OS Independent",
"Intended Audience :: Customer Service",
"License :: OSI Approved :: BSD License",
"Natural Language :: English",
"Topic :: Office/Business",
"Topic :: Software Development :: Bug Tracking",
],
keywords=['django', 'helpdesk', 'tickets', 'incidents', 'cases'],
author='Ross Poulton',
author_email='ross@rossp.org',
url='http://github.com/rossp/django-helpdesk',
license='BSD',
packages=find_packages(),
include_package_data=True,
zip_safe=False,
install_requires=['setuptools'],
)
|
from setuptools import setup, find_packages
import os
version = '0.1.2'
LONG_DESCRIPTION = """
===============
django-helpdesk
===============
This is a Django-powered helpdesk ticket tracker, designed to
plug into an existing Django website and provide you with
internal (or, perhaps, external) helpdesk management.
"""
setup(
name='django-helpdesk',
version=version,
description="Django-powered ticket tracker for your helpdesk",
long_description=LONG_DESCRIPTION,
classifiers=[
"Programming Language :: Python",
"Topic :: Software Development :: Libraries :: Python Modules",
"Framework :: Django",
"Environment :: Web Environment",
"Operating System :: OS Independent",
"Intended Audience :: Customer Service",
"License :: OSI Approved :: BSD License",
"Natural Language :: English",
"Topic :: Office/Business",
"Topic :: Software Development :: Bug Tracking",
],
keywords=['django', 'helpdesk', 'tickets', 'incidents', 'cases'],
author='Ross Poulton',
author_email='ross@rossp.org',
url='http://github.com/rossp/django-helpdesk',
license='BSD',
packages=find_packages(),
include_package_data=True,
zip_safe=False,
install_requires=['setuptools'],
)
|
Increment version number for updated pypi package
|
Increment version number for updated pypi package
|
Python
|
bsd-3-clause
|
fjcapdevila/django-helpdesk,vladyslav2/django-helpdesk,fjcapdevila/django-helpdesk,gjedeer/django-helpdesk-issue-164,comsnetwork/django-helpdesk,comsnetwork/django-helpdesk,harrisonfeng/django-helpdesk,comsnetwork/django-helpdesk,temnoregg/django-helpdesk,harrisonfeng/django-helpdesk,django-helpdesk/django-helpdesk,rossp/django-helpdesk,chriscauley/django-helpdesk,chriscauley/django-helpdesk,fjcapdevila/django-helpdesk,iedparis8/django-helpdesk,django-helpdesk/django-helpdesk,mrkiwi-nz/django-helpdesk,rossp/django-helpdesk,vladyslav2/django-helpdesk,rossp/django-helpdesk,temnoregg/django-helpdesk,fjcapdevila/django-helpdesk,vladyslav2/django-helpdesk,harrisonfeng/django-helpdesk,mrkiwi-nz/django-helpdesk,chriscauley/django-helpdesk,iedparis8/django-helpdesk,django-helpdesk/django-helpdesk,temnoregg/django-helpdesk,django-helpdesk/django-helpdesk,chriscauley/django-helpdesk,gwasser/django-helpdesk,harrisonfeng/django-helpdesk,iedparis8/django-helpdesk,vladyslav2/django-helpdesk,mrkiwi-nz/django-helpdesk,iedparis8/django-helpdesk,temnoregg/django-helpdesk,gjedeer/django-helpdesk-issue-164,gwasser/django-helpdesk,gwasser/django-helpdesk,comsnetwork/django-helpdesk,mrkiwi-nz/django-helpdesk,gjedeer/django-helpdesk-issue-164,gwasser/django-helpdesk,rossp/django-helpdesk
|
---
+++
@@ -1,7 +1,7 @@
from setuptools import setup, find_packages
import os
-version = '0.1.1'
+version = '0.1.2'
LONG_DESCRIPTION = """
===============
|
590de85fdb151e11079796c68f300d4fe7559995
|
setup.py
|
setup.py
|
import subprocess
import sys
from setuptools import Command, setup
class RunTests(Command):
user_options = []
def initialize_options(self):
pass
def finalize_options(self):
pass
def run(self):
errno = subprocess.call([sys.executable, '-m', 'unittest', 'gis_metadata.tests.tests'])
raise SystemExit(errno)
with open('README.md') as readme:
long_description = readme.read()
setup(
name='gis_metadata_parser',
description='Parser for GIS metadata standards including FGDC and ISO-19115',
long_description=long_description,
long_description_content_type='text/markdown',
keywords='arcgis,fgdc,iso,ISO-19115,ISO-19139,gis,metadata,parser,xml,gis_metadata,gis_metadata_parser',
version='1.2.0',
packages=[
'gis_metadata', 'gis_metadata.tests'
],
install_requires=[
'frozendict>=1.2', 'parserutils>=1.1', 'six>=1.9.0'
],
tests_require=['mock'],
url='https://github.com/consbio/gis-metadata-parser',
license='BSD',
cmdclass={'test': RunTests}
)
|
import subprocess
import sys
from setuptools import Command, setup
class RunTests(Command):
user_options = []
def initialize_options(self):
pass
def finalize_options(self):
pass
def run(self):
errno = subprocess.call([sys.executable, '-m', 'unittest', 'gis_metadata.tests.tests'])
raise SystemExit(errno)
with open('README.md') as readme:
long_description = readme.read()
setup(
name='gis_metadata_parser',
description='Parser for GIS metadata standards including FGDC and ISO-19115',
long_description=long_description,
long_description_content_type='text/markdown',
keywords='arcgis,fgdc,iso,ISO-19115,ISO-19139,gis,metadata,parser,xml,gis_metadata,gis_metadata_parser',
version='1.2.1',
packages=[
'gis_metadata', 'gis_metadata.tests'
],
install_requires=[
'frozendict>=1.2', 'parserutils>=1.1', 'six>=1.9.0'
],
tests_require=['mock'],
url='https://github.com/consbio/gis-metadata-parser',
license='BSD',
cmdclass={'test': RunTests}
)
|
Increment version for mock test fix
|
Increment version for mock test fix
|
Python
|
bsd-3-clause
|
consbio/gis-metadata-parser
|
---
+++
@@ -28,7 +28,7 @@
long_description=long_description,
long_description_content_type='text/markdown',
keywords='arcgis,fgdc,iso,ISO-19115,ISO-19139,gis,metadata,parser,xml,gis_metadata,gis_metadata_parser',
- version='1.2.0',
+ version='1.2.1',
packages=[
'gis_metadata', 'gis_metadata.tests'
],
|
9b24bd3a71a8c5564c4f2c36c38872339d176aae
|
setup.py
|
setup.py
|
#!/usr/bin/env python
#
# Author: Logan Gunthorpe <logang@deltatee.com>
# Copyright (c) Deltatee Enterprises Ltd. 2015, All rights reserved.
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 3.0 of the License, or (at your option) any later version.
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library.
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
setup(name='pyft232',
version='0.8',
description="Python bindings to d2xx and libftdi to access FT232 chips with "
"the same interface as pyserial. Using this method gives easy access "
"to the additional features on the chip like CBUS GPIO.",
long_description=open('README.md', 'rt').read(),
author='Logan Gunthorpe',
author_email='logang@deltatee.com',
packages=['ft232'],
install_requires=[
'pyusb >= 0.4',
'pyserial >= 2.5',
]
)
|
#!/usr/bin/env python
#
# Author: Logan Gunthorpe <logang@deltatee.com>
# Copyright (c) Deltatee Enterprises Ltd. 2015, All rights reserved.
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 3.0 of the License, or (at your option) any later version.
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library.
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
setup(name='pyft232',
version='0.8',
description="Python bindings to d2xx and libftdi to access FT232 chips with "
"the same interface as pyserial. Using this method gives easy access "
"to the additional features on the chip like CBUS GPIO.",
long_description=open('README.md', 'rt').read(),
long_description_content_type="text/markdown",
author='Logan Gunthorpe',
author_email='logang@deltatee.com',
packages=['ft232'],
install_requires=[
'pyusb >= 0.4',
'pyserial >= 2.5',
]
)
|
Add long description for PyPI upload
|
Add long description for PyPI upload
|
Python
|
lgpl-2.1
|
lsgunth/pyft232
|
---
+++
@@ -27,6 +27,7 @@
"the same interface as pyserial. Using this method gives easy access "
"to the additional features on the chip like CBUS GPIO.",
long_description=open('README.md', 'rt').read(),
+ long_description_content_type="text/markdown",
author='Logan Gunthorpe',
author_email='logang@deltatee.com',
packages=['ft232'],
|
84daa137c8526a508fa1f2dcf8968137d75e8a0b
|
setup.py
|
setup.py
|
from setuptools import setup, find_packages
import oscrypto
setup(
name='oscrypto',
version=oscrypto.__version__,
description='Crytographic services provided by the operating system, including key generation, encryption, decryption, signing, verifying and key derivation',
long_description='Docs for this project are maintained at https://github.com/wbond/oscrypto#readme.',
url='https://github.com/wbond/oscrypto',
author='wbond',
author_email='will@wbond.net',
license='MIT',
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
],
keywords='crypto',
packages=find_packages(exclude=['tests*', 'dev*'])
)
|
from setuptools import setup, find_packages
import oscrypto
setup(
name='oscrypto',
version=oscrypto.__version__,
description='Crytographic services provided by the operating system, including key generation, encryption, decryption, signing, verifying and key derivation',
long_description='Docs for this project are maintained at https://github.com/wbond/oscrypto#readme.',
url='https://github.com/wbond/oscrypto',
author='wbond',
author_email='will@wbond.net',
license='MIT',
classifiers=[
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
],
keywords='crypto',
install_requires=['asn1crypto'],
packages=find_packages(exclude=['tests*', 'dev*'])
)
|
Add asn1crypto as a dependency
|
Add asn1crypto as a dependency
|
Python
|
mit
|
wbond/oscrypto
|
---
+++
@@ -30,5 +30,6 @@
keywords='crypto',
+ install_requires=['asn1crypto'],
packages=find_packages(exclude=['tests*', 'dev*'])
)
|
9c12bcb4a5b5b2fee28476e047855dca50b3867c
|
mwbase/attr_dict.py
|
mwbase/attr_dict.py
|
from collections import OrderedDict
class AttrDict(OrderedDict):
def __init__(self, *args, **kwargs):
super(AttrDict, self).__init__(*args, **kwargs)
def __getattr__(self, attr):
if attr not in self:
raise AttributeError(attr)
else:
return self[attr]
def __setattr__(self, attr, value):
self[attr] = value
|
from collections import OrderedDict
class AttrDict(OrderedDict):
def __init__(self, *args, **kwargs):
super(OrderedDict, self).__init__(*args, **kwargs)
def __getattribute__(self, attr):
if attr in self:
return self[attr]
else:
return super(OrderedDict, self).__getattribute__(attr)
def __setattr__(self, attr, value):
self[attr] = value
|
Switch use of getattr to getattribute.
|
Switch use of getattr to getattribute.
|
Python
|
mit
|
mediawiki-utilities/python-mwbase
|
---
+++
@@ -3,13 +3,13 @@
class AttrDict(OrderedDict):
def __init__(self, *args, **kwargs):
- super(AttrDict, self).__init__(*args, **kwargs)
+ super(OrderedDict, self).__init__(*args, **kwargs)
- def __getattr__(self, attr):
- if attr not in self:
- raise AttributeError(attr)
+ def __getattribute__(self, attr):
+ if attr in self:
+ return self[attr]
else:
- return self[attr]
+ return super(OrderedDict, self).__getattribute__(attr)
def __setattr__(self, attr, value):
self[attr] = value
|
5ecb6e7c56aa12019c4ca2c47bdd87c49981ad78
|
setup.py
|
setup.py
|
from setuptools import setup, find_packages
install_requires=['django>=1.5', 'django-easysettings', 'pytz']
try:
import importlib
except ImportError:
install_requires.append('importlib')
setup(
name='django-password-policies',
version=__import__('password_policies').__version__,
description='A Django application to implent password policies.',
long_description="""\
django-password-policies is an application for the Django framework that
provides unicode-aware password policies on password changes and resets
and a mechanism to force password changes.
""",
author='Tarak Blah',
author_email='halbkarat@gmail.com',
url='https://github.com/tarak/django-password-policies',
include_package_data=True,
packages=find_packages(),
zip_safe=False,
classifiers=[
'Development Status :: 3 - Alpha',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Framework :: Django',
'License :: OSI Approved :: BSD License',
'Topic :: Software Development :: Libraries :: Python Modules',
'Topic :: Utilities'
],
install_requires=install_requires,
test_suite='tests.runtests',
)
|
from setuptools import setup, find_packages
install_requires=['django>=1.5', 'django-easysettings', 'pytz']
try:
import importlib
except ImportError:
install_requires.append('importlib')
setup(
name='django-password-policies',
version=__import__('password_policies').__version__,
description='A Django application to implent password policies.',
long_description="""\
django-password-policies is an application for the Django framework that
provides unicode-aware password policies on password changes and resets
and a mechanism to force password changes.
""",
author='Tarak Blah',
author_email='halbkarat@gmail.com',
url='https://github.com/tarak/django-password-policies',
include_package_data=True,
packages=find_packages(),
zip_safe=False,
classifiers=[
'Development Status :: 3 - Alpha',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'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',
'Programming Language :: Python :: 3.4',
'Framework :: Django',
'License :: OSI Approved :: BSD License',
'Topic :: Software Development :: Libraries :: Python Modules',
'Topic :: Utilities'
],
install_requires=install_requires,
test_suite='tests.runtests',
)
|
Add the Language classifiers for 3.x and 2.x
|
Add the Language classifiers for 3.x and 2.x
|
Python
|
bsd-3-clause
|
tarak/django-password-policies,tarak/django-password-policies
|
---
+++
@@ -29,6 +29,12 @@
'Intended Audience :: Developers',
'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',
+ 'Programming Language :: Python :: 3.4',
'Framework :: Django',
'License :: OSI Approved :: BSD License',
'Topic :: Software Development :: Libraries :: Python Modules',
|
012e5d7d80b20220a7a41f7f3488ebe468d6b661
|
setup.py
|
setup.py
|
from setuptools import setup, find_packages
version = '0.2.0'
setup(
name='cmsplugin-plaintext',
version=version,
description='Adds a plaintext plugin for django-cms.',
author='Xenofox, LLC',
author_email='info@xenofox.com',
url='http://bitbucket.org/xenofox/cmsplugin-plaintext/',
packages=find_packages(),
zip_safe=False,
include_package_data=True,
install_requires=[],
)
|
from setuptools import setup, find_packages
version = '0.2.1'
setup(
name='cmsplugin-plaintext-djangocms3',
version=version,
description='Adds a plaintext plugin for django-cms. Forked from https://bitbucket.org/xenofox/cmsplugin-plaintext to add django-cms3 support',
author='Changer',
author_email='support@changer.nl',
url='http://bitbucket.org/changer/cmsplugin-plaintext/',
packages=find_packages(),
zip_safe=False,
include_package_data=True,
install_requires=[],
)
|
Change package name for pypi
|
Change package name for pypi
|
Python
|
bsd-3-clause
|
russmo/cmsplugin-plaintext,russmo/cmsplugin-plaintext
|
---
+++
@@ -1,14 +1,14 @@
from setuptools import setup, find_packages
-version = '0.2.0'
+version = '0.2.1'
setup(
- name='cmsplugin-plaintext',
+ name='cmsplugin-plaintext-djangocms3',
version=version,
- description='Adds a plaintext plugin for django-cms.',
- author='Xenofox, LLC',
- author_email='info@xenofox.com',
- url='http://bitbucket.org/xenofox/cmsplugin-plaintext/',
+ description='Adds a plaintext plugin for django-cms. Forked from https://bitbucket.org/xenofox/cmsplugin-plaintext to add django-cms3 support',
+ author='Changer',
+ author_email='support@changer.nl',
+ url='http://bitbucket.org/changer/cmsplugin-plaintext/',
packages=find_packages(),
zip_safe=False,
include_package_data=True,
|
e20051360f9dbf6a879be7acdd9159b8f068a388
|
setup.py
|
setup.py
|
#!/usr/bin/env python
"""Setup script for the pyparsing module distribution."""
# Setuptools depends on pyparsing (via packaging) as of version 34, so allow
# installing without it to avoid bootstrap problems.
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
import sys
import os
from pyparsing import __version__ as pyparsing_version
modules = ["pyparsing",]
setup(# Distribution meta-data
name = "pyparsing",
version = pyparsing_version,
description = "Python parsing module",
author = "Paul McGuire",
author_email = "ptmcg@users.sourceforge.net",
url = "http://pyparsing.wikispaces.com/",
download_url = "http://sourceforge.net/project/showfiles.php?group_id=97203",
license = "MIT License",
py_modules = modules,
classifiers=[
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'Intended Audience :: Information Technology',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
]
)
|
#!/usr/bin/env python
"""Setup script for the pyparsing module distribution."""
# Setuptools depends on pyparsing (via packaging) as of version 34, so allow
# installing without it to avoid bootstrap problems.
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
import sys
import os
from pyparsing import __version__ as pyparsing_version
modules = ["pyparsing",]
setup(# Distribution meta-data
name = "pyparsing",
version = pyparsing_version,
description = "Python parsing module",
author = "Paul McGuire",
author_email = "ptmcg@users.sourceforge.net",
url = "http://pyparsing.wikispaces.com/",
download_url = "http://sourceforge.net/project/showfiles.php?group_id=97203",
license = "MIT License",
py_modules = modules,
classifiers=[
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'Intended Audience :: Information Technology',
'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',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
]
)
|
Add additional trove classifiers for supported Pythons
|
Add additional trove classifiers for supported Pythons
|
Python
|
mit
|
pyparsing/pyparsing,pyparsing/pyparsing
|
---
+++
@@ -33,11 +33,13 @@
'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',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
+ 'Programming Language :: Python :: 3.6',
]
)
|
89898941b9024f2b2c74b187d9d571a0fadb9926
|
setup.py
|
setup.py
|
# -*- encoding: utf-8 -*-
'''A setuptools script to install strip_recipes
'''
from setuptools import setup
setup(
name='strip_recipes',
version='1.0.0',
description='Create recipes for the LSPE/Strip tester software',
long_description='''
Python library to easily create complex recipes to be used with the LSPE/Strip
tester software. All the Python control structures (if, while, for) can be used''',
author='Maurizio Tomasi',
author_email='maurizio.tomasi@unimiREMOVETHIS.it',
url='https://github.com/ziotom78/strip_recipes',
license='MIT',
classifiers=[
'Development Status :: 3 - Alpha',
'Intended Audience :: Developers'
],
keywords='cosmology laboratory',
test_suite='nose.collector',
tests_require=['nose']
)
|
# -*- encoding: utf-8 -*-
'''A setuptools script to install strip_recipes
'''
from setuptools import setup
setup(
name='strip_recipes',
version='1.0.0',
description='Create recipes for the LSPE/Strip tester software',
long_description='''
Python library to easily create complex recipes to be used with the LSPE/Strip
tester software. All the Python control structures (if, while, for) can be used.
(LSPE is a balloon/ground experiment to search for the B-mode signal in the
polarization pattern of the Cosmic Microwave Background. Strip is the low-frequency
polarimetric instrument that will measure the sky from the ground.)''',
author='Maurizio Tomasi',
author_email='maurizio.tomasi@unimiREMOVETHIS.it',
url='https://github.com/ziotom78/strip_recipes',
license='MIT',
classifiers=[
'Development Status :: 3 - Alpha',
'License :: OSI Approved :: MIT License',
'Topic :: Scientific/Engineering :: Astronomy',
'Topic :: Scientific/Engineering :: Physics',
'Topic :: Software Development :: Code Generators'
],
keywords='cosmology laboratory',
test_suite='nose.collector',
tests_require=['nose']
)
|
Improve the metadata describing the package
|
Improve the metadata describing the package
|
Python
|
mit
|
lspestrip/strip_recipes
|
---
+++
@@ -11,14 +11,20 @@
description='Create recipes for the LSPE/Strip tester software',
long_description='''
Python library to easily create complex recipes to be used with the LSPE/Strip
-tester software. All the Python control structures (if, while, for) can be used''',
+tester software. All the Python control structures (if, while, for) can be used.
+(LSPE is a balloon/ground experiment to search for the B-mode signal in the
+polarization pattern of the Cosmic Microwave Background. Strip is the low-frequency
+polarimetric instrument that will measure the sky from the ground.)''',
author='Maurizio Tomasi',
author_email='maurizio.tomasi@unimiREMOVETHIS.it',
url='https://github.com/ziotom78/strip_recipes',
license='MIT',
classifiers=[
'Development Status :: 3 - Alpha',
- 'Intended Audience :: Developers'
+ 'License :: OSI Approved :: MIT License',
+ 'Topic :: Scientific/Engineering :: Astronomy',
+ 'Topic :: Scientific/Engineering :: Physics',
+ 'Topic :: Software Development :: Code Generators'
],
keywords='cosmology laboratory',
test_suite='nose.collector',
|
bcc1048a11345545013c6ea93b92fc52e639cd98
|
tests/unit/models/reddit/test_widgets.py
|
tests/unit/models/reddit/test_widgets.py
|
from praw.models import (SubredditWidgets, SubredditWidgetsModeration,
Widget, WidgetModeration)
from ... import UnitTest
class TestWidgets(UnitTest):
def test_subredditwidgets_mod(self):
sw = SubredditWidgets(self.reddit.subreddit('fake_subreddit'))
assert isinstance(sw.mod, SubredditWidgetsModeration)
def test_widget_mod(self):
w = Widget(self.reddit, {})
assert isinstance(w.mod, WidgetModeration)
assert w.mod.widget == w
|
from json import dumps
from praw.models import (SubredditWidgets, SubredditWidgetsModeration,
Widget, WidgetModeration)
from praw.models.reddit.widgets import WidgetEncoder
from praw.models.base import PRAWBase
from ... import UnitTest
class TestWidgetEncoder(UnitTest):
def test_bad_encode(self):
data = [1, 'two', SubredditWidgetsModeration(
self.reddit.subreddit('subreddit'), self.reddit)]
try:
dumps(data, cls=WidgetEncoder) # should throw TypeError
except TypeError:
pass # success
else:
assert False
def test_good_encode(self):
data = [1, 'two',
PRAWBase(self.reddit, _data={'_secret': 'no', '3': 3})]
assert '[1, "two", {"3": 3}]' == dumps(data, cls=WidgetEncoder)
class TestWidgets(UnitTest):
def test_subredditwidgets_mod(self):
sw = SubredditWidgets(self.reddit.subreddit('fake_subreddit'))
assert isinstance(sw.mod, SubredditWidgetsModeration)
def test_widget_mod(self):
w = Widget(self.reddit, {})
assert isinstance(w.mod, WidgetModeration)
assert w.mod.widget == w
|
Test WidgetEncoder to get coverage to 100%
|
Test WidgetEncoder to get coverage to 100%
|
Python
|
bsd-2-clause
|
leviroth/praw,gschizas/praw,gschizas/praw,praw-dev/praw,13steinj/praw,praw-dev/praw,leviroth/praw,13steinj/praw
|
---
+++
@@ -1,7 +1,28 @@
+from json import dumps
+
from praw.models import (SubredditWidgets, SubredditWidgetsModeration,
Widget, WidgetModeration)
+from praw.models.reddit.widgets import WidgetEncoder
+from praw.models.base import PRAWBase
from ... import UnitTest
+
+
+class TestWidgetEncoder(UnitTest):
+ def test_bad_encode(self):
+ data = [1, 'two', SubredditWidgetsModeration(
+ self.reddit.subreddit('subreddit'), self.reddit)]
+ try:
+ dumps(data, cls=WidgetEncoder) # should throw TypeError
+ except TypeError:
+ pass # success
+ else:
+ assert False
+
+ def test_good_encode(self):
+ data = [1, 'two',
+ PRAWBase(self.reddit, _data={'_secret': 'no', '3': 3})]
+ assert '[1, "two", {"3": 3}]' == dumps(data, cls=WidgetEncoder)
class TestWidgets(UnitTest):
|
45381a1ce6e271cc06ce130cb35a93f14eceba90
|
troposphere/utils.py
|
troposphere/utils.py
|
import time
def _tail_print(e):
print("%s %s %s" % (e.resource_status, e.resource_type, e.event_id))
def get_events(conn, stackname):
"""Get the events in batches and return in chronological order"""
next = None
event_list = []
while 1:
events = conn.describe_stack_events(stackname, next)
event_list.append(events)
if events.next_token is None:
break
next = events.next_token
time.sleep(1)
return reversed(sum(event_list, []))
def tail(conn, stack_name, log_func=_tail_print, sleep_time=5):
"""Show and then tail the event log"""
# First dump the full list of events in chronological order and keep
# track of the events we've seen already
seen = set()
initial_events = get_events(conn, stack_name)
for e in initial_events:
log_func(e)
seen.add(e.event_id)
# Now keep looping through and dump the new events
while 1:
events = get_events(conn, stack_name)
for e in events:
if e.event_id not in seen:
log_func(e)
seen.add(e.event_id)
time.sleep(sleep_time)
|
import time
def _tail_print(e):
print("%s %s %s" % (e.resource_status, e.resource_type, e.event_id))
def get_events(conn, stackname):
"""Get the events in batches and return in chronological order"""
next = None
event_list = []
while 1:
events = conn.describe_stack_events(stackname, next)
event_list.append(events)
if events.next_token is None:
break
next = events.next_token
time.sleep(1)
return reversed(sum(event_list, []))
def tail(conn, stack_name, log_func=_tail_print, sleep_time=5, include_initial=True):
"""Show and then tail the event log"""
# First dump the full list of events in chronological order and keep
# track of the events we've seen already
seen = set()
initial_events = get_events(conn, stack_name)
for e in initial_events:
if include_initial:
log_func(e)
seen.add(e.event_id)
# Now keep looping through and dump the new events
while 1:
events = get_events(conn, stack_name)
for e in events:
if e.event_id not in seen:
log_func(e)
seen.add(e.event_id)
time.sleep(sleep_time)
|
Add "include_initial" kwarg to support tailing stack updates
|
Add "include_initial" kwarg to support tailing stack updates
`get_events` will return all events that have occurred for a stack. This
is useless if we're tailing an update to a stack.
|
Python
|
bsd-2-clause
|
mhahn/troposphere
|
---
+++
@@ -19,14 +19,15 @@
return reversed(sum(event_list, []))
-def tail(conn, stack_name, log_func=_tail_print, sleep_time=5):
+def tail(conn, stack_name, log_func=_tail_print, sleep_time=5, include_initial=True):
"""Show and then tail the event log"""
# First dump the full list of events in chronological order and keep
# track of the events we've seen already
seen = set()
initial_events = get_events(conn, stack_name)
for e in initial_events:
- log_func(e)
+ if include_initial:
+ log_func(e)
seen.add(e.event_id)
# Now keep looping through and dump the new events
|
783af65a5e417a1828105d390f7096066929a4b7
|
ipywidgets/widgets/widget_core.py
|
ipywidgets/widgets/widget_core.py
|
# Copyright (c) Jupyter Development Team.
# Distributed under the terms of the Modified BSD License.
"""Base widget class for widgets provided in Core"""
from .widget import Widget
from .._version import __jupyter_widget_version__
from traitlets import Unicode
class CoreWidget(Widget):
_model_module_version = Unicode(__jupyter_widget_version__).tag(sync=True)
_view_module_version = Unicode('*').tag(sync=True)
|
# Copyright (c) Jupyter Development Team.
# Distributed under the terms of the Modified BSD License.
"""Base widget class for widgets provided in Core"""
from .widget import Widget
from .._version import __jupyter_widget_version__
from traitlets import Unicode
class CoreWidget(Widget):
_model_module_version = Unicode(__jupyter_widget_version__).tag(sync=True)
_view_module_version = Unicode(__jupyter_widget_version__).tag(sync=True)
|
Revert the versioning back until the versioning discussion is settled.
|
Revert the versioning back until the versioning discussion is settled.
|
Python
|
bsd-3-clause
|
ipython/ipywidgets,SylvainCorlay/ipywidgets,ipython/ipywidgets,ipython/ipywidgets,jupyter-widgets/ipywidgets,jupyter-widgets/ipywidgets,SylvainCorlay/ipywidgets,jupyter-widgets/ipywidgets,ipython/ipywidgets,SylvainCorlay/ipywidgets,SylvainCorlay/ipywidgets,jupyter-widgets/ipywidgets,ipython/ipywidgets
|
---
+++
@@ -11,4 +11,4 @@
class CoreWidget(Widget):
_model_module_version = Unicode(__jupyter_widget_version__).tag(sync=True)
- _view_module_version = Unicode('*').tag(sync=True)
+ _view_module_version = Unicode(__jupyter_widget_version__).tag(sync=True)
|
d2ca395f44160272ba3cbe6d68a9c07c0e1cfa3d
|
flask_boilerplate/templates/+app_name+/__init__.py
|
flask_boilerplate/templates/+app_name+/__init__.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
from flask import Flask
from flask_debugtoolbar import DebugToolbarExtension
from .config import settings
def create_app(global_config, **local_conf):
app = Flask(__name__)
app.config.from_object(settings[local_conf['config_key']])
if app.debug:
DebugToolbarExtension(app)
from .views import main
app.register_blueprint(main)
return app
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
from flask import Flask
from flask_debugtoolbar import DebugToolbarExtension
from .config import settings
def create_app(global_config, **local_conf):
return _create_app(settings[local_conf['config_key']])
def _create_app(setting):
app = Flask(__name__)
app.config.from_object(setting)
if app.debug:
DebugToolbarExtension(app)
from .views import main
app.register_blueprint(main)
return app
|
Add internal function for test to set settings flexibly.
|
Add internal function for test to set settings flexibly.
|
Python
|
mit
|
FGtatsuro/flask-boilerplate,FGtatsuro/flask-boilerplate,FGtatsuro/flask-boilerplate
|
---
+++
@@ -9,9 +9,12 @@
from .config import settings
def create_app(global_config, **local_conf):
+ return _create_app(settings[local_conf['config_key']])
+
+def _create_app(setting):
app = Flask(__name__)
- app.config.from_object(settings[local_conf['config_key']])
+ app.config.from_object(setting)
if app.debug:
DebugToolbarExtension(app)
|
1a2e7fd402c9930dae75676b9aadaf5620ac87b9
|
setup.py
|
setup.py
|
from setuptools import setup
setup(
name="hashi",
packages=["hashi"],
version="0.0",
description="Web centric IRC client.",
author="Nell Hardcastle",
author_email="chizu@spicious.com",
install_requires=["pyzmq>=2.1.7",
"txzmq",
"txWebSocket",
"unicode_nazi",
"twisted"]
)
|
from setuptools import setup
setup(
name="hashi",
packages=["hashi"],
version="0.0",
description="Web centric IRC client.",
author="Nell Hardcastle",
author_email="chizu@spicious.com",
install_requires=["pyzmq>=2.1.7",
"txzmq",
"txWebSocket",
"twisted"]
)
|
Remove the unused unicode module.
|
Remove the unused unicode module.
|
Python
|
agpl-3.0
|
chizu/hashi,chizu/hashi
|
---
+++
@@ -9,6 +9,5 @@
install_requires=["pyzmq>=2.1.7",
"txzmq",
"txWebSocket",
- "unicode_nazi",
"twisted"]
)
|
9caec6eb24e43c3b3d403f4e7a49f3614ccf47c2
|
setup.py
|
setup.py
|
#!/usr/bin/env python
from setuptools import setup
setup(
name='Dapi',
version='1.0',
description='DevAssistant Package Index',
author='Miro Hroncok',
author_email='mhroncok@redhat.com',
url='https://github.com/hroncok/dapi',
license='AGPLv3',
install_requires=[
'Django==1.6',
'psycopg2',
'South',
'daploader>=0.0.4',
'PyYAML',
'python-social-auth',
'django-taggit',
'django-simple-captcha',
'django-haystack',
'whoosh',
'djangorestframework==03b4c60b',
'django-gravatar2',
],
dependency_links = [
'git+git://github.com/tomchristie/django-rest-framework.git@03b4c60b#egg=djangorestframework-03b4c60b',
]
)
|
#!/usr/bin/env python
from setuptools import setup
setup(
name='Dapi',
version='1.0',
description='DevAssistant Package Index',
author='Miro Hroncok',
author_email='mhroncok@redhat.com',
url='https://github.com/hroncok/dapi',
license='AGPLv3',
install_requires=[
'Django==1.6',
'psycopg2',
'South',
'daploader>=0.0.4',
'PyYAML',
'python-social-auth==c5dd3339',
'django-taggit',
'django-simple-captcha',
'django-haystack',
'whoosh',
'djangorestframework==03b4c60b',
'django-gravatar2',
],
dependency_links = [
'git+git://github.com/omab/python-social-auth.git@c5dd3339#egg=python-social-auth-c5dd3339',
'git+git://github.com/tomchristie/django-rest-framework.git@03b4c60b#egg=djangorestframework-03b4c60b',
]
)
|
USe git Python Social Auth to get Fedora nicknames
|
USe git Python Social Auth to get Fedora nicknames
|
Python
|
agpl-3.0
|
devassistant/dapi,devassistant/dapi,devassistant/dapi
|
---
+++
@@ -16,7 +16,7 @@
'South',
'daploader>=0.0.4',
'PyYAML',
- 'python-social-auth',
+ 'python-social-auth==c5dd3339',
'django-taggit',
'django-simple-captcha',
'django-haystack',
@@ -25,6 +25,7 @@
'django-gravatar2',
],
dependency_links = [
+ 'git+git://github.com/omab/python-social-auth.git@c5dd3339#egg=python-social-auth-c5dd3339',
'git+git://github.com/tomchristie/django-rest-framework.git@03b4c60b#egg=djangorestframework-03b4c60b',
]
)
|
f0ce157112428701eb04e084cf437097c57c68da
|
setup.py
|
setup.py
|
from setuptools import setup
setup( \
name='blendplot',
version='0.1.0',
description='A program for plotting 3D scatter plots for use in Blender',
long_description=open('README.md').read(),
url='https://github.com/ExcaliburZero/blender-astro-visualization',
author='Christopher Wells',
author_email='cwellsny@nycap.rr.com',
license='MIT',
packages=['blendplot'],
install_requires=[
'pyCLI',
'sklearn',
'scipy',
'pandas'
],
include_package_data=True,
package_data={
'': 'LICENSE'
},
classifiers=[
'Programming Language :: Python',
'Programming Language :: Python :: 3',
'Operating System :: OS Independent',
'Development Status :: 2 - Pre-Alpha',
'License :: OSI Approved :: MIT License'
],
entry_points = {
'console_scripts': [
'blendplot = blendplot.__main__:run',
],
},
)
|
from setuptools import setup
setup( \
name='blendplot',
version='0.1.0',
description='A program for plotting 3D scatter plots for use in Blender',
long_description=open('README.md').read(),
url='https://github.com/ExcaliburZero/blender-astro-visualization',
author='Christopher Wells',
author_email='cwellsny@nycap.rr.com',
license='MIT',
packages=['blendplot'],
install_requires=[
'pyCLI',
'sklearn',
'scipy',
'pandas'
],
include_package_data=True,
package_data={
'': ['LICENSE']
},
classifiers=[
'Programming Language :: Python',
'Programming Language :: Python :: 3',
'Operating System :: OS Independent',
'Development Status :: 2 - Pre-Alpha',
'License :: OSI Approved :: MIT License'
],
entry_points = {
'console_scripts': [
'blendplot = blendplot.__main__:run',
],
},
)
|
Change package_data to have LICENSE in a list
|
Change package_data to have LICENSE in a list
This is required by setuptools and as of a recent version fails if the
value(s) are not provided as a list or tuple of strings.
See: https://github.com/pypa/setuptools/commit/8f848bd777278fc8dcb42dc45751cd8b95ec2a02
|
Python
|
mit
|
ExcaliburZero/blender-astro-visualization
|
---
+++
@@ -18,7 +18,7 @@
],
include_package_data=True,
package_data={
- '': 'LICENSE'
+ '': ['LICENSE']
},
classifiers=[
|
e78099a5a18d7ae0f264a73c10fdf1422cc1d482
|
setup.py
|
setup.py
|
from setuptools import setup
setup(
name="arxiv",
version="0.2.2",
packages=["arxiv"],
# dependencies
install_requires=[
'feedparser',
'requests',
],
# metadata for upload to PyPI
author="Lukas Schwab",
author_email="lukas.schwab@gmail.com",
description="Python wrapper for the arXiv API: http://arxiv.org/help/api/",
license="MIT",
keywords="arxiv api wrapper academic journals papers",
url="https://github.com/lukasschwab/arxiv.py",
download_url="https://github.com/lukasschwab/arxiv.py/tarball/0.2.2",
)
|
from setuptools import setup
setup(
name="arxiv",
version="0.2.3",
packages=["arxiv"],
# dependencies
install_requires=[
'feedparser',
'requests',
],
# metadata for upload to PyPI
author="Lukas Schwab",
author_email="lukas.schwab@gmail.com",
description="Python wrapper for the arXiv API: http://arxiv.org/help/api/",
license="MIT",
keywords="arxiv api wrapper academic journals papers",
url="https://github.com/lukasschwab/arxiv.py",
download_url="https://github.com/lukasschwab/arxiv.py/tarball/0.2.3",
)
|
Increment to tag 0.2.3 for release
|
Increment to tag 0.2.3 for release
|
Python
|
mit
|
lukasschwab/arxiv.py
|
---
+++
@@ -2,7 +2,7 @@
setup(
name="arxiv",
- version="0.2.2",
+ version="0.2.3",
packages=["arxiv"],
# dependencies
@@ -18,5 +18,5 @@
license="MIT",
keywords="arxiv api wrapper academic journals papers",
url="https://github.com/lukasschwab/arxiv.py",
- download_url="https://github.com/lukasschwab/arxiv.py/tarball/0.2.2",
+ download_url="https://github.com/lukasschwab/arxiv.py/tarball/0.2.3",
)
|
37179d21380ec993ea858cec1e030bf7ee6a7b75
|
setup.py
|
setup.py
|
#!/usr/bin/env python
import glob
import os
from setuptools import setup, find_packages
setup(name='openmc',
version='0.6.2',
packages=find_packages(),
scripts=glob.glob('scripts/openmc-*'),
# Required dependencies
install_requires=['numpy', 'scipy', 'h5py', 'matplotlib'],
# Optional dependencies
extras_require={
'vtk': ['vtk', 'silomesh'],
'validate': ['lxml'],
},
# Metadata
author='Will Boyd',
author_email='wbinventor@gmail.com',
description='OpenMC Python API',
url='https://github.com/mit-crpg/openmc',
classifiers=[
'Intended Audience :: Developers',
'Intended Audience :: End Users/Desktop',
'Intended Audience :: Science/Research',
'License :: OSI Approved :: MIT License',
'Natural Language :: English',
'Programming Language :: Python',
'Topic :: Scientific/Engineering'
]
)
|
#!/usr/bin/env python
import glob
import os
from setuptools import setup, find_packages
setup(name='openmc',
version='0.6.2',
packages=find_packages(),
scripts=glob.glob('scripts/openmc-*'),
# Required dependencies
install_requires=['numpy', 'scipy', 'h5py', 'matplotlib'],
# Optional dependencies
extras_require={
'pandas': ['pandas'],
'vtk': ['vtk', 'silomesh'],
'validate': ['lxml']
},
# Metadata
author='Will Boyd',
author_email='wbinventor@gmail.com',
description='OpenMC Python API',
url='https://github.com/mit-crpg/openmc',
classifiers=[
'Intended Audience :: Developers',
'Intended Audience :: End Users/Desktop',
'Intended Audience :: Science/Research',
'License :: OSI Approved :: MIT License',
'Natural Language :: English',
'Programming Language :: Python',
'Topic :: Scientific/Engineering'
]
)
|
Add pandas as an optional dependency
|
Add pandas as an optional dependency
|
Python
|
mit
|
mit-crpg/openmc,bhermanmit/openmc,amandalund/openmc,amandalund/openmc,walshjon/openmc,samuelshaner/openmc,bhermanmit/openmc,wbinventor/openmc,shikhar413/openmc,kellyrowland/openmc,walshjon/openmc,walshjon/openmc,wbinventor/openmc,shikhar413/openmc,paulromano/openmc,johnnyliu27/openmc,wbinventor/openmc,johnnyliu27/openmc,samuelshaner/openmc,kellyrowland/openmc,smharper/openmc,paulromano/openmc,samuelshaner/openmc,smharper/openmc,liangjg/openmc,mjlong/openmc,samuelshaner/openmc,mjlong/openmc,amandalund/openmc,shikhar413/openmc,amandalund/openmc,mit-crpg/openmc,wbinventor/openmc,smharper/openmc,lilulu/openmc,liangjg/openmc,johnnyliu27/openmc,smharper/openmc,walshjon/openmc,lilulu/openmc,mit-crpg/openmc,lilulu/openmc,liangjg/openmc,shikhar413/openmc,paulromano/openmc,mit-crpg/openmc,paulromano/openmc,johnnyliu27/openmc,liangjg/openmc
|
---
+++
@@ -14,8 +14,9 @@
# Optional dependencies
extras_require={
+ 'pandas': ['pandas'],
'vtk': ['vtk', 'silomesh'],
- 'validate': ['lxml'],
+ 'validate': ['lxml']
},
# Metadata
|
e72107f53e4519f16d556b15405b7f7223e0bfae
|
setup.py
|
setup.py
|
import distutils.core
# Uploading to PyPI
# =================
# $ python setup.py register -r pypi
# $ python setup.py sdist upload -r pypi
version = '0.0'
distutils.core.setup(
name='kxg',
version=version,
author='Kale Kundert and Alex Mitchell',
url='https://github.com/kxgames/GameEngine',
download_url='https://github.com/kxgames/GameEngine/tarball/'+version,
license='LICENSE.txt',
description="A multiplayer game engine.",
long_description=open('README.rst').read(),
keywords=['game', 'network', 'gui', 'pyglet'],
packages=['kxg'],
install_requires=[
'pyglet',
'nonstdlib',
'linersock',
'pytest',
],
)
|
import distutils.core
# Uploading to PyPI
# =================
# $ python setup.py register -r pypi
# $ python setup.py sdist upload -r pypi
version = '0.0'
distutils.core.setup(
name='kxg',
version=version,
author='Kale Kundert and Alex Mitchell',
url='https://github.com/kxgames/GameEngine',
download_url='https://github.com/kxgames/GameEngine/tarball/'+version,
license='LICENSE.txt',
description="A multiplayer game engine.",
long_description=open('README.rst').read(),
keywords=['game', 'network', 'gui', 'pyglet'],
packages=['kxg'],
install_requires=[
'pyglet',
'nonstdlib',
'linersock',
'pytest',
'docopt',
],
)
|
Add docopt as a dependency.
|
Add docopt as a dependency.
|
Python
|
mit
|
kxgames/kxg
|
---
+++
@@ -22,5 +22,6 @@
'nonstdlib',
'linersock',
'pytest',
+ 'docopt',
],
)
|
7c424d7eb26712e84be67b2fb5921810f8f042a6
|
kboard/functional_test/test_registration_form.py
|
kboard/functional_test/test_registration_form.py
|
from .base import FunctionalTest
import time
class RegistrationFormTest(FunctionalTest):
def test_two_passwords_are_correct(self):
# 혜선이는 회원가입을 하고싶어한다.
self.browser.get(self.live_server_url + '/accounts/register/')
# 가입에 필요한 정보를 작성한다.
usernamebox = self.browser.find_element_by_id("id_username")
usernamebox.send_keys("chickenlover01")
emailbox = self.browser.find_element_by_id("id_email")
emailbox.send_keys("chsun0303@naver.com")
password1box = self.browser.find_element_by_id("id_password1")
password1box.send_keys("abcd0000")
# 손이 미끄러져서 똑같은 비밀번호를 치지못했다.
password2box = self.browser.find_element_by_id("id_password2")
password2box.send_keys("abcd0009")
checkbox = self.browser.find_element_by_id("agree")
checkbox.click()
# 회원가입약관이 마음에 안들어서 체크를 하지 않고 가입을 진행한다.
self.click_submit_button()
# Password 아래 쪽에 두 비밀번호가 같지않다고 에러메시지가 나온다.
error = self.browser.find_element_by_class_name("errorlist")
self.assertTrue("The two password fields didn't match.", error)
|
Add functional test for both password are the same
|
Add functional test for both password are the same
|
Python
|
mit
|
cjh5414/kboard,kboard/kboard,hyesun03/k-board,hyesun03/k-board,kboard/kboard,cjh5414/kboard,hyesun03/k-board,guswnsxodlf/k-board,kboard/kboard,guswnsxodlf/k-board,cjh5414/kboard,guswnsxodlf/k-board,darjeeling/k-board
|
---
+++
@@ -0,0 +1,31 @@
+from .base import FunctionalTest
+
+import time
+class RegistrationFormTest(FunctionalTest):
+ def test_two_passwords_are_correct(self):
+ # 혜선이는 회원가입을 하고싶어한다.
+ self.browser.get(self.live_server_url + '/accounts/register/')
+
+ # 가입에 필요한 정보를 작성한다.
+ usernamebox = self.browser.find_element_by_id("id_username")
+ usernamebox.send_keys("chickenlover01")
+
+ emailbox = self.browser.find_element_by_id("id_email")
+ emailbox.send_keys("chsun0303@naver.com")
+
+ password1box = self.browser.find_element_by_id("id_password1")
+ password1box.send_keys("abcd0000")
+
+ # 손이 미끄러져서 똑같은 비밀번호를 치지못했다.
+ password2box = self.browser.find_element_by_id("id_password2")
+ password2box.send_keys("abcd0009")
+
+ checkbox = self.browser.find_element_by_id("agree")
+ checkbox.click()
+
+ # 회원가입약관이 마음에 안들어서 체크를 하지 않고 가입을 진행한다.
+ self.click_submit_button()
+
+ # Password 아래 쪽에 두 비밀번호가 같지않다고 에러메시지가 나온다.
+ error = self.browser.find_element_by_class_name("errorlist")
+ self.assertTrue("The two password fields didn't match.", error)
|
|
8dc3eb814bd486951a4efe53d27999da2bd940e2
|
setup.py
|
setup.py
|
from setuptools import setup, find_packages
import sys
import os.path
import numpy as np
# Must be one line or PyPI will cut it off
DESC = ("A powerful, accurate, and easy-to-use Python library for "
"doing colorspace conversions")
LONG_DESC = open("README.rst").read()
# defines __version__
exec(open("colorspacious/version.py").read())
setup(
name="colorspacious",
version=__version__,
description=DESC,
long_description=LONG_DESC,
author="Nathaniel J. Smith",
author_email="njs@pobox.com",
url="https://github.com/njsmith/colorspacious",
license="MIT",
classifiers =
[ "Development Status :: 4 - Beta",
"Intended Audience :: Developers",
"Intended Audience :: Science/Research",
"License :: OSI Approved :: MIT License",
"Programming Language :: Python :: 2",
"Programming Language :: Python :: 3",
],
packages=find_packages(),
install_requires=["numpy"],
)
|
from setuptools import setup, find_packages
import sys
import os.path
import numpy as np
# Must be one line or PyPI will cut it off
DESC = ("A powerful, accurate, and easy-to-use Python library for "
"doing colorspace conversions")
import codecs
LONG_DESC = codecs.open("README.rst", encoding="utf-8").read()
# defines __version__
exec(open("colorspacious/version.py").read())
setup(
name="colorspacious",
version=__version__,
description=DESC,
long_description=LONG_DESC,
author="Nathaniel J. Smith",
author_email="njs@pobox.com",
url="https://github.com/njsmith/colorspacious",
license="MIT",
classifiers =
[ "Development Status :: 4 - Beta",
"Intended Audience :: Developers",
"Intended Audience :: Science/Research",
"License :: OSI Approved :: MIT License",
"Programming Language :: Python :: 2",
"Programming Language :: Python :: 3",
],
packages=find_packages(),
install_requires=["numpy"],
)
|
Use codecs.open for py2/py3-compatible utf8 reading
|
Use codecs.open for py2/py3-compatible utf8 reading
Fixes gh-6
|
Python
|
mit
|
njsmith/colorspacious
|
---
+++
@@ -8,7 +8,8 @@
DESC = ("A powerful, accurate, and easy-to-use Python library for "
"doing colorspace conversions")
-LONG_DESC = open("README.rst").read()
+import codecs
+LONG_DESC = codecs.open("README.rst", encoding="utf-8").read()
# defines __version__
exec(open("colorspacious/version.py").read())
|
b59efc07aed61880f29da88c095a2d9c13a145e4
|
setup.py
|
setup.py
|
from setuptools import setup
from setuptools.extension import Extension
from Cython.Build import cythonize
extensions = [
Extension("smartquadtree",
["smartquadtree.pyx", "quadtree.cpp", "neighbour.cpp"],
extra_compile_args=["-std=c++11"],
language="c++")
]
def get_long_description():
import codecs
with codecs.open('tutorial.rst', encoding='utf-8') as f:
readme = f.read()
return readme
setup(name="smartquadtree",
version="1.0",
author="Xavier Olive",
author_email="xavier@xoolive.org",
description="Implementation of quadtrees for moving objects",
long_description=get_long_description(),
license="MIT",
url="https://github.com/xoolive/quadtree",
ext_modules=cythonize(extensions),
)
# Producing long description
# ipython nbconvert tutorial.ipynb --to rst
# Then manually edit paths to images to point to github
|
from setuptools import setup
from setuptools.extension import Extension
from Cython.Build import cythonize
extensions = [
Extension("smartquadtree",
["smartquadtree.pyx", "quadtree.cpp", "neighbour.cpp"],
extra_compile_args=["-std=c++11"],
language="c++")
]
def get_long_description():
import codecs
with codecs.open('tutorial.rst', encoding='utf-8') as f:
readme = f.read()
return readme
setup(name="smartquadtree",
version="1.0",
author="Xavier Olive",
author_email="xavier@xoolive.org",
description="Implementation of quadtrees for moving objects",
long_description=get_long_description(),
license="MIT",
url="https://github.com/xoolive/quadtree",
ext_modules=cythonize(extensions),
)
# Producing long description
# ipython nbconvert tutorial.ipynb --to rst
# Then manually edit paths to images to point to github
# Windows compilation (mingw)
# edit smartquadtree.cpp
# add #include <cmath> at the top of the file before #include "pyconfig.h"
|
Add comments for Windows mingw compilation
|
Add comments for Windows mingw compilation
|
Python
|
mit
|
xoolive/quadtree,xoolive/quadtree
|
---
+++
@@ -29,3 +29,7 @@
# Producing long description
# ipython nbconvert tutorial.ipynb --to rst
# Then manually edit paths to images to point to github
+
+# Windows compilation (mingw)
+# edit smartquadtree.cpp
+# add #include <cmath> at the top of the file before #include "pyconfig.h"
|
f4c30dbd717a6c7a04a645a2721a1c34936739a1
|
setup.py
|
setup.py
|
from setuptools import setup, find_packages
setup(
name='icecake',
version='0.1.0',
py_modules=['icecake'],
url="https://github.com/cbednarski/icecake",
author="Chris Bednarski",
author_email="banzaimonkey@gmail.com",
description="An easy and cool static site generator",
license="MIT",
install_requires=[
'Click',
'Jinja2',
'Markdown',
'Pygments',
'python-dateutil',
'Werkzeug',
],
entry_points='''
[console_scripts]
icecake=icecake:cli
''',
keywords="static site generator builder icecake"
)
|
from setuptools import setup, find_packages
setup(
name='icecake',
version='0.2.0',
py_modules=['icecake', 'templates'],
url="https://github.com/cbednarski/icecake",
author="Chris Bednarski",
author_email="banzaimonkey@gmail.com",
description="An easy and cool static site generator",
license="MIT",
install_requires=[
'Click',
'Jinja2',
'Markdown',
'Pygments',
'python-dateutil',
'Werkzeug',
],
entry_points='''
[console_scripts]
icecake=icecake:cli
''',
keywords="static site generator builder icecake"
)
|
Add templates, bump version number
|
Add templates, bump version number
|
Python
|
mit
|
cbednarski/icecake,cbednarski/icecake
|
---
+++
@@ -2,8 +2,8 @@
setup(
name='icecake',
- version='0.1.0',
- py_modules=['icecake'],
+ version='0.2.0',
+ py_modules=['icecake', 'templates'],
url="https://github.com/cbednarski/icecake",
author="Chris Bednarski",
author_email="banzaimonkey@gmail.com",
|
b74a1065928514846deb7211541007d4fc45593d
|
setup.py
|
setup.py
|
try:
from setuptools import setup, find_packages
except ImportError:
from distutils.core import setup
import os
import sys
import unittest
import os.path
import platform
sys.path.append('jubatus')
sys.path.append('test')
def read(name):
return open(os.path.join(os.path.dirname(__file__), name)).read()
setup(name='jubatus',
version=read('VERSION').rstrip(),
description='Jubatus is a distributed processing framework and streaming machine learning library. This is the Jubatus client in Python.',
long_description=read('README.rst'),
author='PFI & NTT',
author_email='jubatus@googlegroups.com',
url='http://jubat.us',
download_url='http://pypi.python.org/pypi/jubatus/',
license='MIT License',
platforms='Linux',
packages=find_packages(exclude=['test']),
install_requires=[
'msgpack-rpc-python>=0.3.0'
],
entry_points="",
ext_modules=[],
classifiers=[
'Development Status :: 2 - Pre-Alpha',
'Environment :: Other Environment',
'Intended Audience :: Developers',
'Intended Audience :: Science/Research',
'License :: OSI Approved :: MIT License',
'Operating System :: POSIX :: Linux',
'Programming Language :: Python',
'Topic :: Scientific/Engineering :: Information Analysis'
],
test_suite='jubatus_test',
)
|
try:
from setuptools import setup, find_packages
except ImportError:
from distutils.core import setup
import os
import sys
import unittest
import os.path
import platform
sys.path.append('jubatus')
sys.path.append('test')
def read(name):
return open(os.path.join(os.path.dirname(__file__), name)).read()
setup(name='jubatus',
version=read('VERSION').rstrip(),
description='Jubatus is a distributed processing framework and streaming machine learning library. This is the Jubatus client in Python.',
long_description=read('README.rst'),
author='PFN & NTT',
author_email='jubatus@googlegroups.com',
url='http://jubat.us',
download_url='http://pypi.python.org/pypi/jubatus/',
license='MIT License',
platforms='Linux',
packages=find_packages(exclude=['test']),
install_requires=[
'msgpack-rpc-python>=0.3.0'
],
entry_points="",
ext_modules=[],
classifiers=[
'Development Status :: 2 - Pre-Alpha',
'Environment :: Other Environment',
'Intended Audience :: Developers',
'Intended Audience :: Science/Research',
'License :: OSI Approved :: MIT License',
'Operating System :: POSIX :: Linux',
'Programming Language :: Python',
'Topic :: Scientific/Engineering :: Information Analysis'
],
test_suite='jubatus_test',
)
|
Replace PFI with PFN in copyright notice.
|
Replace PFI with PFN in copyright notice.
|
Python
|
mit
|
hirokiky/jubatus-python-client,jubatus/jubatus-python-client,jubatus/jubatus-python-client,hirokiky/jubatus-python-client
|
---
+++
@@ -19,7 +19,7 @@
version=read('VERSION').rstrip(),
description='Jubatus is a distributed processing framework and streaming machine learning library. This is the Jubatus client in Python.',
long_description=read('README.rst'),
- author='PFI & NTT',
+ author='PFN & NTT',
author_email='jubatus@googlegroups.com',
url='http://jubat.us',
download_url='http://pypi.python.org/pypi/jubatus/',
|
9571d0cf946163c8ca9c01aae3334feebf0a4276
|
setup.py
|
setup.py
|
#!/usr/bin/env python
from __future__ import print_function
from codecs import open
from setuptools import setup
setup(name="abzer",
author="Wieland Hoffmann",
author_email="themineo@gmail.com",
packages=["abzer"],
package_dir={"abzer": "abzer"},
download_url=["https://github.com/mineo/abzer/tarball/master"],
url=["http://github.com/mineo/abzer"],
license="MIT",
classifiers=["Development Status :: 4 - Beta",
"License :: OSI Approved :: MIT License",
"Natural Language :: English",
"Operating System :: OS Independent",
"Programming Language :: Python :: 3.5"],
description="AcousticBrainz submission tool",
long_description=open("README.txt", encoding="utf-8").read(),
setup_requires=["setuptools_scm"],
use_scm_version={"write_to": "abzer/version.py"},
install_requires=["aiohttp"],
extras_require={
'docs': ['sphinx', 'sphinxcontrib-autoprogram']},
python_requires='>=3.5',
entry_points={
'console_scripts': ['abzer=abzer.__main__:main']
}
)
|
#!/usr/bin/env python
from __future__ import print_function
from codecs import open
from setuptools import setup
setup(name="abzer",
author="Wieland Hoffmann",
author_email="themineo@gmail.com",
packages=["abzer"],
package_dir={"abzer": "abzer"},
download_url=["https://github.com/mineo/abzer/tarball/master"],
url=["https://github.com/mineo/abzer"],
license="MIT",
classifiers=["Development Status :: 4 - Beta",
"License :: OSI Approved :: MIT License",
"Natural Language :: English",
"Operating System :: OS Independent",
"Programming Language :: Python :: 3.5"],
description="AcousticBrainz submission tool",
long_description=open("README.txt", encoding="utf-8").read(),
setup_requires=["setuptools_scm"],
use_scm_version={"write_to": "abzer/version.py"},
install_requires=["aiohttp"],
extras_require={
'docs': ['sphinx', 'sphinxcontrib-autoprogram']},
python_requires='>=3.5',
entry_points={
'console_scripts': ['abzer=abzer.__main__:main']
}
)
|
Use HTTPS for GitHub URLs
|
Use HTTPS for GitHub URLs
|
Python
|
mit
|
mineo/abzer,mineo/abzer
|
---
+++
@@ -10,7 +10,7 @@
packages=["abzer"],
package_dir={"abzer": "abzer"},
download_url=["https://github.com/mineo/abzer/tarball/master"],
- url=["http://github.com/mineo/abzer"],
+ url=["https://github.com/mineo/abzer"],
license="MIT",
classifiers=["Development Status :: 4 - Beta",
"License :: OSI Approved :: MIT License",
|
28b261e1f9af635fd2355085303d67991856584f
|
mathdeck/settings.py
|
mathdeck/settings.py
|
# -*- coding: utf-8 -*-
"""
mathdeck.settings
~~~~~~~~~~~~~~~~~
This module accesses the settings file located at
/etc/mathdeck/mathdeckconf.json
:copyright: (c) 2015 by Patrick Spencer.
:license: Apache 2.0, see ../LICENSE for more details.
"""
import json
import os
# Make this a class so we can pass conf_dir value. We want this so
# testings is easier.
class ProblemLibs:
def __init__(self,conf_dir=os.path.expanduser('~')):
self.conf_dir = conf_dir
@classmethod
def get_dir(cls):
with open('/etc/mathdeck/mathdeckconf.json') as file:
data = json.load(file)
return data['prob_lib_dir']
|
# -*- coding: utf-8 -*-
"""
mathdeck.settings
~~~~~~~~~~~~~~~~~
This module accesses the settings file located at
/etc/mathdeck/mathdeckconf.json
:copyright: (c) 2014-2016 by Patrick Spencer.
:license: Apache 2.0, see ../LICENSE for more details.
"""
import json
import os
# Make this a class so we can pass conf_dir value. We want this so
# testings is easier.
class ProblemLibs:
"""
By default, mathdeck looks for the settings file in
/etc/mathdeck/mathdeckconf.json. We can change where get_dir() looks
for the settings file in tests
"""
default_file = '/etc/mathdeck/mathdeckconf.json'
default_lib_name ='main_lib'
def __init__(self):
pass
@classmethod
def get_dir(cls, settings_file = default_file, lib_name = default_lib_name):
with open(settings_file) as file:
data = json.load(file)
return data["problem_libs"][lib_name]
|
Fix problem file importing bug
|
Fix problem file importing bug
|
Python
|
apache-2.0
|
patrickspencer/mathdeck,patrickspencer/mathdeck
|
---
+++
@@ -7,7 +7,7 @@
This module accesses the settings file located at
/etc/mathdeck/mathdeckconf.json
-:copyright: (c) 2015 by Patrick Spencer.
+:copyright: (c) 2014-2016 by Patrick Spencer.
:license: Apache 2.0, see ../LICENSE for more details.
"""
@@ -19,12 +19,20 @@
# testings is easier.
class ProblemLibs:
- def __init__(self,conf_dir=os.path.expanduser('~')):
- self.conf_dir = conf_dir
+ """
+ By default, mathdeck looks for the settings file in
+ /etc/mathdeck/mathdeckconf.json. We can change where get_dir() looks
+ for the settings file in tests
+ """
+ default_file = '/etc/mathdeck/mathdeckconf.json'
+ default_lib_name ='main_lib'
+
+ def __init__(self):
+ pass
@classmethod
- def get_dir(cls):
- with open('/etc/mathdeck/mathdeckconf.json') as file:
+ def get_dir(cls, settings_file = default_file, lib_name = default_lib_name):
+ with open(settings_file) as file:
data = json.load(file)
- return data['prob_lib_dir']
+ return data["problem_libs"][lib_name]
|
dd3ea448dee1cc77069244d9d1151e8ee07147bc
|
setup.py
|
setup.py
|
#!/usr/bin/env python
from setuptools import setup, find_packages
setup(
name='Flask-RESTful',
version='0.2.1',
url='https://www.github.com/twilio/flask-restful/',
author='Kyle Conroy',
author_email='help@twilio.com',
description='Simple framework for creating REST APIs',
packages=find_packages(),
zip_safe=False,
include_package_data=True,
platforms='any',
test_suite = 'nose.collector',
setup_requires=[
'nose>=1.1.2',
'mock>=0.8',
'blinker==1.2',
],
install_requires=[
'Flask>=0.8',
'pycrypto>=2.6',
]
)
|
#!/usr/bin/env python
from setuptools import setup, find_packages
setup(
name='Flask-RESTful',
version='0.2.1',
url='https://www.github.com/twilio/flask-restful/',
author='Kyle Conroy',
author_email='help@twilio.com',
description='Simple framework for creating REST APIs',
packages=find_packages(),
zip_safe=False,
include_package_data=True,
platforms='any',
test_suite = 'nose.collector',
setup_requires=[
'nose>=1.1.2',
'mock>=0.8',
'blinker==1.2',
],
install_requires=[
'Flask>=0.8',
],
extras_require={
'paging': 'pycrypto>=2.6',
}
)
|
Add pycrypto to optional module
|
Add pycrypto to optional module
It's not used by core code at the moment
|
Python
|
bsd-3-clause
|
elatomo/flask-restful,frol/flask-restful,santtu/flask-restful,FashtimeDotCom/flask-restful,ankravch/flask-restful,expobrain/flask-restful,codephillip/flask-restful,marrybird/flask-restful,mackjoner/flask-restful,sergeyromanov/flask-restful,ihiji/flask-restful,liangmingjie/flask-restful,samarthmshah/flask-restful,Khan/flask-restful,whitekid/flask-restful,ueg1990/flask-restful,flask-restful/flask-restful,red3/flask-restful,CanalTP/flask-restful,gonboy/flask-restful,justanr/flask-restful,mitchfriedman/flask-restful
|
---
+++
@@ -21,6 +21,8 @@
],
install_requires=[
'Flask>=0.8',
- 'pycrypto>=2.6',
- ]
+ ],
+ extras_require={
+ 'paging': 'pycrypto>=2.6',
+ }
)
|
c07013887a105a3adf0a6f1aa9d09357450cba46
|
tools/fontbakery-build-metadata.py
|
tools/fontbakery-build-metadata.py
|
import sys
from bakery_cli.scripts import genmetadata
def main(argv=None):
if argv is None:
argv = sys.argv
if len(argv) != 2:
genmetadata.usage()
return 1
genmetadata.run(argv[1])
return 0
if __name__ == '__main__':
sys.exit(main())
|
#!/usr/bin/env python
# coding: utf-8
# Copyright 2013 The Font Bakery 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.
#
# See AUTHORS.txt for the list of Authors and LICENSE.txt for the License.
import sys
from bakery_cli.scripts import genmetadata
def main(argv=None):
if argv is None:
argv = sys.argv
if len(argv) != 2:
genmetadata.usage()
return 1
genmetadata.run(argv[1])
return 0
if __name__ == '__main__':
sys.exit(main())
|
Add license and shebang to build-metadata.py
|
Add license and shebang to build-metadata.py
|
Python
|
apache-2.0
|
googlefonts/fontbakery,googlefonts/fontbakery,graphicore/fontbakery,moyogo/fontbakery,graphicore/fontbakery,graphicore/fontbakery,davelab6/fontbakery,moyogo/fontbakery,moyogo/fontbakery,googlefonts/fontbakery,jessamynsmith/fontbakery
|
---
+++
@@ -1,3 +1,20 @@
+#!/usr/bin/env python
+# coding: utf-8
+# Copyright 2013 The Font Bakery 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.
+#
+# See AUTHORS.txt for the list of Authors and LICENSE.txt for the License.
import sys
from bakery_cli.scripts import genmetadata
|
268e10a066655f88da5b1da82ac2cfd9b6e7e03f
|
setup.py
|
setup.py
|
"""
Flask-Autodoc
-------------
Flask autodoc automatically creates an online documentation for your flask application.
"""
from setuptools import setup
setup(
name='Flask-Autodoc',
version='0.1',
url='http://github.com/acoomans/flask-autodoc',
license='MIT',
author='Arnaud Coomans',
author_email='arnaud.coomans@gmail.com',
description='Documentation generator for flask',
long_description=__doc__,
#py_modules=['flask_autodoc'],
# if you would be using a package instead use packages instead
# of py_modules:
packages=['flask_autodoc'],
package_data={'flask_autodoc': ['templates/autodoc_default.html']},
zip_safe=False,
include_package_data=True,
platforms='any',
install_requires=[
'Flask'
],
classifiers=[
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
'Topic :: Software Development :: Libraries :: Python Modules'
],
test_suite = 'tests.test_autodoc',
)
|
"""
Flask-Autodoc
-------------
Flask autodoc automatically creates an online documentation for your flask application.
"""
from setuptools import setup
def readme():
with open('README') as f:
return f.read()
setup(
name='Flask-Autodoc',
version='0.1',
url='http://github.com/acoomans/flask-autodoc',
license='MIT',
author='Arnaud Coomans',
author_email='arnaud.coomans@gmail.com',
description='Documentation generator for flask',
long_description=readme(),
#py_modules=['flask_autodoc'],
# if you would be using a package instead use packages instead
# of py_modules:
packages=['flask_autodoc'],
package_data={'flask_autodoc': ['templates/autodoc_default.html']},
zip_safe=False,
include_package_data=True,
platforms='any',
install_requires=[
'Flask'
],
classifiers=[
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Topic :: Internet :: WWW/HTTP :: Dynamic Content',
'Topic :: Software Development :: Libraries :: Python Modules'
],
test_suite = 'tests.test_autodoc',
)
|
Include README as long description
|
Include README as long description
|
Python
|
mit
|
lukeyeager/flask-autodoc,jwg4/flask-autodoc,acoomans/flask-autodoc,BallisticBuddha/flask-autodoc,jwg4/flask-autodoc,lukeyeager/flask-autodoc,acoomans/flask-autodoc
|
---
+++
@@ -5,6 +5,10 @@
Flask autodoc automatically creates an online documentation for your flask application.
"""
from setuptools import setup
+
+def readme():
+ with open('README') as f:
+ return f.read()
setup(
@@ -15,7 +19,7 @@
author='Arnaud Coomans',
author_email='arnaud.coomans@gmail.com',
description='Documentation generator for flask',
- long_description=__doc__,
+ long_description=readme(),
#py_modules=['flask_autodoc'],
# if you would be using a package instead use packages instead
# of py_modules:
|
0fbbfcbe69eba31709862bf9372a3a77fcc3dde9
|
setup.py
|
setup.py
|
from setuptools import setup, find_packages
import os.path
import re
package_name = 'sqlalchemy_dict'
# reading package's version (same way sqlalchemy does)
with open(os.path.join(os.path.dirname(__file__), package_name, '__init__.py')) as v_file:
package_version = re.compile(r".*__version__ = '(.*?)'", re.S).match(v_file.read()).group(1)
dependencies = [
'sqlalchemy'
]
setup(
name=package_name,
version=package_version,
author='Mahdi Ghane.g',
description='sqlalchemy extension for interacting models with python dictionary.',
long_description=open('README.rst').read(),
url='https://github.com/meyt/sqlalchemy-dict',
packages=find_packages(),
install_requires=dependencies,
license='MIT License',
classifiers=[
'Development Status :: 3 - Alpha',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Operating System :: OS Independent',
'Topic :: Software Development :: Libraries',
]
)
|
from setuptools import setup, find_packages
import os.path
import re
import sys
package_name = 'sqlalchemy_dict'
py_version = sys.version_info[:2]
# reading package's version (same way sqlalchemy does)
with open(os.path.join(os.path.dirname(__file__), package_name, '__init__.py')) as v_file:
package_version = re.compile(r".*__version__ = '(.*?)'", re.S).match(v_file.read()).group(1)
dependencies = [
'sqlalchemy'
]
if py_version < (3, 5):
dependencies.append('typing')
setup(
name=package_name,
version=package_version,
author='Mahdi Ghane.g',
description='sqlalchemy extension for interacting models with python dictionary.',
long_description=open('README.rst').read(),
url='https://github.com/meyt/sqlalchemy-dict',
packages=find_packages(),
install_requires=dependencies,
license='MIT License',
classifiers=[
'Development Status :: 3 - Alpha',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Programming Language :: Python :: 3.5',
'Programming Language :: Python :: 3.6',
'Operating System :: OS Independent',
'Topic :: Software Development :: Libraries',
]
)
|
Add typing module as dependencies for python versions older than 3.5
|
Add typing module as dependencies
for python versions older than 3.5
|
Python
|
mit
|
meyt/sqlalchemy-dict
|
---
+++
@@ -1,8 +1,10 @@
from setuptools import setup, find_packages
import os.path
import re
+import sys
package_name = 'sqlalchemy_dict'
+py_version = sys.version_info[:2]
# reading package's version (same way sqlalchemy does)
with open(os.path.join(os.path.dirname(__file__), package_name, '__init__.py')) as v_file:
@@ -11,6 +13,9 @@
dependencies = [
'sqlalchemy'
]
+
+if py_version < (3, 5):
+ dependencies.append('typing')
setup(
name=package_name,
|
27e67076d4a2cfe68ab3a9113bb37344b35b3c90
|
scipy_base/__init__.py
|
scipy_base/__init__.py
|
from info_scipy_base import __doc__
from scipy_base_version import scipy_base_version as __version__
from ppimport import ppimport, ppimport_attr
# The following statement is equivalent to
#
# from Matrix import Matrix as mat
#
# but avoids expensive LinearAlgebra import when
# Matrix is not used.
mat = ppimport_attr(ppimport('Matrix'), 'Matrix')
# Force Numeric to use scipy_base.fastumath instead of Numeric.umath.
import fastumath # no need to use scipy_base.fastumath
import sys as _sys
_sys.modules['umath'] = fastumath
import Numeric
from Numeric import *
import limits
from type_check import *
from index_tricks import *
from function_base import *
from shape_base import *
from matrix_base import *
from polynomial import *
from scimath import *
from machar import *
from pexec import *
Inf = inf = fastumath.PINF
try:
NAN = NaN = nan = fastumath.NAN
except AttributeError:
NaN = NAN = nan = fastumath.PINF/fastumath.PINF
from scipy_test.testing import ScipyTest
test = ScipyTest('scipy_base').test
if _sys.modules.has_key('scipy_base.Matrix') \
and _sys.modules['scipy_base.Matrix'] is None:
del _sys.modules['scipy_base.Matrix']
|
from info_scipy_base import __doc__
from scipy_base_version import scipy_base_version as __version__
from ppimport import ppimport, ppimport_attr
# The following statement is equivalent to
#
# from Matrix import Matrix as mat
#
# but avoids expensive LinearAlgebra import when
# Matrix is not used.
mat = ppimport_attr(ppimport('Matrix'), 'Matrix')
# Force Numeric to use scipy_base.fastumath instead of Numeric.umath.
import fastumath # no need to use scipy_base.fastumath
import sys as _sys
_sys.modules['umath'] = fastumath
import Numeric
from Numeric import *
import limits
from type_check import *
from index_tricks import *
from function_base import *
from shape_base import *
from matrix_base import *
from polynomial import *
from scimath import *
from machar import *
from pexec import *
if Numeric.__version__ < '23.5':
matrixmultiply=dot
Inf = inf = fastumath.PINF
try:
NAN = NaN = nan = fastumath.NAN
except AttributeError:
NaN = NAN = nan = fastumath.PINF/fastumath.PINF
from scipy_test.testing import ScipyTest
test = ScipyTest('scipy_base').test
if _sys.modules.has_key('scipy_base.Matrix') \
and _sys.modules['scipy_base.Matrix'] is None:
del _sys.modules['scipy_base.Matrix']
|
Fix for matrixmultiply != dot on Numeric < 23.4
|
Fix for matrixmultiply != dot on Numeric < 23.4
git-svn-id: 77a43f9646713b91fea7788fad5dfbf67e151ece@857 94b884b6-d6fd-0310-90d3-974f1d3f35e1
|
Python
|
bsd-3-clause
|
illume/numpy3k,chadnetzer/numpy-gaurdro,jasonmccampbell/numpy-refactor-sprint,efiring/numpy-work,Ademan/NumPy-GSoC,illume/numpy3k,Ademan/NumPy-GSoC,teoliphant/numpy-refactor,teoliphant/numpy-refactor,illume/numpy3k,Ademan/NumPy-GSoC,jasonmccampbell/numpy-refactor-sprint,Ademan/NumPy-GSoC,chadnetzer/numpy-gaurdro,chadnetzer/numpy-gaurdro,teoliphant/numpy-refactor,illume/numpy3k,teoliphant/numpy-refactor,jasonmccampbell/numpy-refactor-sprint,chadnetzer/numpy-gaurdro,jasonmccampbell/numpy-refactor-sprint,efiring/numpy-work,teoliphant/numpy-refactor,efiring/numpy-work,efiring/numpy-work
|
---
+++
@@ -34,6 +34,9 @@
from machar import *
from pexec import *
+if Numeric.__version__ < '23.5':
+ matrixmultiply=dot
+
Inf = inf = fastumath.PINF
try:
NAN = NaN = nan = fastumath.NAN
@@ -46,3 +49,4 @@
if _sys.modules.has_key('scipy_base.Matrix') \
and _sys.modules['scipy_base.Matrix'] is None:
del _sys.modules['scipy_base.Matrix']
+
|
48e14e2f5cb6d7be0e9ec2f39858002b41911245
|
setup.py
|
setup.py
|
#! /usr/bin/env python
"""TODO: Maybe add a docstring containing a long description
This would double as something we could put int the `long_description`
parameter for `setup` and it would squelch some complaints pylint has on
`setup.py`.
"""
from setuptools import setup
import os
setup(name='demandlib',
version='0.1.0rc1',
author='oemof developing group',
url='http://github.com/oemof/demandlib',
license='GPL3',
author_email='oemof@rl-institut.de',
description='Demandlib of the open energy modelling framework',
packages=['demandlib', 'examples'],
package_data = {
'demandlib': [os.path.join('bdew_data', '*.csv')],
'examples': ['*.csv']},
install_requires=['numpy >= 1.7.0',
'pandas >= 0.18.0']
)
|
#! /usr/bin/env python
"""TODO: Maybe add a docstring containing a long description
This would double as something we could put int the `long_description`
parameter for `setup` and it would squelch some complaints pylint has on
`setup.py`.
"""
from setuptools import setup
import os
setup(name='demandlib',
version='0.1.0rc1',
author='oemof developing group',
url='http://github.com/oemof/demandlib',
license='GPL3',
author_email='oemof@rl-institut.de',
description='Demandlib of the open energy modelling framework',
packages=['demandlib', 'examples'],
package_data = {
'demandlib': [os.path.join('bdew_data', '*.csv')],
'examples': ['*.csv']},
install_requires=['numpy >= 1.7.0',
'pandas >= 0.18.0'],
entry_points={
'console_scripts': [
'demandlib_heat_example = examples.heat_demand_example:heat_example',
'demandlib_power_example = examples.power_demand_example:power_example',]}
)
|
Add console scripts for both examples
|
Add console scripts for both examples
Now they are callable from console via
$ demandlib_power_example
and
$ demandlib_heat_example
when installed bia pip3.
|
Python
|
mit
|
oemof/demandlib
|
---
+++
@@ -23,5 +23,9 @@
'demandlib': [os.path.join('bdew_data', '*.csv')],
'examples': ['*.csv']},
install_requires=['numpy >= 1.7.0',
- 'pandas >= 0.18.0']
+ 'pandas >= 0.18.0'],
+ entry_points={
+ 'console_scripts': [
+ 'demandlib_heat_example = examples.heat_demand_example:heat_example',
+ 'demandlib_power_example = examples.power_demand_example:power_example',]}
)
|
c889ffd1f86a445f2e5ba157fc81cbb64e92dc12
|
voctocore/lib/sources/videoloopsource.py
|
voctocore/lib/sources/videoloopsource.py
|
#!/usr/bin/env python3
import logging
import re
from gi.repository import Gst
from lib.config import Config
from lib.sources.avsource import AVSource
class VideoLoopSource(AVSource):
def __init__(self, name):
super().__init__('VideoLoopSource', name, False, True)
self.location = Config.getLocation(name)
self.build_pipeline()
def __str__(self):
return 'VideoLoopSource[{name}] displaying {location}'.format(
name=self.name,
location=self.location
)
def port(self):
m = re.search('.*/([^/]*)', self.location)
return self.location
def num_connections(self):
return 1
def video_channels(self):
return 1
def build_source(self):
return """
multifilesrc
name=videoloop-{name}
location={location}
loop=true
! decodebin
! videoconvert
! videoscale
name=videoloop
""".format(
name=self.name,
location=self.location
)
def build_videoport(self):
return 'videoloop.'
def build_audioport(self, audiostream):
return 'audioloop.'
|
#!/usr/bin/env python3
import logging
import re
from gi.repository import Gst
from lib.config import Config
from lib.sources.avsource import AVSource
class VideoLoopSource(AVSource):
timer_resolution = 0.5
def __init__(self, name, has_audio=True, has_video=True,
force_num_streams=None):
super().__init__('VideoLoopSource', name, has_audio, has_video, show_no_signal=True)
self.location = Config.getLocation(name)
self.build_pipeline()
def __str__(self):
return 'VideoLoopSource[{name}] displaying {location}'.format(
name=self.name,
location=self.location
)
def port(self):
m = re.search('.*/([^/]*)', self.location)
return self.location
def num_connections(self):
return 1
def video_channels(self):
return 1
def build_source(self):
return """
multifilesrc
location={location}
loop=true
! decodebin
name=videoloop-{name}
""".format(
name=self.name,
location=self.location
)
def build_videoport(self):
return """
videoloop-{name}.
! videoconvert
! videoscale
""".format(name=self.name)
def build_audioport(self):
return """
videoloop-{name}.
! audioconvert
! audioresample
""".format(name=self.name)
|
Modify videoloop to allow for audio
|
Modify videoloop to allow for audio
|
Python
|
mit
|
voc/voctomix,voc/voctomix
|
---
+++
@@ -9,8 +9,11 @@
class VideoLoopSource(AVSource):
- def __init__(self, name):
- super().__init__('VideoLoopSource', name, False, True)
+ timer_resolution = 0.5
+
+ def __init__(self, name, has_audio=True, has_video=True,
+ force_num_streams=None):
+ super().__init__('VideoLoopSource', name, has_audio, has_video, show_no_signal=True)
self.location = Config.getLocation(name)
self.build_pipeline()
@@ -33,20 +36,25 @@
def build_source(self):
return """
multifilesrc
- name=videoloop-{name}
location={location}
loop=true
! decodebin
- ! videoconvert
- ! videoscale
- name=videoloop
+ name=videoloop-{name}
""".format(
name=self.name,
location=self.location
)
def build_videoport(self):
- return 'videoloop.'
+ return """
+ videoloop-{name}.
+ ! videoconvert
+ ! videoscale
+ """.format(name=self.name)
- def build_audioport(self, audiostream):
- return 'audioloop.'
+ def build_audioport(self):
+ return """
+ videoloop-{name}.
+ ! audioconvert
+ ! audioresample
+ """.format(name=self.name)
|
acab1af0e9bebeea011de1be472f298ddedd862b
|
src/pretix/control/views/global_settings.py
|
src/pretix/control/views/global_settings.py
|
from django.shortcuts import reverse
from django.views.generic import FormView
from pretix.control.forms.global_settings import GlobalSettingsForm
from pretix.control.permissions import AdministratorPermissionRequiredMixin
class GlobalSettingsView(AdministratorPermissionRequiredMixin, FormView):
template_name = 'pretixcontrol/global_settings.html'
form_class = GlobalSettingsForm
def form_valid(self, form):
form.save()
return super().form_valid(form)
def get_success_url(self):
return reverse('control:global-settings')
|
from django.contrib import messages
from django.shortcuts import reverse
from django.utils.translation import ugettext_lazy as _
from django.views.generic import FormView
from pretix.control.forms.global_settings import GlobalSettingsForm
from pretix.control.permissions import AdministratorPermissionRequiredMixin
class GlobalSettingsView(AdministratorPermissionRequiredMixin, FormView):
template_name = 'pretixcontrol/global_settings.html'
form_class = GlobalSettingsForm
def form_valid(self, form):
form.save()
messages.success(self.request, _('Your changes have been saved.'))
return super().form_valid(form)
def form_invalid(self, form):
messages.error(self.request, _('Your changes have not been saved, see below for errors.'))
return super().form_invalid(form)
def get_success_url(self):
return reverse('control:global-settings')
|
Add feedback to global settings
|
Add feedback to global settings
|
Python
|
apache-2.0
|
Flamacue/pretix,Flamacue/pretix,Flamacue/pretix,Flamacue/pretix
|
---
+++
@@ -1,4 +1,6 @@
+from django.contrib import messages
from django.shortcuts import reverse
+from django.utils.translation import ugettext_lazy as _
from django.views.generic import FormView
from pretix.control.forms.global_settings import GlobalSettingsForm
@@ -11,7 +13,12 @@
def form_valid(self, form):
form.save()
+ messages.success(self.request, _('Your changes have been saved.'))
return super().form_valid(form)
+
+ def form_invalid(self, form):
+ messages.error(self.request, _('Your changes have not been saved, see below for errors.'))
+ return super().form_invalid(form)
def get_success_url(self):
return reverse('control:global-settings')
|
7da7789a6508a60d0ad7662ac69bcee9c478c239
|
numpy/typing/tests/data/fail/array_constructors.py
|
numpy/typing/tests/data/fail/array_constructors.py
|
import numpy as np
a: np.ndarray
generator = (i for i in range(10))
np.require(a, requirements=1) # E: No overload variant
np.require(a, requirements="TEST") # E: incompatible type
np.zeros("test") # E: incompatible type
np.zeros() # E: Too few arguments
np.ones("test") # E: incompatible type
np.ones() # E: Too few arguments
np.array(0, float, True) # E: Too many positional
np.linspace(None, 'bob') # E: No overload variant
np.linspace(0, 2, num=10.0) # E: No overload variant
np.linspace(0, 2, endpoint='True') # E: No overload variant
np.linspace(0, 2, retstep=b'False') # E: No overload variant
np.linspace(0, 2, dtype=0) # E: No overload variant
np.linspace(0, 2, axis=None) # E: No overload variant
np.logspace(None, 'bob') # E: Argument 1
np.logspace(0, 2, base=None) # E: Argument "base"
np.geomspace(None, 'bob') # E: Argument 1
np.stack(generator) # E: No overload variant
np.hstack({1, 2}) # E: incompatible type
np.vstack(1) # E: incompatible type
|
import numpy as np
a: np.ndarray
generator = (i for i in range(10))
np.require(a, requirements=1) # E: No overload variant
np.require(a, requirements="TEST") # E: incompatible type
np.zeros("test") # E: incompatible type
np.zeros() # E: Missing positional argument
np.ones("test") # E: incompatible type
np.ones() # E: Missing positional argument
np.array(0, float, True) # E: Too many positional
np.linspace(None, 'bob') # E: No overload variant
np.linspace(0, 2, num=10.0) # E: No overload variant
np.linspace(0, 2, endpoint='True') # E: No overload variant
np.linspace(0, 2, retstep=b'False') # E: No overload variant
np.linspace(0, 2, dtype=0) # E: No overload variant
np.linspace(0, 2, axis=None) # E: No overload variant
np.logspace(None, 'bob') # E: Argument 1
np.logspace(0, 2, base=None) # E: Argument "base"
np.geomspace(None, 'bob') # E: Argument 1
np.stack(generator) # E: No overload variant
np.hstack({1, 2}) # E: incompatible type
np.vstack(1) # E: incompatible type
|
Fix two failing typing tests
|
TST: Fix two failing typing tests
Mypy 0.800 changed one of its error messages;
the `fail` tests have now been altered to reflect this change
|
Python
|
bsd-3-clause
|
seberg/numpy,jakirkham/numpy,endolith/numpy,pdebuyl/numpy,seberg/numpy,seberg/numpy,mhvk/numpy,pbrod/numpy,pbrod/numpy,pbrod/numpy,endolith/numpy,pbrod/numpy,seberg/numpy,madphysicist/numpy,pbrod/numpy,mattip/numpy,jakirkham/numpy,numpy/numpy,madphysicist/numpy,rgommers/numpy,mhvk/numpy,mhvk/numpy,rgommers/numpy,anntzer/numpy,anntzer/numpy,madphysicist/numpy,simongibbons/numpy,charris/numpy,numpy/numpy,simongibbons/numpy,mhvk/numpy,rgommers/numpy,endolith/numpy,simongibbons/numpy,numpy/numpy,madphysicist/numpy,jakirkham/numpy,charris/numpy,madphysicist/numpy,mattip/numpy,mattip/numpy,anntzer/numpy,endolith/numpy,charris/numpy,jakirkham/numpy,anntzer/numpy,pdebuyl/numpy,rgommers/numpy,pdebuyl/numpy,mattip/numpy,mhvk/numpy,pdebuyl/numpy,simongibbons/numpy,simongibbons/numpy,jakirkham/numpy,charris/numpy,numpy/numpy
|
---
+++
@@ -7,10 +7,10 @@
np.require(a, requirements="TEST") # E: incompatible type
np.zeros("test") # E: incompatible type
-np.zeros() # E: Too few arguments
+np.zeros() # E: Missing positional argument
np.ones("test") # E: incompatible type
-np.ones() # E: Too few arguments
+np.ones() # E: Missing positional argument
np.array(0, float, True) # E: Too many positional
|
0dc833919af095470f1324d9e59647c2f6f851f5
|
genshi/__init__.py
|
genshi/__init__.py
|
# -*- coding: utf-8 -*-
#
# Copyright (C) 2006-2008 Edgewall Software
# All rights reserved.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution. The terms
# are also available at http://genshi.edgewall.org/wiki/License.
#
# This software consists of voluntary contributions made by many
# individuals. For the exact contribution history, see the revision
# history and logs, available at http://genshi.edgewall.org/log/.
"""This package provides various means for generating and processing web markup
(XML or HTML).
The design is centered around the concept of streams of markup events (similar
in concept to SAX parsing events) which can be processed in a uniform manner
independently of where or how they are produced.
"""
__docformat__ = 'restructuredtext en'
try:
from pkg_resources import get_distribution, ResolutionError
try:
__version__ = get_distribution('Genshi').version
except ResolutionError:
__version__ = None # unknown
except ImportError:
__version__ = None # unknown
from genshi.core import *
from genshi.input import ParseError, XML, HTML
|
# -*- coding: utf-8 -*-
#
# Copyright (C) 2006-2008 Edgewall Software
# All rights reserved.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution. The terms
# are also available at http://genshi.edgewall.org/wiki/License.
#
# This software consists of voluntary contributions made by many
# individuals. For the exact contribution history, see the revision
# history and logs, available at http://genshi.edgewall.org/log/.
"""This package provides various means for generating and processing web markup
(XML or HTML).
The design is centered around the concept of streams of markup events (similar
in concept to SAX parsing events) which can be processed in a uniform manner
independently of where or how they are produced.
"""
__docformat__ = 'restructuredtext en'
__version__ = '0.6'
from genshi.core import *
from genshi.input import ParseError, XML, HTML
|
Remove pkg_resources import from top-level package, will just need to remember updating the version in two places.
|
Remove pkg_resources import from top-level package, will just need to remember updating the version in two places.
|
Python
|
bsd-3-clause
|
mitchellrj/genshi,mitchellrj/genshi,mitchellrj/genshi,mitchellrj/genshi
|
---
+++
@@ -20,14 +20,7 @@
"""
__docformat__ = 'restructuredtext en'
-try:
- from pkg_resources import get_distribution, ResolutionError
- try:
- __version__ = get_distribution('Genshi').version
- except ResolutionError:
- __version__ = None # unknown
-except ImportError:
- __version__ = None # unknown
+__version__ = '0.6'
from genshi.core import *
from genshi.input import ParseError, XML, HTML
|
1e71315c20cc542dff207f309993d298de054eb7
|
signac/gui/__init__.py
|
signac/gui/__init__.py
|
# Copyright (c) 2016 The Regents of the University of Michigan
# All rights reserved.
# This software is licensed under the BSD 3-Clause License.
"""Graphical User Interface (GUI) for configuration and database inspection.
The GUI is a leight-weight interface which makes the configuration
of the signac framework and data inspection more straight-forward."""
import logging
try:
import PySide # noqa
import pymongo # noqa
except ImportError as error:
logging.debug("{}. The signac gui is not available.".format(error))
def main():
"""Start signac-gui.
The gui requires PySide and pymongo."""
raise ImportError(msg)
else:
from .gui import main
__all__ = ['main']
|
# Copyright (c) 2016 The Regents of the University of Michigan
# All rights reserved.
# This software is licensed under the BSD 3-Clause License.
"""Graphical User Interface (GUI) for configuration and database inspection.
The GUI is a leight-weight interface which makes the configuration
of the signac framework and data inspection more straight-forward."""
import logging
logger = logging.getLogger(__name__)
try:
import PySide # noqa
import pymongo # noqa
except ImportError as error:
logger.debug("{}. The signac gui is not available.".format(error))
def main():
"""Start signac-gui.
The gui requires PySide and pymongo."""
raise ImportError(msg)
else:
from .gui import main
__all__ = ['main']
|
Fix logging bug in gui module introduced in earlier commit.
|
Fix logging bug in gui module introduced in earlier commit.
|
Python
|
bsd-3-clause
|
csadorf/signac,csadorf/signac
|
---
+++
@@ -6,11 +6,14 @@
The GUI is a leight-weight interface which makes the configuration
of the signac framework and data inspection more straight-forward."""
import logging
+
+logger = logging.getLogger(__name__)
+
try:
import PySide # noqa
import pymongo # noqa
except ImportError as error:
- logging.debug("{}. The signac gui is not available.".format(error))
+ logger.debug("{}. The signac gui is not available.".format(error))
def main():
"""Start signac-gui.
|
7cb4734a837ad9d43ef979085d0f6d474f45178c
|
test_project/select2_outside_admin/views.py
|
test_project/select2_outside_admin/views.py
|
try:
from django.urls import reverse_lazy
except ImportError:
from django.core.urlresolvers import reverse_lazy
from django.forms import inlineformset_factory
from django.views import generic
from select2_many_to_many.forms import TForm
from select2_many_to_many.models import TModel
class UpdateView(generic.UpdateView):
model = TModel
form_class = TForm
template_name = 'select2_outside_admin.html'
success_url = reverse_lazy('select2_outside_admin')
formset_class = inlineformset_factory(
TModel,
TModel,
form=TForm,
extra=1,
fk_name='for_inline',
fields=('name', 'test')
)
def get_object(self):
return TModel.objects.first()
def post(self, request, *args, **kwargs):
form = self.get_form()
if form.is_valid() and self.formset.is_valid():
return self.form_valid(form)
else:
return self.form_invalid(form)
def form_valid(self, form):
result = super().form_valid(form)
self.formset.save()
return result
@property
def formset(self):
if '_formset' not in self.__dict__:
setattr(self, '_formset', self.formset_class(
self.request.POST if self.request.method == 'POST' else None,
instance=getattr(self, 'object', self.get_object()),
))
return self._formset
|
try:
from django.urls import reverse_lazy
except ImportError:
from django.core.urlresolvers import reverse_lazy
from django.forms import inlineformset_factory
from django.views import generic
from select2_many_to_many.forms import TForm
from select2_many_to_many.models import TModel
class UpdateView(generic.UpdateView):
model = TModel
form_class = TForm
template_name = 'select2_outside_admin.html'
success_url = reverse_lazy('select2_outside_admin')
formset_class = inlineformset_factory(
TModel,
TModel,
form=TForm,
extra=1,
fk_name='for_inline',
fields=('name', 'test')
)
def get_object(self):
return TModel.objects.first()
def post(self, request, *args, **kwargs):
self.object = self.get_object()
form = self.get_form()
if form.is_valid() and self.formset.is_valid():
return self.form_valid(form)
else:
return self.form_invalid(form)
def form_valid(self, form):
result = super().form_valid(form)
self.formset.save()
return result
@property
def formset(self):
if '_formset' not in self.__dict__:
setattr(self, '_formset', self.formset_class(
self.request.POST if self.request.method == 'POST' else None,
instance=getattr(self, 'object', self.get_object()),
))
return self._formset
|
Fix example outside the admin
|
Fix example outside the admin
|
Python
|
mit
|
yourlabs/django-autocomplete-light,yourlabs/django-autocomplete-light,yourlabs/django-autocomplete-light,yourlabs/django-autocomplete-light
|
---
+++
@@ -27,6 +27,8 @@
return TModel.objects.first()
def post(self, request, *args, **kwargs):
+ self.object = self.get_object()
+
form = self.get_form()
if form.is_valid() and self.formset.is_valid():
return self.form_valid(form)
|
d7b92a15756dbbad1d66cbe7b2ef25f680e59b10
|
postmarker/pytest.py
|
postmarker/pytest.py
|
from unittest.mock import patch
import pytest
from .core import PostmarkClient, requests
@pytest.yield_fixture
def postmark_request():
"""Mocks network requests to Postmark API."""
if patch is None:
raise AssertionError('To use pytest fixtures on Python 2, please, install postmarker["tests"]')
with patch("postmarker.core.requests.Session.request", wraps=requests.Session().request) as patched:
with patch("postmarker.core.requests.Session.send"):
yield patched
@pytest.yield_fixture
def postmark_client(postmark_request): # pylint: disable=redefined-outer-name
client = PostmarkClient(server_token="SERVER_TOKEN", account_token="ACCOUNT_TOKEN")
client.mock = postmark_request
yield client
|
from unittest.mock import patch
import pytest
from .core import PostmarkClient, requests
@pytest.yield_fixture
def postmark_request():
"""Mocks network requests to Postmark API."""
with patch("postmarker.core.requests.Session.request", wraps=requests.Session().request) as patched:
with patch("postmarker.core.requests.Session.send"):
yield patched
@pytest.yield_fixture
def postmark_client(postmark_request): # pylint: disable=redefined-outer-name
client = PostmarkClient(server_token="SERVER_TOKEN", account_token="ACCOUNT_TOKEN")
client.mock = postmark_request
yield client
|
Drop another Python 2 shim
|
chore: Drop another Python 2 shim
|
Python
|
mit
|
Stranger6667/postmarker
|
---
+++
@@ -8,8 +8,6 @@
@pytest.yield_fixture
def postmark_request():
"""Mocks network requests to Postmark API."""
- if patch is None:
- raise AssertionError('To use pytest fixtures on Python 2, please, install postmarker["tests"]')
with patch("postmarker.core.requests.Session.request", wraps=requests.Session().request) as patched:
with patch("postmarker.core.requests.Session.send"):
yield patched
|
4716df0c5cf96f5a3869bbae60844afbe2aaca4a
|
kolibri/tasks/management/commands/base.py
|
kolibri/tasks/management/commands/base.py
|
from collections import namedtuple
from django.core.management.base import BaseCommand
Progress = namedtuple('Progress', ['progress', 'overall'])
class AsyncCommand(BaseCommand):
CELERY_PROGRESS_STATE_NAME = "PROGRESS"
def handle(self, *args, **options):
self.update_state = options.pop("update_state", id)
self.handle_async(*args, **options)
def set_progress(self, progress, overall=None, message=None):
overall = overall or self.get_overall()
progress = Progress(progress, overall)
self.update_state(state=self.CELERY_PROGRESS_STATE_NAME,
meta=progress)
def get_overall():
pass
def set_overall():
pass
|
from collections import namedtuple
from django.core.management.base import BaseCommand
Progress = namedtuple('Progress', ['progress', 'overall'])
class AsyncCommand(BaseCommand):
"""A management command with added convenience functions for displaying
progress to the user.
Rather than implementing handle() (as is for BaseCommand), subclasses, must
implement handle_async(), which accepts the same arguments as handle().
If ran from the command line, AsynCommand displays a progress bar to the
user. If ran asynchronously through kolibri.tasks.schedule_command(),
AsyncCommand sends results through the Progress class to the main Django
process. Anyone who knows the task id for the command instance can check
the intermediate progress by looking at the task's AsyncResult.result
variable.
"""
CELERY_PROGRESS_STATE_NAME = "PROGRESS"
def _identity(*args, **kwargs):
# heh, are we all just NoneTypes after all?
pass
def handle(self, *args, **options):
self.update_state = options.pop("update_state", self._identity)
self.handle_async(*args, **options)
def set_progress(self, progress, overall=None, message=None):
overall = overall or self.get_overall()
progress = Progress(progress, overall)
self.update_state(state=self.CELERY_PROGRESS_STATE_NAME,
meta=progress)
def get_overall():
pass
def set_overall():
pass
|
Add a bit of documentation on what AsyncCommand is.
|
Add a bit of documentation on what AsyncCommand is.
|
Python
|
mit
|
aronasorman/kolibri,DXCanas/kolibri,DXCanas/kolibri,lyw07/kolibri,jtamiace/kolibri,christianmemije/kolibri,aronasorman/kolibri,aronasorman/kolibri,learningequality/kolibri,rtibbles/kolibri,lyw07/kolibri,mrpau/kolibri,mrpau/kolibri,66eli77/kolibri,jamalex/kolibri,ralphiee22/kolibri,lyw07/kolibri,jamalex/kolibri,indirectlylit/kolibri,benjaoming/kolibri,jayoshih/kolibri,66eli77/kolibri,whitzhu/kolibri,benjaoming/kolibri,benjaoming/kolibri,ralphiee22/kolibri,MingDai/kolibri,ralphiee22/kolibri,christianmemije/kolibri,learningequality/kolibri,jtamiace/kolibri,jamalex/kolibri,aronasorman/kolibri,learningequality/kolibri,indirectlylit/kolibri,christianmemije/kolibri,jonboiser/kolibri,MingDai/kolibri,whitzhu/kolibri,jamalex/kolibri,mrpau/kolibri,indirectlylit/kolibri,learningequality/kolibri,whitzhu/kolibri,MingDai/kolibri,jtamiace/kolibri,jonboiser/kolibri,66eli77/kolibri,jonboiser/kolibri,indirectlylit/kolibri,mrpau/kolibri,DXCanas/kolibri,whitzhu/kolibri,jayoshih/kolibri,jtamiace/kolibri,jayoshih/kolibri,benjaoming/kolibri,jonboiser/kolibri,lyw07/kolibri,MingDai/kolibri,66eli77/kolibri,christianmemije/kolibri,jayoshih/kolibri,rtibbles/kolibri,rtibbles/kolibri,DXCanas/kolibri,ralphiee22/kolibri,rtibbles/kolibri
|
---
+++
@@ -6,11 +6,29 @@
class AsyncCommand(BaseCommand):
+ """A management command with added convenience functions for displaying
+ progress to the user.
+
+ Rather than implementing handle() (as is for BaseCommand), subclasses, must
+ implement handle_async(), which accepts the same arguments as handle().
+
+ If ran from the command line, AsynCommand displays a progress bar to the
+ user. If ran asynchronously through kolibri.tasks.schedule_command(),
+ AsyncCommand sends results through the Progress class to the main Django
+ process. Anyone who knows the task id for the command instance can check
+ the intermediate progress by looking at the task's AsyncResult.result
+ variable.
+
+ """
CELERY_PROGRESS_STATE_NAME = "PROGRESS"
+ def _identity(*args, **kwargs):
+ # heh, are we all just NoneTypes after all?
+ pass
+
def handle(self, *args, **options):
- self.update_state = options.pop("update_state", id)
+ self.update_state = options.pop("update_state", self._identity)
self.handle_async(*args, **options)
|
eb7993ce52e6f8ba7298b6ba9bc68356e99c339b
|
troposphere/codestarconnections.py
|
troposphere/codestarconnections.py
|
# Copyright (c) 2012-2020, Mark Peek <mark@peek.org>
# All rights reserved.
#
# See LICENSE file for full license.
from . import AWSObject
VALID_CONNECTION_PROVIDERTYPE = ('Bitbucket')
def validate_connection_providertype(connection_providertype):
"""Validate ProviderType for Connection"""
if connection_providertype not in VALID_CONNECTION_PROVIDERTYPE:
raise ValueError("Connection ProviderType must be one of: %s" %
", ".join(VALID_CONNECTION_PROVIDERTYPE))
return connection_providertype
class Connection(AWSObject):
resource_type = "AWS::CodeStarConnections::Connection"
props = {
'ConnectionName': (basestring, True),
'ProviderType': (validate_connection_providertype, True),
}
|
# Copyright (c) 2012-2020, Mark Peek <mark@peek.org>
# All rights reserved.
#
# See LICENSE file for full license.
from . import AWSObject, Tags
VALID_CONNECTION_PROVIDERTYPE = ('Bitbucket')
def validate_connection_providertype(connection_providertype):
"""Validate ProviderType for Connection"""
if connection_providertype not in VALID_CONNECTION_PROVIDERTYPE:
raise ValueError("Connection ProviderType must be one of: %s" %
", ".join(VALID_CONNECTION_PROVIDERTYPE))
return connection_providertype
class Connection(AWSObject):
resource_type = "AWS::CodeStarConnections::Connection"
props = {
'ConnectionName': (basestring, True),
'ProviderType': (validate_connection_providertype, True),
'Tags': (Tags, False),
}
|
Add AWS::CodeStarConnections::Connection props, per May 14, 2020 update
|
Add AWS::CodeStarConnections::Connection props, per May 14, 2020 update
|
Python
|
bsd-2-clause
|
cloudtools/troposphere,cloudtools/troposphere
|
---
+++
@@ -4,7 +4,7 @@
# See LICENSE file for full license.
-from . import AWSObject
+from . import AWSObject, Tags
VALID_CONNECTION_PROVIDERTYPE = ('Bitbucket')
@@ -25,4 +25,5 @@
props = {
'ConnectionName': (basestring, True),
'ProviderType': (validate_connection_providertype, True),
+ 'Tags': (Tags, False),
}
|
2733408a9e24c30214831c46ac748aa4884a18fb
|
haddock/haddock.py
|
haddock/haddock.py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#import sys
#reload(sys)
#sys.setdefaultencoding("utf-8")
import os
import random
from io import open
curses_en = os.path.join(os.path.dirname(__file__), "curses_en.txt")
curses_de = os.path.join(os.path.dirname(__file__), "curses_de.txt")
curses_fr = os.path.join(os.path.dirname(__file__), "curses_fr.txt")
file_en = open(curses_en, encoding="utf-8").readlines()
file_de = open(curses_de, encoding="utf-8").readlines()
file_fr = open(curses_fr, encoding="utf-8").readlines()
def curse(lang="en"):
if lang=="de":
return random.choice(file_de).strip()
elif lang=="fr":
return random.choice(file_fr).strip()
else:
return random.choice(file_en).strip()
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import random
from io import open
def curse(lang="en"):
if lang not in curses:
try:
filename = os.path.join(os.path.dirname(__file__), 'curses_%s.txt' % lang)
with open(filename, encoding='utf-8') as f:
curses[lang] = [c.strip() for c in f]
except IOError:
lang = 'en'
return random.choice(curses[lang])
curses = {}
_ = curse('en')
|
Refactor code to eliminate O(n) hard-coding.
|
Refactor code to eliminate O(n) hard-coding.
|
Python
|
mit
|
asmaier/haddock,asmaier/haddock
|
---
+++
@@ -1,27 +1,19 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
-
-#import sys
-#reload(sys)
-#sys.setdefaultencoding("utf-8")
import os
import random
from io import open
-curses_en = os.path.join(os.path.dirname(__file__), "curses_en.txt")
-curses_de = os.path.join(os.path.dirname(__file__), "curses_de.txt")
-curses_fr = os.path.join(os.path.dirname(__file__), "curses_fr.txt")
+def curse(lang="en"):
+ if lang not in curses:
+ try:
+ filename = os.path.join(os.path.dirname(__file__), 'curses_%s.txt' % lang)
+ with open(filename, encoding='utf-8') as f:
+ curses[lang] = [c.strip() for c in f]
+ except IOError:
+ lang = 'en'
+ return random.choice(curses[lang])
-file_en = open(curses_en, encoding="utf-8").readlines()
-file_de = open(curses_de, encoding="utf-8").readlines()
-file_fr = open(curses_fr, encoding="utf-8").readlines()
-
-def curse(lang="en"):
-
- if lang=="de":
- return random.choice(file_de).strip()
- elif lang=="fr":
- return random.choice(file_fr).strip()
- else:
- return random.choice(file_en).strip()
+curses = {}
+_ = curse('en')
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.