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 |
|---|---|---|---|---|---|---|---|---|---|---|
d1a96f13204ad7028432096d25718e611d4d3d9d | depot/gpg.py | depot/gpg.py | import getpass
import os
import gnupg
class GPG(object):
def __init__(self, keyid):
self.gpg = gnupg.GPG(use_agent=False)
self.keyid = keyid
if not self.keyid:
# Compat with how Freight does it.
self.keyid = os.environ.get('GPG')
self.passphrase = None
... | import getpass
import os
import gnupg
class GPG(object):
def __init__(self, keyid, key=None, home=None):
self.gpg = gnupg.GPG(use_agent=False, gnupghome=home)
if key:
if not home:
raise ValueError('Cowardly refusing to import key in to default key store')
r... | Allow passing in a raw key and homedir. | Allow passing in a raw key and homedir. | Python | apache-2.0 | coderanger/depot | ---
+++
@@ -5,8 +5,13 @@
class GPG(object):
- def __init__(self, keyid):
- self.gpg = gnupg.GPG(use_agent=False)
+ def __init__(self, keyid, key=None, home=None):
+ self.gpg = gnupg.GPG(use_agent=False, gnupghome=home)
+ if key:
+ if not home:
+ raise ValueErr... |
11f43c583fb3b7e8ed2aa74f0f58445a6c2fbecf | bot/api/api.py | bot/api/api.py | from bot.api.domain import Message
from bot.api.telegram import TelegramBotApi
from bot.storage import State
class Api:
def __init__(self, telegram_api: TelegramBotApi, state: State):
self.telegram_api = telegram_api
self.state = state
def send_message(self, message: Message, **params):
... | from bot.api.domain import Message
from bot.api.telegram import TelegramBotApi
from bot.storage import State
class Api:
def __init__(self, telegram_api: TelegramBotApi, state: State):
self.telegram_api = telegram_api
self.state = state
def send_message(self, message: Message, **params):
... | Fix get_pending_updates not correctly returning all pending updates | Fix get_pending_updates not correctly returning all pending updates
It was only returning the first 100 ones returned in the first telegram API call.
| Python | agpl-3.0 | alvarogzp/telegram-bot,alvarogzp/telegram-bot | ---
+++
@@ -14,7 +14,12 @@
return self.telegram_api.sendMessage(**message_params)
def get_pending_updates(self):
- return self.get_updates(timeout=0)
+ there_are_pending_updates = True
+ while there_are_pending_updates:
+ there_are_pending_updates = False
+ f... |
48b8efabd11a44dfabcd91f6744858535ddfb498 | djangosaml2/templatetags/idplist.py | djangosaml2/templatetags/idplist.py | # Copyright (C) 2011 Yaco Sistemas (http://www.yaco.es)
#
# 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 applic... | # Copyright (C) 2011 Yaco Sistemas (http://www.yaco.es)
#
# 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 applic... | Load the config as late as possible to avoid crashing when the configuration is not ready yet. Also this code is more reentrant | Load the config as late as possible to avoid crashing when the configuration is not ready yet. Also this code is more reentrant
| Python | apache-2.0 | GradConnection/djangosaml2,advisory/djangosaml2_tenant,WiserTogether/djangosaml2,kviktor/djangosaml2-py3,advisory/djangosaml2_tenant,Gagnavarslan/djangosaml2,shabda/djangosaml2,GradConnection/djangosaml2,WiserTogether/djangosaml2,shabda/djangosaml2,kviktor/djangosaml2-py3,City-of-Helsinki/djangosaml2,City-of-Helsinki/d... | ---
+++
@@ -23,10 +23,10 @@
def __init__(self, variable_name):
self.variable_name = variable_name
- self.conf = config_settings_loader()
def render(self, context):
- context[self.variable_name] = self.conf.get_available_idps()
+ conf = config_settings_loader()
+ cont... |
d636d8e74514bbda29170b18ef3de90dfbd96397 | pylisp/application/lispd/address_tree/ddt_container_node.py | pylisp/application/lispd/address_tree/ddt_container_node.py | '''
Created on 1 jun. 2013
@author: sander
'''
from .container_node import ContainerNode
class DDTContainerNode(ContainerNode):
pass
| '''
Created on 1 jun. 2013
@author: sander
'''
from .container_node import ContainerNode
class DDTContainerNode(ContainerNode):
'''
A ContainerNode that indicates that we are responsible for this part of
the DDT tree.
'''
| Add a bit of docs | Add a bit of docs
| Python | bsd-3-clause | steffann/pylisp | ---
+++
@@ -7,4 +7,7 @@
class DDTContainerNode(ContainerNode):
- pass
+ '''
+ A ContainerNode that indicates that we are responsible for this part of
+ the DDT tree.
+ ''' |
b6e9215457eba813f91c9eb4a8b96f8652bcd5fc | functional_tests/pages/settings.py | functional_tests/pages/settings.py | # -*- coding: utf-8 -*-
from selenium.webdriver.support.ui import Select
from page_objects import PageObject, PageElement, MultiPageElement
class SettingsPage(PageObject):
return_link = PageElement(css='.mui--text-title a.appbar-correct')
inlist_delete_confirm = PageElement(name='inlist_delete_confirm')
ac... | # -*- coding: utf-8 -*-
from selenium.webdriver.support.ui import Select
from page_objects import PageObject, PageElement, MultiPageElement
class SettingsPage(PageObject):
return_link = PageElement(css='#sidebar-brand a')
inlist_delete_confirm = PageElement(name='inlist_delete_confirm')
action_delete_confi... | Make the return link work again | Make the return link work again
| Python | mit | XeryusTC/projman,XeryusTC/projman,XeryusTC/projman | ---
+++
@@ -3,7 +3,7 @@
from page_objects import PageObject, PageElement, MultiPageElement
class SettingsPage(PageObject):
- return_link = PageElement(css='.mui--text-title a.appbar-correct')
+ return_link = PageElement(css='#sidebar-brand a')
inlist_delete_confirm = PageElement(name='inlist_delete_con... |
a38e293d76beaa71893a8f5c4be2ea562d6d3fc2 | apistar/layouts/standard/project/routes.py | apistar/layouts/standard/project/routes.py | from apistar import Route, Include
from apistar.docs import docs_routes
from apistar.statics import static_routes
from project.views import welcome
routes = [
Route('/', 'GET', welcome),
Include('/docs', docs_routes),
Include('/static', static_routes)
]
| from apistar import Include, Route
from apistar.docs import docs_routes
from apistar.statics import static_routes
from project.views import welcome
routes = [
Route('/', 'GET', welcome),
Include('/docs', docs_routes),
Include('/static', static_routes)
]
| Fix import ordering in standard layout | Fix import ordering in standard layout
| Python | bsd-3-clause | encode/apistar,rsalmaso/apistar,rsalmaso/apistar,encode/apistar,tomchristie/apistar,tomchristie/apistar,tomchristie/apistar,thimslugga/apistar,thimslugga/apistar,rsalmaso/apistar,encode/apistar,rsalmaso/apistar,encode/apistar,thimslugga/apistar,thimslugga/apistar,tomchristie/apistar | ---
+++
@@ -1,4 +1,4 @@
-from apistar import Route, Include
+from apistar import Include, Route
from apistar.docs import docs_routes
from apistar.statics import static_routes
from project.views import welcome |
bfad91e9685b94f7c1072126d44ef29c9235f973 | reports/management/commands/tests.py | reports/management/commands/tests.py | import pytz
try:
import mock
except ImportError:
from unittest import mock
try:
from StringIO import StringIO
except ImportError:
from io import StringIO
from datetime import datetime
from django.conf import settings
from django.core import management
from django.test import TestCase
from tempfile imp... | Test report generation management command calls task correctly | Test report generation management command calls task correctly
| Python | bsd-3-clause | praekelt/hellomama-registration,praekelt/hellomama-registration | ---
+++
@@ -0,0 +1,54 @@
+import pytz
+try:
+ import mock
+except ImportError:
+ from unittest import mock
+
+try:
+ from StringIO import StringIO
+except ImportError:
+ from io import StringIO
+
+from datetime import datetime
+from django.conf import settings
+from django.core import management
+from dja... | |
0e3da072c5ff62996ebed9d5d6909bbf9bb4b30f | jsonrpcserver/blueprint.py | jsonrpcserver/blueprint.py | """blueprint.py"""
import flask
from werkzeug.exceptions import HTTPException
from werkzeug.exceptions import default_exceptions
from jsonrpcserver import exceptions
from jsonrpcserver import logger
from jsonrpcserver import bp
def error(e, response_str):
"""Ensure we always respond with jsonrpc, such as on 400 ... | """blueprint.py"""
import flask
from werkzeug.exceptions import HTTPException
from werkzeug.exceptions import default_exceptions
from jsonrpcserver import exceptions
from jsonrpcserver import logger
from jsonrpcserver import bp
def error(e, response_str):
"""Ensure we always respond with jsonrpc, such as on 400... | Return http status code 400 (Bad Request) unless flask gives an error code | Return http status code 400 (Bad Request) unless flask gives an error code
| Python | mit | bcb/jsonrpcserver | ---
+++
@@ -8,24 +8,28 @@
from jsonrpcserver import logger
from jsonrpcserver import bp
+
def error(e, response_str):
"""Ensure we always respond with jsonrpc, such as on 400 or other bad
request"""
response = flask.Response(response_str, mimetype='application/json')
- response.status_code = ... |
e9bd1c56025e380444ba1e92f6631f59dd01a10a | cms/djangoapps/contentstore/views/session_kv_store.py | cms/djangoapps/contentstore/views/session_kv_store.py | from xblock.runtime import KeyValueStore, InvalidScopeError
class SessionKeyValueStore(KeyValueStore):
def __init__(self, request, descriptor_model_data):
self._descriptor_model_data = descriptor_model_data
self._session = request.session
def get(self, key):
try:
return se... | from xblock.runtime import KeyValueStore, InvalidScopeError
class SessionKeyValueStore(KeyValueStore):
def __init__(self, request, descriptor_model_data):
self._descriptor_model_data = descriptor_model_data
self._session = request.session
def get(self, key):
try:
return se... | Fix SessionKeyValueStore.has to use the correct indexing value when looking up data | Fix SessionKeyValueStore.has to use the correct indexing value when looking up data
| Python | agpl-3.0 | ampax/edx-platform-backup,ak2703/edx-platform,ferabra/edx-platform,doganov/edx-platform,pdehaye/theming-edx-platform,jelugbo/tundex,jazztpt/edx-platform,shubhdev/edx-platform,J861449197/edx-platform,wwj718/ANALYSE,wwj718/ANALYSE,doismellburning/edx-platform,shabab12/edx-platform,jamiefolsom/edx-platform,abdoosh00/edraa... | ---
+++
@@ -25,4 +25,4 @@
del self._session[tuple(key)]
def has(self, key):
- return key in self._descriptor_model_data or key in self._session
+ return key.field_name in self._descriptor_model_data or tuple(key) in self._session |
4a67ee6df306fa7907ef76647446e46ae1bfea99 | erudite/components/knowledge_provider.py | erudite/components/knowledge_provider.py | """
Knowledge provider that will respond to requests made by the rdf publisher or another bot.
"""
from sleekxmpp.plugins.base import base_plugin
from rhobot.components.storage.client import StoragePayload
from rdflib.namespace import FOAF
import logging
logger = logging.getLogger(__name__)
class KnowledgeProvider(b... | """
Knowledge provider that will respond to requests made by the rdf publisher or another bot.
"""
from sleekxmpp.plugins.base import base_plugin
from rhobot.components.storage.client import StoragePayload
from rdflib.namespace import FOAF
from rhobot.namespace import RHO
import logging
logger = logging.getLogger(__na... | Use string of Rho Namespace | Use string of Rho Namespace
Instead of the URI object, need to use the string.
| Python | bsd-3-clause | rerobins/rho_erudite | ---
+++
@@ -4,6 +4,7 @@
from sleekxmpp.plugins.base import base_plugin
from rhobot.components.storage.client import StoragePayload
from rdflib.namespace import FOAF
+from rhobot.namespace import RHO
import logging
logger = logging.getLogger(__name__)
@@ -14,7 +15,7 @@
description = 'Knowledge Provider'
... |
154659f2126cd83e0a52af3d1a84620ca5c52409 | examples/generic_lpu/visualize_output.py | examples/generic_lpu/visualize_output.py |
import numpy as np
import neurokernel.LPU.utils.visualizer as vis
import networkx as nx
nx.readwrite.gexf.GEXF.convert_bool = {'false':False, 'False':False,
'true':True, 'True':True}
G = nx.read_gexf('./data/generic_lpu.gexf.gz')
neu_out = [k for k,n in G.node.items() if n['na... |
import numpy as np
import matplotlib as mpl
mpl.use('agg')
import neurokernel.LPU.utils.visualizer as vis
import networkx as nx
nx.readwrite.gexf.GEXF.convert_bool = {'false':False, 'False':False,
'true':True, 'True':True}
G = nx.read_gexf('./data/generic_lpu.gexf.gz')
neu_ou... | Use AGG backend for generic visualization to avoid display dependency. | Use AGG backend for generic visualization to avoid display dependency.
| Python | bsd-3-clause | cerrno/neurokernel | ---
+++
@@ -1,5 +1,8 @@
import numpy as np
+import matplotlib as mpl
+mpl.use('agg')
+
import neurokernel.LPU.utils.visualizer as vis
import networkx as nx
|
d38f36e0b783c1a1f72ead46b90a982fcbe34488 | tools/conan/conanfile.py | tools/conan/conanfile.py | from conans import ConanFile, CMake, tools
class LibWFUTConan(ConanFile):
name = "libwfut"
version = "0.2.4"
license = "GPL-2.0+"
author = "Erik Ogenvik <erik@ogenvik.org>"
homepage = "https://www.worldforge.org"
url = "https://github.com/worldforge/libwfut"
description = "A client side C+... | from conans import ConanFile, CMake, tools
class LibWFUTConan(ConanFile):
name = "libwfut"
version = "0.2.4"
license = "GPL-2.0+"
author = "Erik Ogenvik <erik@ogenvik.org>"
homepage = "https://www.worldforge.org"
url = "https://github.com/worldforge/libwfut"
description = "A client side C+... | Use Conan Center provided libcurl. | Use Conan Center provided libcurl.
| Python | lgpl-2.1 | worldforge/libwfut,worldforge/libwfut,worldforge/libwfut,worldforge/libwfut | ---
+++
@@ -16,7 +16,7 @@
generators = "cmake"
requires = ["sigc++/2.10.0@worldforge/stable",
"zlib/1.2.11",
- "libcurl/7.66.0@worldforge/stable"]
+ "libcurl/7.75.0"]
scm = {
"type": "git", |
68287347cacae6a7836698cfb11523c8819628c9 | virustotal/vt.py | virustotal/vt.py | from threading import Semaphore
from os.path import basename
from rate import ratelimiter
import requests
class VirusTotal():
def __init__(self, apikey, limit=4, every=60):
self.semaphore = Semaphore(limit)
self.apikey = apikey
self.every = every
def scan(self, path):
with ra... | from threading import Semaphore
from os.path import basename
from rate import ratelimiter
import requests
class VirusTotal():
def __init__(self, apikey, limit=4, every=60):
self.semaphore = threading.Semaphore(limit)
self.apikey = apikey
self.every = every
def scan(self, path):
... | Add apikey to get_report api | Add apikey to get_report api
| Python | mit | enricobacis/playscraper | ---
+++
@@ -7,7 +7,7 @@
class VirusTotal():
def __init__(self, apikey, limit=4, every=60):
- self.semaphore = Semaphore(limit)
+ self.semaphore = threading.Semaphore(limit)
self.apikey = apikey
self.every = every
@@ -22,7 +22,7 @@
def get_report(self, resource):
... |
b2adc19e5f28c16bc7cfcd38ed35043d7b1fbe29 | profile_collection/startup/15-machines.py | profile_collection/startup/15-machines.py | from ophyd import PVPositionerPC, EpicsSignal, EpicsSignalRO
from ophyd import Component as Cpt
# Undulator
class Undulator(PVPositionerPC):
readback = Cpt(EpicsSignalRO, '-LEnc}Gap')
setpoint = Cpt(EpicsSignal, '-Mtr:2}Inp:Pos')
actuate = Cpt(EpicsSignal, '-Mtr:2}Sw:Go')
actuate_value = 1
stop_si... | from ophyd import PVPositionerPC, EpicsSignal, EpicsSignalRO
from ophyd import Component as Cpt
# Undulator
class Undulator(PVPositionerPC):
readback = Cpt(EpicsSignalRO, '-LEnc}Gap')
setpoint = Cpt(EpicsSignal, '-Mtr:2}Inp:Pos')
actuate = Cpt(EpicsSignal, '-Mtr:2}Sw:Go')
actuate_value = 1
stop_si... | ADD readback.name in iuv_gap to fix speck save prob | ADD readback.name in iuv_gap to fix speck save prob
| Python | bsd-2-clause | NSLS-II-CHX/ipython_ophyd,NSLS-II-CHX/ipython_ophyd | ---
+++
@@ -12,7 +12,9 @@
stop_value = 1
ivu_gap = Undulator('SR:C11-ID:G1{IVU20:1', name='ivu_gap')
-ivu_gap.readback = 'ivu_gap'
+# ivu_gap.readback = 'ivu_gap' ####what the ^*(*()**)(* !!!!
+#To solve the "KeyError Problem" when doing dscan and trying to save to a spec file, Y.G., 20170110
+ivu_gap.readb... |
d5b068b2efc5fca30014ac7b4d58123461bfbdc1 | djedi/utils/templates.py | djedi/utils/templates.py | import json
from django.core.exceptions import ImproperlyConfigured
from ..compat import NoReverseMatch, render, render_to_string, reverse
def render_embed(nodes=None, request=None):
context = {}
if nodes is None:
try:
prefix = request.build_absolute_uri("/").rstrip("/")
con... | import json
from django.core.exceptions import ImproperlyConfigured
from ..compat import NoReverseMatch, render, render_to_string, reverse
def render_embed(nodes=None, request=None):
context = {}
if nodes is None:
try:
prefix = request.build_absolute_uri("/").rstrip("/")
con... | Update rest api url config error message | Update rest api url config error message
| Python | bsd-3-clause | 5monkeys/djedi-cms,5monkeys/djedi-cms,5monkeys/djedi-cms | ---
+++
@@ -21,7 +21,8 @@
except NoReverseMatch:
raise ImproperlyConfigured(
"Could not find djedi in your url conf, "
- "include djedi.rest.urls within the djedi namespace."
+ "enable django admin or include "
+ "djedi.urls within th... |
248fda4f499375b24a2f670569259f0904948b7e | troposphere/detective.py | troposphere/detective.py | # Copyright (c) 2020, Mark Peek <mark@peek.org>
# All rights reserved.
#
# See LICENSE file for full license.
from . import AWSObject
from .validators import boolean
class Graph(AWSObject):
resource_type = "AWS::Detective::Graph"
props = {}
class MemberInvitation(AWSObject):
resource_type = "AWS::Dete... | # Copyright (c) 2020, Mark Peek <mark@peek.org>
# All rights reserved.
#
# See LICENSE file for full license.
from . import AWSObject, Tags
from .validators import boolean
class Graph(AWSObject):
resource_type = "AWS::Detective::Graph"
props = {
"Tags": (Tags, False),
}
class MemberInvitation(... | Update Detective per 2021-04-29 changes | Update Detective per 2021-04-29 changes
| Python | bsd-2-clause | cloudtools/troposphere,cloudtools/troposphere | ---
+++
@@ -3,14 +3,16 @@
#
# See LICENSE file for full license.
-from . import AWSObject
+from . import AWSObject, Tags
from .validators import boolean
class Graph(AWSObject):
resource_type = "AWS::Detective::Graph"
- props = {}
+ props = {
+ "Tags": (Tags, False),
+ }
class Mem... |
7c0d68b1bce27d026b69e3a069c549ab560b0f3d | spillway/mixins.py | spillway/mixins.py | class FormMixin(object):
"""Mixin to provide form validation and data cleaning of GET or POST
requests.
"""
form_class = None
@property
def form(self):
"""Returns a validated form dict or an empty dict."""
_form = getattr(self, '_form', False)
if not _form:
s... | class FormMixin(object):
"""Mixin to provide form validation and data cleaning of GET or POST
requests.
"""
form_class = None
@property
def form(self):
"""Returns a validated form dict or an empty dict."""
_form = getattr(self, '_form', False)
if not _form:
s... | Use DRF query params and data request attrs | Use DRF query params and data request attrs
| Python | bsd-3-clause | barseghyanartur/django-spillway,kuzmich/django-spillway,bkg/django-spillway | ---
+++
@@ -9,7 +9,8 @@
"""Returns a validated form dict or an empty dict."""
_form = getattr(self, '_form', False)
if not _form:
- self._form = self.form_class(self.request.GET or self.request.POST,
- self.request.FILES or None)
+ ... |
f62278c420429cfe9a3f2a8903f902ae24bdd95d | remoteappmanager/handlers/home_handler.py | remoteappmanager/handlers/home_handler.py | from tornado import gen, web
from remoteappmanager.handlers.base_handler import BaseHandler
class HomeHandler(BaseHandler):
"""Render the user's home page"""
@web.authenticated
@gen.coroutine
def get(self):
images_info = yield self._get_images_info()
self.render('home.html', images_i... | from tornado import gen, web
from remoteappmanager.handlers.base_handler import BaseHandler
class HomeHandler(BaseHandler):
"""Render the user's home page"""
@web.authenticated
@gen.coroutine
def get(self):
self.render('home.html')
| Remove dead code now part of the REST API. | Remove dead code now part of the REST API.
| Python | bsd-3-clause | simphony/simphony-remote,simphony/simphony-remote,simphony/simphony-remote,simphony/simphony-remote | ---
+++
@@ -9,43 +9,4 @@
@web.authenticated
@gen.coroutine
def get(self):
- images_info = yield self._get_images_info()
- self.render('home.html', images_info=images_info)
-
- # private
-
- @gen.coroutine
- def _get_images_info(self):
- """Retrieves a dictionary containing... |
20ecbcf76581caca255572e634883bc3746fe41f | src/metpy/__init__.py | src/metpy/__init__.py | # Copyright (c) 2015,2019 MetPy Developers.
# Distributed under the terms of the BSD 3-Clause License.
# SPDX-License-Identifier: BSD-3-Clause
"""Tools for reading, calculating, and plotting with weather data."""
# What do we want to pull into the top-level namespace?
import os
import sys
import warnings
if sys.versi... | # Copyright (c) 2015,2019 MetPy Developers.
# Distributed under the terms of the BSD 3-Clause License.
# SPDX-License-Identifier: BSD-3-Clause
"""Tools for reading, calculating, and plotting with weather data."""
# What do we want to pull into the top-level namespace?
import os
import sys
import warnings
if sys.versi... | Fix new lint found by flake8 | MNT: Fix new lint found by flake8
| Python | bsd-3-clause | ShawnMurd/MetPy,Unidata/MetPy,dopplershift/MetPy,dopplershift/MetPy,Unidata/MetPy | ---
+++
@@ -32,6 +32,6 @@
os.environ['PINT_ARRAY_PROTOCOL_FALLBACK'] = '0'
from ._version import get_version # noqa: E402
-from .xarray import * # noqa: F401, F403
+from .xarray import * # noqa: F401, F403, E402
__version__ = get_version()
del get_version |
e18153ba918592bedb1ae363afc2b437db7576db | examples/livestream_datalogger.py | examples/livestream_datalogger.py | from pymoku import Moku, MokuException, NoDataException
from pymoku.instruments import *
import time, logging, traceback
logging.basicConfig(format='%(asctime)s:%(name)s:%(levelname)s::%(message)s')
logging.getLogger('pymoku').setLevel(logging.INFO)
# Use Moku.get_by_serial() or get_by_name() if you don't know the IP... | from pymoku import Moku, MokuException, NoDataException
from pymoku.instruments import *
import time, logging, traceback
logging.basicConfig(format='%(asctime)s:%(name)s:%(levelname)s::%(message)s')
logging.getLogger('pymoku').setLevel(logging.INFO)
# Use Moku.get_by_serial() or get_by_name() if you don't know the IP... | Fix trivial off by 1 in the livestream datalogger example | Datalogger: Fix trivial off by 1 in the livestream datalogger example
| Python | mit | benizl/pymoku,liquidinstruments/pymoku | ---
+++
@@ -24,7 +24,7 @@
while True:
ch, idx, d = i.datalogger_get_samples(timeout=5)
- print "Received samples %d to %d from channel %d" % (idx, idx + len(d), ch)
+ print "Received samples %d to %d from channel %d" % (idx, idx + len(d) - 1, ch)
except NoDataException as e:
# This will be raised if we tr... |
916b86865acf0297293e4a13f1da6838f9b2711f | scripts/lib/errors.py | scripts/lib/errors.py | """ Оповещение администратора о возникших ошибках """
from traceback import format_exception, format_exc
from lib.config import emergency_id
from lib.commands import vk, api
class ErrorManager:
""" Упрощенное оповещение об ошибках
str name: название скрипта (обычно укороченное)
Использование: with ErrorManager... | """ Оповещение администратора о возникших ошибках """
from traceback import format_exception, format_exc
from contextlib import contextmanager
from lib.config import emergency_id
from lib.commands import vk, api
@contextmanager
def ErrorManager(name):
""" Упрощенное оповещение об ошибках
str name: название скрипт... | Change error class to function | Change error class to function
| Python | mit | Varabe/Guild-Manager | ---
+++
@@ -1,25 +1,23 @@
""" Оповещение администратора о возникших ошибках """
from traceback import format_exception, format_exc
+from contextlib import contextmanager
from lib.config import emergency_id
from lib.commands import vk, api
-class ErrorManager:
+@contextmanager
+def ErrorManager(name):
""" ... |
146e35f48774173c2000b8a9790cdbe6925ba94a | opps/contrib/multisite/admin.py | opps/contrib/multisite/admin.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from django.contrib import admin
from .models import SitePermission
admin.site.register(SitePermission)
| #!/usr/bin/env python
# -*- coding: utf-8 -*-
from django.contrib import admin
from django.utils import timezone
from .models import SitePermission
class AdminViewPermission(admin.ModelAdmin):
def queryset(self, request):
queryset = super(AdminViewPermission, self).queryset(request)
try:
... | Create AdminViewPermission on contrib multisite | Create AdminViewPermission on contrib multisite
| Python | mit | opps/opps,YACOWS/opps,williamroot/opps,jeanmask/opps,opps/opps,williamroot/opps,jeanmask/opps,YACOWS/opps,YACOWS/opps,YACOWS/opps,opps/opps,jeanmask/opps,williamroot/opps,opps/opps,jeanmask/opps,williamroot/opps | ---
+++
@@ -1,7 +1,24 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from django.contrib import admin
+from django.utils import timezone
+
from .models import SitePermission
+class AdminViewPermission(admin.ModelAdmin):
+
+ def queryset(self, request):
+ queryset = super(AdminViewPermission, self)... |
7e25a0097c3a4e7d37d75f6e90bcee2883df0a46 | analysis/opening_plot.py | analysis/opening_plot.py | #!/usr/bin/python
import sys
def parse_opening_list(filename):
with open(filename) as f:
open_count = dict()
openings = []
for line in (raw.strip() for raw in f):
open_count.setdefault(line, 0)
open_count[line] += 1
openings.append(line)
top10 = lis... | #!/usr/bin/python
import sys
def parse_opening_list(filename):
with open(filename) as f:
open_count = dict()
openings = []
for line in (raw.strip() for raw in f):
open_count.setdefault(line, 0)
open_count[line] += 1
openings.append(line)
top10 = lis... | Write correct titles for opening plots | Write correct titles for opening plots
| Python | mit | MarkZH/Genetic_Chess,MarkZH/Genetic_Chess,MarkZH/Genetic_Chess,MarkZH/Genetic_Chess,MarkZH/Genetic_Chess | ---
+++
@@ -21,7 +21,7 @@
for data in [[top10, '_top_opening_data.txt'], [top10_rate, '_top_opening_rate_data.txt']]:
with open(filename + data[1] , 'w') as out:
- out.write(','.join(top10) + '\n')
+ out.write(','.join(data[0]) + '\n')
for opening in openings:
... |
bc92988baee2186fe5b746751fb5d2e3ec6cb8d9 | statzlogger.py | statzlogger.py | import logging
try:
NullHandler = logging.NullHandler
except AttributeError:
class NullHandler(logging.Handler):
def emit(self, record):
pass
log = logging.getLogger("statzlogger")
log.addHandler(NullHandler())
class StatzHandler(logging.Handler):
def emit(self, record):
pass... | import logging
try:
NullHandler = logging.NullHandler
except AttributeError:
class NullHandler(logging.Handler):
def emit(self, record):
pass
log = logging.getLogger("statzlogger")
log.addHandler(NullHandler())
class StatzHandler(logging.Handler):
def __init__(self, level=logging.NOT... | Index creation should apply across the board. | Index creation should apply across the board.
| Python | isc | whilp/statzlogger | ---
+++
@@ -12,14 +12,14 @@
class StatzHandler(logging.Handler):
+ def __init__(self, level=logging.NOTSET):
+ logging.Handler.__init__(self, level)
+ self.indices = {}
+
def emit(self, record):
pass
class Collection(StatzHandler):
-
- def __init__(self, level=logging.NOTSET)... |
dbe5c25e302b4b71603a94a9519e74605714284c | generic_links/migrations/0001_initial.py | generic_links/migrations/0001_initial.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
('contenttypes', '0002_remove_content_type_name'),
migrations.swappable_dependency(settings.AUTH_USER_... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.Create... | Remove migration dependency from Django 1.8 | Remove migration dependency from Django 1.8 | Python | bsd-3-clause | matagus/django-generic-links,matagus/django-generic-links | ---
+++
@@ -8,7 +8,6 @@
class Migration(migrations.Migration):
dependencies = [
- ('contenttypes', '0002_remove_content_type_name'),
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
|
a3eb818fb9201d5fdf520ce87c9da1d11e1c7e75 | denim/constants.py | denim/constants.py | # -*- encoding:utf8 -*-
from fabric.api import env
class RootUser(object):
"""
Class to define Root user.
"""
uid=0
@classmethod
def sudo_identity(cls):
return None
class DeployUser(object):
"""
Class to define Deploy User.
"""
@classmethod
def sudo_identity(cls... | # -*- encoding:utf8 -*-
from fabric.api import env
class UserBase(object):
pass
class RootUser(UserBase):
"""
Class to define Root user.
"""
uid=0
@classmethod
def sudo_identity(cls):
return None
class DeployUser(UserBase):
"""
Class to define Deploy User.
"""
... | Fix issue running database creation, should be run as the deployment user | Fix issue running database creation, should be run as the deployment user
| Python | bsd-2-clause | timsavage/denim | ---
+++
@@ -2,7 +2,11 @@
from fabric.api import env
-class RootUser(object):
+class UserBase(object):
+ pass
+
+
+class RootUser(UserBase):
"""
Class to define Root user.
"""
@@ -13,7 +17,7 @@
return None
-class DeployUser(object):
+class DeployUser(UserBase):
"""
Class t... |
9bdfdc860264aa200d74bcaf813c2f5055307a3b | webapp/tests/__init__.py | webapp/tests/__init__.py | # -*- coding: utf-8 -*-
from unittest import TestCase
from byceps.application import create_app
from byceps.database import db
class AbstractAppTestCase(TestCase):
def setUp(self):
self.app = create_app('test', initialize=False)
db.app = self.app
db.create_all()
def tearDown(self)... | # -*- coding: utf-8 -*-
from unittest import TestCase
from byceps.application import create_app
from byceps.blueprints.brand.models import Brand
from byceps.blueprints.party.models import Party
from byceps.database import db
class AbstractAppTestCase(TestCase):
def setUp(self):
self.app = create_app('t... | Prepare application test with current brand and party. | Prepare application test with current brand and party.
| Python | bsd-3-clause | homeworkprod/byceps,m-ober/byceps,m-ober/byceps,homeworkprod/byceps,homeworkprod/byceps,m-ober/byceps | ---
+++
@@ -3,6 +3,8 @@
from unittest import TestCase
from byceps.application import create_app
+from byceps.blueprints.brand.models import Brand
+from byceps.blueprints.party.models import Party
from byceps.database import db
@@ -11,8 +13,20 @@
def setUp(self):
self.app = create_app('test', in... |
af3a124c8608fc516a0b78b25da0d4c96aef68da | avahi-daemon/dbus-test.py | avahi-daemon/dbus-test.py | #!/usr/bin/python2.4
import dbus
import dbus.glib
import gtk
from time import sleep
bus = dbus.SystemBus()
server = dbus.Interface(bus.get_object("org.freedesktop.Avahi", '/org/freedesktop/Avahi/Server'), 'org.freedesktop.Avahi.Server')
print "Host name: %s" % server.GetHostName()
print "Domain name: %s" % server.... | #!/usr/bin/python2.4
import dbus
import dbus.glib
import gtk
from time import sleep
bus = dbus.SystemBus()
server = dbus.Interface(bus.get_object("org.freedesktop.Avahi", '/org/freedesktop/Avahi/Server'), 'org.freedesktop.Avahi.Server')
def server_state_changed_callback(t):
print "Server::StateChanged: ", t
s... | Make use of StateChanged signal of DBUS Server object | Make use of StateChanged signal of DBUS Server object
git-svn-id: ff687e355030673c307e7da231f59639d58f56d5@172 941a03a8-eaeb-0310-b9a0-b1bbd8fe43fe
| Python | lgpl-2.1 | Distrotech/avahi,Kisensum/xmDNS-avahi,Kisensum/xmDNS-avahi,heftig/avahi,catta-x/catta,lathiat/avahi,catta-x/catta,lathiat/avahi,heftig/avahi,sunilghai/avahi-clone,sunilghai/avahi-clone,lathiat/avahi,heftig/avahi-1,catta-x/catta,Distrotech/avahi,Distrotech/avahi,heftig/avahi,heftig/avahi-1,heftig/avahi-1,Kisensum/xmDNS-... | ---
+++
@@ -10,16 +10,22 @@
server = dbus.Interface(bus.get_object("org.freedesktop.Avahi", '/org/freedesktop/Avahi/Server'), 'org.freedesktop.Avahi.Server')
+def server_state_changed_callback(t):
+ print "Server::StateChanged: ", t
+
+server.connect_to_signal("StateChanged", server_state_changed_callback)
+
... |
50488976619795621b5eb6dd3e427f6f82188426 | peanut/template.py | peanut/template.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Template"""
import peanut
import jinja2
from os import path
from jinja2 import FileSystemLoader
from jinja2.exceptions import TemplateNotFound
class SmartLoader(FileSystemLoader):
"""A smart template loader"""
available_extension = ['.html', '.xml']
def... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Template"""
import peanut
import jinja2
from os import path
from jinja2 import FileSystemLoader
from jinja2.exceptions import TemplateNotFound
class SmartLoader(FileSystemLoader):
"""A smart template loader"""
available_extension = ['.html', '.xml']
def... | Add an interface to update global context | Add an interface to update global context
| Python | mit | zqqf16/Peanut,zqqf16/Peanut,zqqf16/Peanut | ---
+++
@@ -45,6 +45,11 @@
# Update global namesapce
self.env.globals.update(kwargs)
+ def update_context(self, **kwargs):
+ """Update global context
+ """
+ self.env.globals.update(kwargs)
+
def render(self, name, **context):
"""Render template with name ... |
a5387c85a898717a5ae13dafe6f0f2b19f44e749 | apps/vacancies/tasks.py | apps/vacancies/tasks.py | # coding: utf-8
import urllib
from celery import shared_task
from apps.vacancies.parsers import VacancySync, YandexRabotaParser
@shared_task(ignore_result=True)
def update_vacancies():
fulltime = {
'rid': 213,
'currency': 'RUR',
'text': 'python программист',
'strict': 'false',
... | # coding: utf-8
import urllib
from celery import shared_task
from apps.vacancies.parsers import VacancySync, YandexRabotaParser
@shared_task(ignore_result=True)
def update_vacancies():
fulltime = {
'rid': 213,
'currency': 'RUR',
'text': 'python программист',
'strict': 'false',
... | Disable contracts in jobs parser | Disable contracts in jobs parser
| Python | bsd-3-clause | moscowdjango/moscowdjango,moscowdjango/moscowdjango,moscowdjango/moscowdjango,VladimirFilonov/moscowdjango,moscowpython/moscowpython,VladimirFilonov/moscowdjango,moscowpython/moscowpython,VladimirFilonov/moscowdjango,moscowpython/moscowpython | ---
+++
@@ -18,6 +18,7 @@
syncer = VacancySync(parsers=[
YandexRabotaParser(urllib.parse.urlencode(fulltime), type='fulltime'),
- YandexRabotaParser(urllib.parse.urlencode(part_time), type='contract')
+ # Contract feed is broken as of 13 july (shows same data as fulltime)
+ # Yand... |
0281aaa0868d0bfa6ecb7368cff89b4af6b57129 | tests/functions_tests/test_dropout.py | tests/functions_tests/test_dropout.py | import unittest
import numpy
import chainer
from chainer import cuda
from chainer import functions
from chainer import testing
if cuda.available:
cuda.init()
class TestDropout(unittest.TestCase):
def setUp(self):
self.x = numpy.random.uniform(-1, 1, (2, 3)).astype(numpy.float32)
def check_ty... | import unittest
import numpy
import chainer
from chainer import cuda
from chainer import functions
from chainer import testing
from chainer.testing import attr
if cuda.available:
cuda.init()
class TestDropout(unittest.TestCase):
def setUp(self):
self.x = numpy.random.uniform(-1, 1, (2, 3)).astype... | Add attr.gpu decorator to gpu test of dropout | Add attr.gpu decorator to gpu test of dropout
| Python | mit | yanweifu/chainer,hvy/chainer,cupy/cupy,ysekky/chainer,woodshop/complex-chainer,niboshi/chainer,tkerola/chainer,kashif/chainer,kikusu/chainer,jnishi/chainer,okuta/chainer,niboshi/chainer,benob/chainer,chainer/chainer,AlpacaDB/chainer,sou81821/chainer,umitanuki/chainer,tscohen/chainer,cupy/cupy,laysakura/chainer,masia02/... | ---
+++
@@ -6,6 +6,7 @@
from chainer import cuda
from chainer import functions
from chainer import testing
+from chainer.testing import attr
if cuda.available:
@@ -27,6 +28,7 @@
def test_type_forward_cpu(self):
self.check_type_forward(self.x)
+ @attr.gpu
def test_type_forward_gpu(self)... |
45ba5e046a7ab76d54422a41604c7a90794cfd3f | app/handlers/__init__.py | app/handlers/__init__.py | __version__ = "2019.11.1"
__versionfull__ = __version__
| __version__ = "2019.12.0"
__versionfull__ = __version__
| Bump app version to 2019.12.0 | Bump app version to 2019.12.0
Signed-off-by: Guillaume Tucker <e7e20b7c30f19d4ca6b81319ef81bf200369d137@collabora.com>
| Python | lgpl-2.1 | kernelci/kernelci-backend,kernelci/kernelci-backend | ---
+++
@@ -1,2 +1,2 @@
-__version__ = "2019.11.1"
+__version__ = "2019.12.0"
__versionfull__ = __version__ |
f9c1393b9773a5df993a98b877ce5178d44c8575 | common.py | common.py | import os, os.path
base_dir = os.getcwd()
script_dir = os.path.realpath(os.path.dirname(__file__))
def get_crawl_dir():
return os.path.join(base_dir, "crawl")
def revision_present(version, revision):
return os.path.isdir(os.path.join(get_crawl_dir(), version, revision))
| import os, os.path
script_dir = os.path.realpath(os.path.dirname(__file__))
base_dir = script_dir
def get_crawl_dir():
return os.path.join(base_dir, "crawl")
def revision_present(version, revision):
return os.path.isdir(os.path.join(get_crawl_dir(), version, revision))
| Use the script dir as base_dir for now. | Use the script dir as base_dir for now.
| Python | mit | flodiebold/crawl-versions | ---
+++
@@ -1,7 +1,7 @@
import os, os.path
-base_dir = os.getcwd()
script_dir = os.path.realpath(os.path.dirname(__file__))
+base_dir = script_dir
def get_crawl_dir():
return os.path.join(base_dir, "crawl") |
9b4e803f68b33f193f0a41784e2f51672d69c4c2 | benchmarks/numpy-bench.py | benchmarks/numpy-bench.py | # Copyright 2019 Google LLC
#
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file or at
# https://developers.google.com/open-source/licenses/bsd
import time
import numpy as np
import sys
n = int(sys.argv[1])
x = np.random.randn(n,n)
y = np.random.randn(n,n)
t0 = time... | # Copyright 2019 Google LLC
#
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file or at
# https://developers.google.com/open-source/licenses/bsd
import time
import numpy as np
import sys
from __future__ import print_function
n = int(sys.argv[1])
x = np.random.randn(n,... | Make bechmark compatible with python3 | Make bechmark compatible with python3
| Python | bsd-3-clause | google-research/dex-lang,google-research/dex-lang,google-research/dex-lang,google-research/dex-lang,google-research/dex-lang,google-research/dex-lang | ---
+++
@@ -7,6 +7,7 @@
import time
import numpy as np
import sys
+from __future__ import print_function
n = int(sys.argv[1])
@@ -15,4 +16,4 @@
t0 = time.time()
z = np.dot(x, y)
-print "Time for {} by {} matmul: {} s".format(n,n, time.time() - t0)
+print("Time for {} by {} matmul: {} s".format(n,n, time.t... |
5ef45edb38ed5475351d484b89f0e99e5d50ea92 | examples/test-archive.py | examples/test-archive.py | from __future__ import print_function
import unittest
import modfoo
import saliweb.test
import os
class JobTests(saliweb.test.TestCase):
"""Check custom ModFoo Job class"""
def test_archive(self):
"""Test the archive method"""
# Make a ModFoo Job test job in ARCHIVED state
j = self.mak... | from __future__ import print_function
import unittest
import modfoo
import saliweb.test
import os
class JobTests(saliweb.test.TestCase):
"""Check custom ModFoo Job class"""
def test_archive(self):
"""Test the archive method"""
# Make a ModFoo Job test job in ARCHIVED state
j = self.ma... | Use context manager in example | Use context manager in example
| Python | lgpl-2.1 | salilab/saliweb,salilab/saliweb,salilab/saliweb,salilab/saliweb,salilab/saliweb | ---
+++
@@ -3,6 +3,7 @@
import modfoo
import saliweb.test
import os
+
class JobTests(saliweb.test.TestCase):
"""Check custom ModFoo Job class"""
@@ -12,21 +13,22 @@
# Make a ModFoo Job test job in ARCHIVED state
j = self.make_test_job(modfoo.Job, 'ARCHIVED')
# Run the rest of thi... |
169df99132c9f4d0d44a9207184e53537d0688ec | tappy_tests.py | tappy_tests.py | # -*- coding: utf-8 -*-
"""
Tappy Terror Tests
------------------
Tests Tappy Terror
:license: MIT; details in LICENSE
"""
import tappy
import unittest
class TappyTerrorTestCase(unittest.TestCase):
def setUp(self):
tappy.app.config['TESTING'] = True
self.app = tappy.app.test_clie... | # -*- coding: utf-8 -*-
"""
Tappy Terror Tests
------------------
Tests Tappy Terror
:license: MIT; details in LICENSE
"""
import tappy
import unittest
class TappyTerrorWebTestCase(unittest.TestCase):
def setUp(self):
tappy.app.config['TESTING'] = True
self.app = tappy.app.test_c... | Rename test case to be clearly for the web-facing parts of Tappy Terror | Rename test case to be clearly for the web-facing parts of Tappy Terror
| Python | mit | jculpon/tappy-flask,jculpon/tappy-flask | ---
+++
@@ -11,7 +11,7 @@
import tappy
import unittest
-class TappyTerrorTestCase(unittest.TestCase):
+class TappyTerrorWebTestCase(unittest.TestCase):
def setUp(self):
tappy.app.config['TESTING'] = True
self.app = tappy.app.test_client() |
44cec721b7a0a20059c143124a889f8f7a1fe615 | config.py | config.py | ###
# Copyright (c) 2012, spline
# All rights reserved.
#
#
###
import os
import supybot.conf as conf
import supybot.registry as registry
from supybot.i18n import PluginInternationalization, internationalizeDocstring
_ = PluginInternationalization('MLB')
def configure(advanced):
# This will be called by supybot... | ###
# Copyright (c) 2012-2013, spline
# All rights reserved.
#
#
###
import os
import supybot.conf as conf
import supybot.registry as registry
from supybot.i18n import PluginInternationalization, internationalizeDocstring
_ = PluginInternationalization('MLB')
def configure(advanced):
# This will be called by su... | Remove the dbLocation as we do this within plugin.py | Remove the dbLocation as we do this within plugin.py
| Python | mit | reticulatingspline/MLB | ---
+++
@@ -1,5 +1,5 @@
###
-# Copyright (c) 2012, spline
+# Copyright (c) 2012-2013, spline
# All rights reserved.
#
#
@@ -23,9 +23,6 @@
MLB = conf.registerPlugin('MLB')
-# This is where your configuration variables (if any) should go. For example:
-conf.registerGlobalValue(MLB, 'dbLocation', registry.Stri... |
e71caded81851c585dcfd2326f8aa4342d9fbd8b | docs/conf.py | docs/conf.py | AUTHOR = u'Adrian Sampson'
# General configuration
extensions = ['sphinx.ext.autodoc', 'sphinx.ext.extlinks']
exclude_patterns = ['_build']
source_suffix = '.rst'
master_doc = 'index'
project = u'beets'
copyright = u'2012, Adrian Sampson'
version = '1.3'
release = '1.3.11'
pygments_style = 'sphinx'
# External li... | AUTHOR = u'Adrian Sampson'
# General configuration
extensions = ['sphinx.ext.autodoc', 'sphinx.ext.extlinks']
exclude_patterns = ['_build']
source_suffix = '.rst'
master_doc = 'index'
project = u'beets'
copyright = u'2012, Adrian Sampson'
version = '1.3'
release = '1.3.11'
pygments_style = 'sphinx'
# External li... | Update docs' html_theme value: default → classic | Update docs' html_theme value: default → classic
New proposed default is 'alabaster', which looks nice but leaves less
room to the core content. 'classic' replaces 'default'.
Anyway readthedocs.org applies its own theme so this only impacts local
builds.
| Python | mit | mosesfistos1/beetbox,MyTunesFreeMusic/privacy-policy,PierreRust/beets,multikatt/beets,shamangeorge/beets,mathstuf/beets,diego-plan9/beets,ruippeixotog/beets,mathstuf/beets,parapente/beets,gabrielaraujof/beets,YetAnotherNerd/beets,shamangeorge/beets,kareemallen/beets,swt30/beets,marcuskrahl/beets,Dishwishy/beets,sadatay... | ---
+++
@@ -23,7 +23,7 @@
}
# Options for HTML output
-html_theme = 'default'
+html_theme = 'classic'
htmlhelp_basename = 'beetsdoc'
# Options for LaTeX output |
bc05c56c60fa61f045079a4b3ef2dea185b213b4 | fortuitus/fcore/tests.py | fortuitus/fcore/tests.py | from django.core.urlresolvers import reverse
from django.test import TestCase
from fortuitus.fcore.factories import UserF
from fortuitus.fcore.models import FortuitusProfile
class HomeViewTestCase(TestCase):
def test_renders_template(self):
""" Tests is home page is rendered properly. """
respons... | from django.core.urlresolvers import reverse
from django.test import TestCase
from fortuitus.fcore.factories import UserF
from fortuitus.fcore.models import FortuitusProfile
class HomeViewTestCase(TestCase):
def test_renders_template(self):
""" Tests is home page is rendered properly. """
respons... | Fix failing user profile test | Fix failing user profile test
| Python | mit | elegion/djangodash2012,elegion/djangodash2012 | ---
+++
@@ -25,8 +25,8 @@
Tests that second profile is created and not conflicted with the first
user nor his profile.
"""
- u1 = UserF.create()
+ u1 = UserF.create(username='u1')
p1 = FortuitusProfile.objects.get(user_id=u1.pk)
- u2 = UserF.create()
+ u... |
2f44eb65e22672a894cced9c9de8d64f72d0fc39 | pyosmo/algorithm/weighted.py | pyosmo/algorithm/weighted.py | from typing import List
from pyosmo.algorithm.base import OsmoAlgorithm
from pyosmo.history.history import OsmoHistory
from pyosmo.model import TestStep
class WeightedAlgorithm(OsmoAlgorithm):
""" Weighted random algorithm """
def choose(self, history: OsmoHistory, choices: List[TestStep]) -> TestStep:
... | from typing import List
from pyosmo.algorithm.base import OsmoAlgorithm
from pyosmo.history.history import OsmoHistory
from pyosmo.model import TestStep
class WeightedAlgorithm(OsmoAlgorithm):
""" Weighted random algorithm """
def choose(self, history: OsmoHistory, choices: List[TestStep]) -> TestStep:
... | Fix py3.9 check that total weight need to be more than zero | Fix py3.9 check that total weight need to be more than zero
| Python | mit | OPpuolitaival/pyosmo,OPpuolitaival/pyosmo | ---
+++
@@ -26,4 +26,10 @@
history_normalized_weights = [float(i) / max(history_counts) for i in history_counts]
total_weights = [a - b if a - b != 0 else 0.1 for (a, b) in zip(normalized_weights, history_normalized_weights)]
+
+ # Make sure that total weight is more than zero
+ if s... |
c108c418935b2b5ea8ec42696a8d11f97601e552 | qual/calendars/historical.py | qual/calendars/historical.py | from datetime import date
from base import Calendar
from main import JulianCalendar
class JulianToGregorianCalendar(Calendar):
def date(self, year, month, day):
gregorian_date = date(year, month, day)
if gregorian_date < self.first_gregorian_day:
julian_date = JulianCalendar().date(yea... | from datetime import date
from base import Calendar
from main import JulianCalendar
class JulianToGregorianCalendar(Calendar):
def date(self, year, month, day):
gregorian_date = date(year, month, day)
if gregorian_date < self.first_gregorian_day:
julian_date = JulianCalendar().date(yea... | Change the first gregorian date in the English calendar. | Change the first gregorian date in the English calendar.
| Python | apache-2.0 | jwg4/calexicon,jwg4/qual | ---
+++
@@ -16,4 +16,4 @@
date.calendar = self.__class__
class EnglishHistoricalCalendar(JulianToGregorianCalendar):
- first_gregorian_day = date(1752, 9, 14)
+ first_gregorian_day = date(1752, 9, 13) |
7a3325a7fe5c99116587751ae58480b3b83760d1 | bokeh/charts/__init__.py | bokeh/charts/__init__.py | from __future__ import absolute_import
# defaults and constants
from .utils import DEFAULT_PALETTE
from ._chart_options import default_options as defaults
# main components
from ._chart import Chart
# operations and attributes for users to input into Charts
from ._attributes import color
from .operations import stac... | from __future__ import absolute_import
# defaults and constants
from .utils import DEFAULT_PALETTE
from ._chart_options import default_options as defaults
# main components
from ._chart import Chart
# operations and attributes for users to input into Charts
from ._attributes import color, marker
from .operations imp... | Add marker attr spec function to chart import. | Add marker attr spec function to chart import.
| Python | bsd-3-clause | aavanian/bokeh,philippjfr/bokeh,KasperPRasmussen/bokeh,phobson/bokeh,philippjfr/bokeh,ptitjano/bokeh,DuCorey/bokeh,ericmjl/bokeh,ptitjano/bokeh,msarahan/bokeh,justacec/bokeh,maxalbert/bokeh,draperjames/bokeh,timsnyder/bokeh,ChinaQuants/bokeh,KasperPRasmussen/bokeh,jakirkham/bokeh,DuCorey/bokeh,DuCorey/bokeh,dennisobrie... | ---
+++
@@ -8,7 +8,7 @@
from ._chart import Chart
# operations and attributes for users to input into Charts
-from ._attributes import color
+from ._attributes import color, marker
from .operations import stack, blend
# builders |
e949f5cb8ad2a8e8642ce9307cb8eedf3caf1254 | src/pyhmsa/fileformat/xmlhandler/header.py | src/pyhmsa/fileformat/xmlhandler/header.py | #!/usr/bin/env python
"""
================================================================================
:mod:`header` -- XML handler for header
================================================================================
.. module:: header
:synopsis: XML handler for header
.. inheritance-diagram:: header
"... | #!/usr/bin/env python
"""
================================================================================
:mod:`header` -- XML handler for header
================================================================================
.. module:: header
:synopsis: XML handler for header
.. inheritance-diagram:: header
"... | Fix iteration was over whole element instead of only over subelements. | Fix iteration was over whole element instead of only over subelements.
| Python | mit | pyhmsa/pyhmsa | ---
+++
@@ -30,7 +30,7 @@
def parse(self, element):
obj = self._parse_parameter(element, Header)
- for subelement in element.iter():
+ for subelement in element:
name = subelement.tag
if name in obj:
continue # already parsed |
b438e3858910eee4f24a5f33858fb039240750cd | get_data_from_twitter.py | get_data_from_twitter.py | # -*- coding: UTF-8 -*-
import numpy
from tweepy.streaming import StreamListener
from tweepy import OAuthHandler
from tweepy import Stream
import json
import config
#Much of this code comes from http://adilmoujahid.com/posts/2014/07/twitter-analytics/
class StdOutListener(StreamListener):
def on_data(self, data_... | # -*- coding: UTF-8 -*-
import numpy
from tweepy.streaming import StreamListener
from tweepy import OAuthHandler
from tweepy import Stream
import json
import config
#Much of this code comes from http://adilmoujahid.com/posts/2014/07/twitter-analytics/
class StdOutListener(StreamListener):
def on_data(self, data_... | Add support for pulling hash tags | Add support for pulling hash tags
| Python | mpl-2.0 | aDataAlchemist/election-tweets | ---
+++
@@ -14,6 +14,7 @@
data = json.loads(data_str)
if len(data['entities']['urls']) != 0:
newdata = {'created_at' : data['created_at'], 'text' : data['text'],
+ 'hashtags' : [hashtag['text'] for hashtag in data['entities']['hashtags'] ],
'urls' : [url[... |
bb6599477ffe696a5d37a781b33f02f5623dc1a2 | eve_swagger/swagger.py | eve_swagger/swagger.py | # -*- coding: utf-8 -*-
"""
eve-swagger.swagger
~~~~~~~~~~~~~~~~~~~
swagger.io extension for Eve-powered REST APIs.
:copyright: (c) 2015 by Nicola Iarocci.
:license: BSD, see LICENSE for more details.
"""
from collections import OrderedDict
from flask import Blueprint, jsonify
from objects import ... | # -*- coding: utf-8 -*-
"""
eve-swagger.swagger
~~~~~~~~~~~~~~~~~~~
swagger.io extension for Eve-powered REST APIs.
:copyright: (c) 2015 by Nicola Iarocci.
:license: BSD, see LICENSE for more details.
"""
from collections import OrderedDict
from flask import Blueprint, jsonify
from objects import ... | Refactor node() into a closure | Refactor node() into a closure
| Python | bsd-3-clause | nicolaiarocci/eve-swagger | ---
+++
@@ -21,6 +21,10 @@
@swagger.route('/api-docs')
def index():
+ def node(parent, key, value):
+ if value:
+ parent[key] = value
+
root = OrderedDict()
root['swagger'] = '2.0'
node(root, 'info', info())
@@ -39,8 +43,3 @@
node(root, 'externalDocs', external_docs())
... |
5c8cd5be944da9d765f71e62c42e1525736b14a1 | tests/tools.py | tests/tools.py | # coding=utf-8
"""
Test tools required by multiple suites.
"""
import contextlib
import shutil
import subprocess
import tempfile
from devpi_builder import devpi
@contextlib.contextmanager
def devpi_server(port=2414):
server_dir = tempfile.mkdtemp()
try:
subprocess.check_output(['devpi-server', '--s... | # coding=utf-8
"""
Test tools required by multiple suites.
"""
import contextlib
import shutil
import subprocess
import tempfile
from devpi_builder import devpi
@contextlib.contextmanager
def devpi_server(port=2414):
server_dir = tempfile.mkdtemp()
try:
subprocess.check_output(['devpi-server', '--s... | Fix name of index created for tests. | Fix name of index created for tests.
| Python | bsd-3-clause | tylerdave/devpi-builder | ---
+++
@@ -36,7 +36,7 @@
with devpi.Client(server_url) as devpi_client:
devpi_client._execute('user', '-c', user, 'password=' + password)
devpi_client._execute('login', user, '--password=' + password)
- devpi_client._execute('index', '-c', 'wheels', 'bases=')
+ devpi_client._exec... |
d37f9646b13df624f04050a63d34b3d33e9e6e9e | python/matasano/set1/c8.py | python/matasano/set1/c8.py | from matasano.util.converters import hex_to_bytestr
from Crypto.Cipher import AES
if __name__ == "__main__":
chal_file = open("matasano/data/c8.txt", 'r');
for line in chal_file:
ct = hex_to_bytestr(line[:-1])
for i in range(0, len(ct), 16):
for j in range(i+16, len(ct), 16):
... | from matasano.util.converters import hex_to_bytestr
if __name__ == "__main__":
chal_file = open("matasano/data/c8.txt", 'r');
coll_count = {}
for idx, line in enumerate(chal_file):
count = 0
ct = line[:-1]
for i in range(0, len(ct), 32):
for j in range(i+32, len(ct), 3... | Improve the code, return most collisions. Work on hex strings. | Improve the code, return most collisions. Work on hex strings.
| Python | mit | TheLunchtimeAttack/matasano-challenges,TheLunchtimeAttack/matasano-challenges | ---
+++
@@ -1,21 +1,21 @@
from matasano.util.converters import hex_to_bytestr
-from Crypto.Cipher import AES
if __name__ == "__main__":
chal_file = open("matasano/data/c8.txt", 'r');
- for line in chal_file:
- ct = hex_to_bytestr(line[:-1])
- for i in range(0, len(ct), 16):
- ... |
02d1b76067a8c3b2de9abc09cd841fe8b8bd7605 | example/app/integrations/fps_integration.py | example/app/integrations/fps_integration.py | from billing.integrations.amazon_fps_integration import AmazonFpsIntegration as Integration
from django.core.urlresolvers import reverse
import urlparse
class FpsIntegration(Integration):
def transaction(self, request):
"""Ideally at this method, you will check the
caller reference against a user ... | from billing.integrations.amazon_fps_integration import AmazonFpsIntegration as Integration
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect
import urlparse
class FpsIntegration(Integration):
def transaction(self, request):
"""Ideally at this method, you will check ... | Use the HttpResponseRedirect for redirection. | Use the HttpResponseRedirect for redirection.
| Python | bsd-3-clause | biddyweb/merchant,spookylukey/merchant,spookylukey/merchant,digideskio/merchant,mjrulesamrat/merchant,agiliq/merchant,SimpleTax/merchant,mjrulesamrat/merchant,biddyweb/merchant,SimpleTax/merchant,agiliq/merchant,digideskio/merchant | ---
+++
@@ -1,5 +1,6 @@
from billing.integrations.amazon_fps_integration import AmazonFpsIntegration as Integration
from django.core.urlresolvers import reverse
+from django.http import HttpResponseRedirect
import urlparse
class FpsIntegration(Integration):
@@ -16,5 +17,5 @@
query = parsed_url.query
... |
886fac0476d05806c5d396f0740bc24f3fa343ed | rslinac/pkcli/beam_solver.py | rslinac/pkcli/beam_solver.py | import rslinac
def run(ini_filename, input_filename, output_filename):
rslinac.run_beam_solver(ini_filename, input_filename, output_filename)
| import rslinac
from argh import arg
@arg('ini', help='path configuration file in INI format')
@arg('input', help='path to file with input data')
@arg('output', help='path to file to write output data')
def run(ini, input, output):
"""runs the beam solver"""
rslinac.run_beam_solver(ini, input, output)
| Add documentation to cli command arguments | Add documentation to cli command arguments
| Python | apache-2.0 | elventear/rslinac,radiasoft/rslinac,radiasoft/rslinac,elventear/rslinac,elventear/rslinac,radiasoft/rslinac,radiasoft/rslinac,radiasoft/rslinac,elventear/rslinac,elventear/rslinac,elventear/rslinac | ---
+++
@@ -1,4 +1,9 @@
import rslinac
+from argh import arg
-def run(ini_filename, input_filename, output_filename):
- rslinac.run_beam_solver(ini_filename, input_filename, output_filename)
+@arg('ini', help='path configuration file in INI format')
+@arg('input', help='path to file with input data')
+@arg('out... |
077016fbe6ee17c8eb3528b957b05eb4682b8d26 | scrapi/processing/elastic_search.py | scrapi/processing/elastic_search.py | import json
import logging
from elasticsearch import Elasticsearch
from scrapi import settings
from scrapi.processing.base import BaseProcessor
es = Elasticsearch(
settings.ELASTIC_URI,
request_timeout=settings.ELASTIC_TIMEOUT
)
logging.getLogger('elasticsearch').setLevel(logging.WARN)
logging.getLogger('el... | import json
import logging
from elasticsearch import Elasticsearch
from scrapi import settings
from scrapi.processing.base import BaseProcessor
es = Elasticsearch(
settings.ELASTIC_URI,
request_timeout=settings.ELASTIC_TIMEOUT
)
logging.getLogger('elasticsearch').setLevel(logging.WARN)
logging.getLogger('el... | Handle 404s due to index not existing when doing versioning | Handle 404s due to index not existing when doing versioning
| Python | apache-2.0 | jeffreyliu3230/scrapi,ostwald/scrapi,felliott/scrapi,felliott/scrapi,fabianvf/scrapi,erinspace/scrapi,fabianvf/scrapi,erinspace/scrapi,mehanig/scrapi,CenterForOpenScience/scrapi,mehanig/scrapi,icereval/scrapi,alexgarciac/scrapi,CenterForOpenScience/scrapi | ---
+++
@@ -40,13 +40,13 @@
)
def version_dateUpdated(self, normalized):
- old_doc = es.get_source(
- index='share',
- doc_type=normalized['source'],
- id=normalized['id']['serviceID'],
- ignore=[404]
- )
-
- logger.info(json.dumps(old_d... |
646bebdef900869c7a53997d6e9ab79150c0257c | server/apps/webterminal/handlers.py | server/apps/webterminal/handlers.py | import tornado.web
import tornado.escape
import json
import time
import os
import settings as global_settings
from lib.handlers.base import BaseHandler
class EmbedTerminalHandler(BaseHandler):
@tornado.web.authenticated
def get(self):
if not self.get_secure_cookie('gateone_ssl'):
self.s... | import tornado.web
import tornado.escape
import json
import time
import os
import settings as global_settings
from lib.handlers.base import BaseHandler
class EmbedTerminalHandler(BaseHandler):
@tornado.web.authenticated
def get(self):
if not self.get_secure_cookie('gateone_ssl'):
self.s... | Revert previous change to auth timestamp. | Revert previous change to auth timestamp. | Python | mit | SandstoneHPC/sandstone-ide,SandstoneHPC/OIDE,ResearchComputing/OIDE,ResearchComputing/OIDE,SandstoneHPC/OIDE,SandstoneHPC/sandstone-ide,ResearchComputing/OIDE,ResearchComputing/OIDE,SandstoneHPC/sandstone-ide,SandstoneHPC/OIDE | ---
+++
@@ -22,7 +22,7 @@
authobj = {
'api_key': global_settings.TERMINAL_API_KEY,
'upn': self.get_current_user(),
- 'timestamp': str(int(time.time())),
+ 'timestamp': str(int(time.time() * 1000)),
'signature': "",
... |
36288cf5357d58b0989b090965fd231bb01137ed | imager/profiles/tests.py | imager/profiles/tests.py | from django.test import TestCase
import factory
from django.contrib.auth.models import User
from profiles.models import ImagerProfile
class UserFactory(factory.django.DjangoModelFactory):
class Meta:
model = User
django_get_or_create = ('username',)
username = 'john'
class Test_ImagerProfile... | from django.test import TestCase
import factory
from django.contrib.auth.models import User
from profiles.models import ImagerProfile
class UserFactory(factory.django.DjangoModelFactory):
"""Creates a test user not: non permante to db"""
class Meta:
model = User
django_get_or_create = ('userna... | Update docstrings for test file | Update docstrings for test file
| Python | mit | edpark13/django-imager | ---
+++
@@ -5,41 +5,48 @@
class UserFactory(factory.django.DjangoModelFactory):
+ """Creates a test user not: non permante to db"""
class Meta:
model = User
django_get_or_create = ('username',)
username = 'john'
+
class Test_ImagerProfile(TestCase):
def setUp(self):
+ ... |
d142bed6916d8b34509c12623b4802eca9206695 | tests/test_ab_testing.py | tests/test_ab_testing.py | from . import TheInternetTestCase
from helium.api import go_to, S, get_driver
class AbTestingTest(TheInternetTestCase):
def get_page(self):
return "http://the-internet.herokuapp.com/abtest"
def test_ab_variates(self):
variation = S("h3")
first_variation = variation.web_element.text
self.assertIn(
first_va... | from . import TheInternetTestCase
from helium.api import go_to, S, get_driver
class AbTestingTest(TheInternetTestCase):
def get_page(self):
return "http://the-internet.herokuapp.com/abtest"
def test_ab_variates(self):
header = S("h3")
first_variation = header.web_element.text
self.assertIn(
first_variatio... | Make the AB test case more stable. | Make the AB test case more stable.
| Python | mit | bugfree-software/the-internet-solution-python | ---
+++
@@ -5,16 +5,18 @@
def get_page(self):
return "http://the-internet.herokuapp.com/abtest"
def test_ab_variates(self):
- variation = S("h3")
- first_variation = variation.web_element.text
+ header = S("h3")
+ first_variation = header.web_element.text
self.assertIn(
first_variation, [u"A/B Test ... |
3d95a986538dce6476962b46b0075303f2055311 | comics/core/middleware.py | comics/core/middleware.py | import re
from django.utils.html import strip_spaces_between_tags
from django.conf import settings
RE_MULTISPACE = re.compile(r'\s{2,}')
RE_NEWLINE = re.compile(r'\n')
class MinifyHTMLMiddleware(object):
def process_response(self, request, response):
if 'text/html' in response['Content-Type'] and setting... | import re
from django.utils.html import strip_spaces_between_tags
from django.conf import settings
RE_MULTISPACE = re.compile(r'\s{2,}')
RE_NEWLINE = re.compile(r'\n')
class MinifyHTMLMiddleware(object):
def process_response(self, request, response):
if 'text/html' in response['Content-Type'] and setting... | Replace newlines with a single space instead of nothing when minifying HTML | Replace newlines with a single space instead of nothing when minifying HTML
| Python | agpl-3.0 | klette/comics,jodal/comics,jodal/comics,datagutten/comics,klette/comics,klette/comics,datagutten/comics,datagutten/comics,datagutten/comics,jodal/comics,jodal/comics | ---
+++
@@ -11,6 +11,6 @@
if 'text/html' in response['Content-Type'] and settings.COMPRESS_HTML:
response.content = strip_spaces_between_tags(
response.content.strip())
- response.content = RE_MULTISPACE.sub(" ", response.content)
- response.content = RE_NE... |
8a73d31a9bbff831be3e92b73ddb0841e61b3457 | reviewboard/admin/tests.py | reviewboard/admin/tests.py | from django.conf import settings
from django.test import TestCase
from reviewboard.admin import checks
class UpdateTests(TestCase):
"""Tests for update required pages"""
def tearDown(self):
# Make sure we don't break further tests by resetting this fully.
checks.reset_check_cache()
def ... | from django.conf import settings
from django.test import TestCase
from reviewboard.admin import checks
class UpdateTests(TestCase):
"""Tests for update required pages"""
def tearDown(self):
# Make sure we don't break further tests by resetting this fully.
checks.reset_check_cache()
def ... | Fix the media manual updates unit test to account for the new ext dir page. | Fix the media manual updates unit test to account for the new ext dir page.
My previous change for the extension directory manual updates page broke
the unit tests. The existing test for the upload directory didn't take
into account that the extension directory would also now be needed. The
test was fixed and renamed ... | Python | mit | brennie/reviewboard,beol/reviewboard,sgallagher/reviewboard,custode/reviewboard,1tush/reviewboard,atagar/ReviewBoard,beol/reviewboard,1tush/reviewboard,davidt/reviewboard,brennie/reviewboard,1tush/reviewboard,Khan/reviewboard,davidt/reviewboard,1tush/reviewboard,Khan/reviewboard,atagar/ReviewBoard,custode/reviewboard,a... | ---
+++
@@ -20,8 +20,8 @@
self.assertEqual(len(updates_required), 0)
- def testManualUpdatesRequiredBadUpload(self):
- """Testing check_updates_required with a bad upload directory"""
+ def testManualUpdatesRequiredBadMediaDirs(self):
+ """Testing check_updates_required with bad media... |
8940d3805f9377654046ff8b00807472b6925149 | lib/setup.py | lib/setup.py | # --------------------------------------------------------
# Fast R-CNN
# Copyright (c) 2015 Microsoft
# Licensed under The MIT License [see LICENSE for details]
# Written by Ross Girshick
# --------------------------------------------------------
import numpy as np
from distutils.core import setup
from distutils.exte... | # --------------------------------------------------------
# Fast R-CNN
# Copyright (c) 2015 Microsoft
# Licensed under The MIT License [see LICENSE for details]
# Written by Ross Girshick
# --------------------------------------------------------
import numpy as np
from distutils.core import setup
from distutils.exte... | Comment compilation options for Windows. | Comment compilation options for Windows. | Python | mit | only4hj/fast-rcnn,only4hj/fast-rcnn,only4hj/fast-rcnn | ---
+++
@@ -15,12 +15,12 @@
Extension(
"utils.cython_bbox",
["utils/bbox.pyx"],
- extra_compile_args=["-Wno-cpp", "-Wno-unused-function"],
+ #extra_compile_args=["-Wno-cpp", "-Wno-unused-function"],
),
Extension(
"utils.cython_nms",
["utils/nms.pyx"],
-... |
4753a6d19d00f9669e864f92730d56aaf31575da | 1-multiples-of-3-and-5.py | 1-multiples-of-3-and-5.py | from itertools import chain
def threes_and_fives_gen(num=1000):
for i in range(num):
if i % 3 == 0 or i % 5 == 0:
yield i
def threes_and_fives_fun(n):
return set(chain(range(3, n+1, 3), range(5, n+1, 5)))
if __name__ == '__main__':
print(sum(threes_and_fives_gen(10000000)))
| from itertools import chain
def threes_and_fives_gen(num=1000):
for i in range(num):
if i % 3 == 0 or i % 5 == 0:
yield i
def threes_and_fives_fun(n):
return set(chain(range(3, n+1, 3), range(5, n+1, 5)))
def solve(n):
return sum(
filter(lambda x: x%3==0 or x%5==0,
... | Add functional solution to 1 | Add functional solution to 1
| Python | mit | dawran6/project-euler | ---
+++
@@ -8,5 +8,12 @@
def threes_and_fives_fun(n):
return set(chain(range(3, n+1, 3), range(5, n+1, 5)))
+def solve(n):
+ return sum(
+ filter(lambda x: x%3==0 or x%5==0,
+ range(1, n)
+ )
+ )
+
if __name__ == '__main__':
- print(sum(threes_and_fives_gen(10000000)))
+ ... |
80503c24854e976fa4bc86319f6c11dc3a5186b2 | test/test_property.py | test/test_property.py | import unittest
from odml import Property, Section, Document
class TestProperty(unittest.TestCase):
def setUp(self):
pass
def test_value(self):
p = Property("property", 100)
assert(p.value[0] == 100)
def test_name(self):
pass
def test_parent(self):
pass
... | import unittest
from odml import Property, Section, Document, DType
class TestProperty(unittest.TestCase):
def setUp(self):
pass
def test_value(self):
p = Property("property", 100)
assert(p.value[0] == 100)
def test_bool_conversion(self):
p = Property(name='received', v... | Add tests for boolean conversion | Add tests for boolean conversion
| Python | bsd-3-clause | lzehl/python-odml | ---
+++
@@ -1,5 +1,5 @@
import unittest
-from odml import Property, Section, Document
+from odml import Property, Section, Document, DType
class TestProperty(unittest.TestCase):
@@ -10,6 +10,21 @@
def test_value(self):
p = Property("property", 100)
assert(p.value[0] == 100)
+
+ def tes... |
f2005fadb9fb2e2bcad32286a9d993c291c1992e | lazyblacksmith/models/api/industry_index.py | lazyblacksmith/models/api/industry_index.py | # -*- encoding: utf-8 -*-
from . import db
from lazyblacksmith.models import Activity
class IndustryIndex(db.Model):
solarsystem_id = db.Column(
db.Integer, db.ForeignKey('solar_system.id'), primary_key=True
)
solarsystem = db.relationship('SolarSystem', backref=db.backref('indexes'))
activi... | # -*- encoding: utf-8 -*-
from . import db
from lazyblacksmith.models import Activity
class IndustryIndex(db.Model):
solarsystem_id = db.Column(
db.Integer, db.ForeignKey('solar_system.id'), primary_key=True
)
solarsystem = db.relationship('SolarSystem', backref=db.backref('indexes'))
activi... | Fix celery task for industry indexes by adding missing field | Fix celery task for industry indexes by adding missing field
| Python | bsd-3-clause | Kyria/LazyBlacksmith,Kyria/LazyBlacksmith,Kyria/LazyBlacksmith,Kyria/LazyBlacksmith | ---
+++
@@ -32,3 +32,5 @@
return Activity.RESEARCH_MATERIAL_EFFICIENCY
if activity_string == 'copying':
return Activity.COPYING
+ if activity_string == 'reaction':
+ return Activity.REACTIONS |
874a6eff186d1c1ca6f90d69fd24fad11180c5a9 | thread_output_ctrl.py | thread_output_ctrl.py | import threading
import wx
from styled_text_ctrl import StyledTextCtrl
class ThreadOutputCtrl(StyledTextCtrl):
def __init__(self, parent, env, auto_scroll=False):
StyledTextCtrl.__init__(self, parent, env)
self.auto_scroll = auto_scroll
self.__lock = threading.Lock()
self.__queue ... | import threading
import wx
from styled_text_ctrl import StyledTextCtrl
class ThreadOutputCtrl(StyledTextCtrl):
def __init__(self, parent, env, auto_scroll=False):
StyledTextCtrl.__init__(self, parent, env)
self.auto_scroll = auto_scroll
self.__lock = threading.Lock()
self.__queue ... | Clear undo buffer when terminal cleared. | Clear undo buffer when terminal cleared.
| Python | mit | shaurz/devo | ---
+++
@@ -44,3 +44,4 @@
def ClearAll(self):
with self.ModifyReadOnly():
StyledTextCtrl.ClearAll(self)
+ self.EmptyUndoBuffer() |
53080f89af51340b0b2c1854e0a4bf38346c14a8 | kill.py | kill.py | #!/usr/bin/env python2
return 1
| #!/usr/bin/env python2
from datetime import datetime, timedelta
from json import loads
import sys
if len(sys.argv) < 2:
raise Exception("Need an amount of keep-days of which to save your comments.")
days = int(sys.argv[1])
before_time = datetime.now() - timedelta(days=days)
f = open('data.json', 'r')
data = lo... | Work out now() - 7 days | Work out now() - 7 days
| Python | bsd-2-clause | bparafina/Shreddit,bparafina/Shreddit,ijkilchenko/Shreddit,ijkilchenko/Shreddit | ---
+++
@@ -1,3 +1,21 @@
#!/usr/bin/env python2
-return 1
+from datetime import datetime, timedelta
+from json import loads
+import sys
+
+if len(sys.argv) < 2:
+ raise Exception("Need an amount of keep-days of which to save your comments.")
+
+days = int(sys.argv[1])
+
+before_time = datetime.now() - timedelta... |
6047cab9c099c8a6740b7de1006f41e7d10f9f65 | jal_stats/stats/views.py | jal_stats/stats/views.py | # from django.shortcuts import render
from rest_framework import viewsets
from .models import Datapoint, Activity
from .serializers import ActivitySerializer, DatapointSerializer
# Create your views here.
class ActivityViewSet(viewsets.ModelViewSet):
queryset = Activity.objects.all()
serializer_class = Activ... | # from django.shortcuts import render
from rest_framework import viewsets
from .models import Datapoint, Activity
from .serializers import ActivitySerializer, DatapointSerializer
# Create your views here.
class ActivityViewSet(viewsets.ModelViewSet):
queryset = Activity.objects.all()
serializer_class = Activ... | Remove more remnants of users | Remove more remnants of users
| Python | mit | jal-stats/django | ---
+++
@@ -10,8 +10,8 @@
queryset = Activity.objects.all()
serializer_class = ActivitySerializer
- def get_queryset(self):
- return self.request.user.activity_set.all()
+ # def get_queryset(self):
+ # return self.request.user.activity_set.all()
class DatapointViewSet(viewsets.Mod... |
9d3889a67ff6de69cd539b688cf3c2b9db17f0cb | jarn/mkrelease/python.py | jarn/mkrelease/python.py | from process import Process
from exit import err_exit
class Python(object):
"""A Python interpreter path that can test itself."""
def __init__(self, defaults, process=None):
self.process = process or Process()
self.python = defaults.python
def __str__(self):
return self.python
... | import sys
from process import Process
from exit import err_exit
class Python(object):
"""A Python interpreter path that can test itself."""
def __init__(self, defaults, process=None):
self.process = process or Process()
self.python = defaults.python
def __str__(self):
return se... | Optimize the common case to reduce startup time. | Optimize the common case to reduce startup time.
| Python | bsd-2-clause | Jarn/jarn.mkrelease | ---
+++
@@ -1,3 +1,5 @@
+import sys
+
from process import Process
from exit import err_exit
@@ -28,6 +30,8 @@
def get_python_version(self, python=None):
if python is None:
python = self.python
+ if python == sys.executable:
+ return sys.version[:3]
version = s... |
72f8249cb26ad38e77ac74a7d149839fb3a1cf95 | utils/swift_build_support/swift_build_support/diagnostics.py | utils/swift_build_support/swift_build_support/diagnostics.py | # swift_build_support/diagnostics.py - Diagnostic Utilities -*- python -*-
#
# This source file is part of the Swift.org open source project
#
# Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
# Licensed under Apache License v2.0 with Runtime Library Exception
#
# See https://swift.org/LICENSE.tx... | # swift_build_support/diagnostics.py - Diagnostic Utilities -*- python -*-
#
# This source file is part of the Swift.org open source project
#
# Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
# Licensed under Apache License v2.0 with Runtime Library Exception
#
# See https://swift.org/LICENSE.tx... | Print build-script notes to stderr | Print build-script notes to stderr
This makes it easier to ignore them programmatically.
| Python | apache-2.0 | xwu/swift,aschwaighofer/swift,karwa/swift,sschiau/swift,shajrawi/swift,airspeedswift/swift,hooman/swift,devincoughlin/swift,stephentyrone/swift,jmgc/swift,rudkx/swift,rudkx/swift,xwu/swift,allevato/swift,xedin/swift,allevato/swift,apple/swift,benlangmuir/swift,atrick/swift,parkera/swift,tkremenek/swift,hooman/swift,nat... | ---
+++
@@ -19,10 +19,10 @@
"""
note(message)
- Print a diagnostic notification to the standard output.
+ Print a diagnostic notification to the standard error stream.
"""
- print(sys.argv[0] + ": note: " + message)
- sys.stdout.flush()
+ print(sys.argv[0] + ": note: " + message, file=... |
bceaa1ef82004076640381619ebc399513e83128 | genes/intellij/main.py | genes/intellij/main.py | from genes.brew import commands as brew
from genes.curl.commands import download
from genes.debian.traits import is_debian
from genes.directory import DirectoryBuilder
from genes.mac.traits import is_osx
from genes.tar.commands import untar
from genes.ubuntu.traits import is_ubuntu
def main():
if is_debian() or i... | from genes.brew import commands as brew
from genes.curl.commands import download
from genes.debian.traits import is_debian
from genes import directory
from genes.directory import DirectoryConfig
from genes.mac.traits import is_osx
from genes.tar.commands import untar
from genes.ubuntu.traits import is_ubuntu
def main... | Change to directory config method | Change to directory config method | Python | mit | hatchery/Genepool2,hatchery/genepool | ---
+++
@@ -1,7 +1,8 @@
from genes.brew import commands as brew
from genes.curl.commands import download
from genes.debian.traits import is_debian
-from genes.directory import DirectoryBuilder
+from genes import directory
+from genes.directory import DirectoryConfig
from genes.mac.traits import is_osx
from genes... |
029bd1c15a489ab8833ffaff5130995bf4d31c5a | tests/test_auth.py | tests/test_auth.py | # -*- coding: utf-8 *-*
import logging
import unittest
from mongolog import MongoHandler
try:
from pymongo import MongoClient as Connection
except ImportError:
from pymongo import Connection
class TestAuth(unittest.TestCase):
def setUp(self):
""" Create an empty database that could be used for ... | # -*- coding: utf-8 *-*
import logging
import unittest
from mongolog import MongoHandler
try:
from pymongo import MongoClient as Connection
except ImportError:
from pymongo import Connection
class TestAuth(unittest.TestCase):
def setUp(self):
""" Create an empty database that could be used for ... | Add roles argument for createUser command. | Add roles argument for createUser command.
| Python | bsd-2-clause | puentesarrin/mongodb-log,puentesarrin/mongodb-log | ---
+++
@@ -27,7 +27,8 @@
self.db.command(
'createUser',
self.user_name,
- pwd=self.password
+ pwd=self.password,
+ roles=["readWrite"]
)
def tearDown(self): |
ff12421cc6c3067bac11ece75cf4a16d11859ed0 | tests/test_envs.py | tests/test_envs.py | import gym
import pytest
# Import for side-effect of registering environment
import imitation.examples.airl_envs # noqa: F401
import imitation.examples.model_envs # noqa: F401
ENV_NAMES = [env_spec.id for env_spec in gym.envs.registration.registry.all()
if env_spec.id.startswith('imitation/')]
@pytes... | import gym
import pytest
# Import for side-effect of registering environment
import imitation.examples.airl_envs # noqa: F401
import imitation.examples.model_envs # noqa: F401
ENV_NAMES = [env_spec.id for env_spec in gym.envs.registration.registry.all()
if env_spec.id.startswith('imitation/')]
@pytes... | Move the pragma: nocover to except block | Move the pragma: nocover to except block
| Python | mit | HumanCompatibleAI/imitation,humancompatibleai/imitation,humancompatibleai/imitation,HumanCompatibleAI/imitation | ---
+++
@@ -10,11 +10,11 @@
@pytest.mark.parametrize("env_name", ENV_NAMES)
-def test_envs(env_name): # pragma: no cover
+def test_envs(env_name):
"""Check that our custom environments don't crash on `step`, and `reset`."""
try:
env = gym.make(env_name)
- except gym.error.DependencyNotInstalled as e... |
011ad6090e183ce359c0a74bbd2f2530e1d5178c | tests/test_repr.py | tests/test_repr.py | """ Test __str__ methods. """
import pexpect
from . import PexpectTestCase
class TestCaseMisc(PexpectTestCase.PexpectTestCase):
def test_str_spawnu(self):
""" Exercise spawnu.__str__() """
# given,
p = pexpect.spawnu('cat')
# exercise,
value = str(p)
# verify
... | """ Test __str__ methods. """
import pexpect
from . import PexpectTestCase
class TestCaseMisc(PexpectTestCase.PexpectTestCase):
def test_str_spawnu(self):
""" Exercise spawnu.__str__() """
# given,
p = pexpect.spawnu('cat')
# exercise,
value = str(p)
# verify
... | Check error repr can be str-ed | Check error repr can be str-ed
| Python | isc | nodish/pexpect,nodish/pexpect,nodish/pexpect | ---
+++
@@ -31,7 +31,7 @@
child.read_nonblocking = lambda size, timeout: b''
try:
child.expect('alpha', timeout=0.1)
- except pexpect.TIMEOUT:
- pass
+ except pexpect.TIMEOUT as e:
+ str(e) # Smoketest
else:
- assert False, 'TIMEO... |
2234cbdc78e81329c4110f4eb4e69f429d9b6fb5 | csvkit/convert/dbase.py | csvkit/convert/dbase.py | #!/usr/bin/env python
from cStringIO import StringIO
import dbf
from csvkit import table
def dbf2csv(f, **kwargs):
"""
Convert a dBASE .dbf file to csv.
"""
db = dbf.Table(f.name)
headers = db.field_names
column_ids = range(len(headers))
data_columns = [[] for c in headers]
for ... | #!/usr/bin/env python
from cStringIO import StringIO
import dbf
from csvkit import table
def dbf2csv(f, **kwargs):
"""
Convert a dBASE .dbf file to csv.
"""
with dbf.Table(f.name) as db:
headers = db.field_names
column_ids = range(len(headers))
data_columns = [[] for c in h... | Fix for bug in latest dbf module. Pypy passes now. | Fix for bug in latest dbf module. Pypy passes now.
| Python | mit | bradparks/csvkit__query_join_filter_CSV_cli,matterker/csvkit,unpingco/csvkit,kyeoh/csvkit,Jobava/csvkit,snuggles08/csvkit,dannguyen/csvkit,cypreess/csvkit,jpalvarezf/csvkit,archaeogeek/csvkit,gepuro/csvkit,haginara/csvkit,barentsen/csvkit,bmispelon/csvkit,wjr1985/csvkit,KarrieK/csvkit,onyxfish/csvkit,wireservice/csvkit... | ---
+++
@@ -9,35 +9,33 @@
def dbf2csv(f, **kwargs):
"""
Convert a dBASE .dbf file to csv.
+ """
+ with dbf.Table(f.name) as db:
+ headers = db.field_names
- """
- db = dbf.Table(f.name)
+ column_ids = range(len(headers))
- headers = db.field_names
+ data_columns = [[... |
61072f0054abcb50caa813fc35eff194be64727b | src/icecast_parser.py | src/icecast_parser.py | from bs4 import BeautifulSoup
from requests.auth import HTTPBasicAuth
import requests
import json
def parse_content():
rs = requests.get('http://soundspectra.com/admin/', auth=HTTPBasicAuth('admin', 'h@ckm3'))
html_data = rs.text
soup = BeautifulSoup(html_data)
details = {'stream_details' : []}
... | from bs4 import BeautifulSoup
from requests.auth import HTTPBasicAuth
import requests
import json
def parse_content():
rs = requests.get('http://soundspectra.com/admin/', auth=HTTPBasicAuth('admin', 'h@ckm3'))
html_data = rs.text
soup = BeautifulSoup(html_data)
details = {'stream_details' : []}
... | Return the json from the parser method | Return the json from the parser method
| Python | apache-2.0 | ekholabs/icecast_scraper | ---
+++
@@ -29,7 +29,8 @@
details_list.append(d)
details['stream_details'] = details_list
- print details
+ return details
if __name__ == '__main__':
- parse_content()
+ details = parse_content()
+ print details |
4eff72987144a31ca1dee922a755adc8a5efefb8 | linter.py | linter.py | #
# linter.py
# Linter for SublimeLinter4, a code checking framework for Sublime Text 3
#
# Written by Markus Liljedahl
# Copyright (c) 2017 Markus Liljedahl
#
# License: MIT
#
"""This module exports the AnsibleLint plugin class."""
from SublimeLinter.lint import Linter, util
class AnsibleLint(Linter):
"""Provi... | #
# linter.py
# Linter for SublimeLinter4, a code checking framework for Sublime Text 3
#
# Written by Markus Liljedahl
# Copyright (c) 2017 Markus Liljedahl
#
# License: MIT
#
"""This module exports the AnsibleLint plugin class."""
from SublimeLinter.lint import Linter, util
class AnsibleLint(Linter):
"""Provi... | Replace @ with , otherwise there is blank output from ansible-lint | Replace @ with , otherwise there is blank output from ansible-lint
| Python | mit | mliljedahl/SublimeLinter-contrib-ansible-lint | ---
+++
@@ -22,7 +22,7 @@
version_requirement = '>= 3.0.1'
# linter settings
- cmd = ('ansible-lint', '${args}', '@')
+ cmd = ('ansible-lint', '${args}', '${file}')
regex = r'^.+:(?P<line>\d+): \[.(?P<error>.+)\] (?P<message>.+)'
# -p generate non-multi-line, pep8 compatible output
mu... |
b3e892f476c743a6ed2e2518fd1c9c2bec4d56ae | invocations/testing.py | invocations/testing.py | from invoke import ctask as task
@task(help={
'module': "Just runs tests/STRING.py.",
'runner': "Use STRING to run tests instead of 'spec'.",
'opts': "Extra flags for the test runner",
'pty': "Whether to run tests under a pseudo-tty",
})
def test(c, module=None, runner=None, opts=None, pty=True):
... | from invoke import ctask as task
@task(help={
'module': "Just runs tests/STRING.py.",
'runner': "Use STRING to run tests instead of 'spec'.",
'opts': "Extra flags for the test runner",
'pty': "Whether to run tests under a pseudo-tty",
})
def test(c, module=None, runner=None, opts=None, pty=True):
... | Use spec 1.1 --with-timing option | Use spec 1.1 --with-timing option
| Python | bsd-2-clause | mrjmad/invocations,singingwolfboy/invocations,pyinvoke/invocations | ---
+++
@@ -17,5 +17,7 @@
args = (specific_module if module else "")
if opts:
args += " " + opts
+ # Always enable timing info by default. OPINIONATED
+ args += " --with-timing"
# Use pty by default so the spec/nose/Python process buffers "correctly"
c.run(runner + args, pty=pty) |
f495ecb5f9131c2c13c41e78cc3fc2e182bdc8fc | hotline/db/db_redis.py | hotline/db/db_redis.py | import os
import redis
from urllib.parse import urlparse
redis_url = os.environ.get('REDISCLOUD_URL', 'redis://localhost:6379')
redis_url_parse = urlparse(redis_url)
redis_client = redis.StrictRedis(host=redis_url_parse.hostname, port=redis_url_parse.port)
| from db.db_abstract import AbstractClient
from redis import StrictRedis
from urllib.parse import urlparse
class RedisClient(AbstractClient):
def __init__(self, url):
self.url = url
self.client = None
def connect(self):
redis_url = urlparse(self.url)
self.client = StrictRedis(h... | Update to inherit from abstract class | Update to inherit from abstract class
| Python | mit | wearhacks/hackathon_hotline | ---
+++
@@ -1,10 +1,25 @@
-import os
-import redis
-
+from db.db_abstract import AbstractClient
+from redis import StrictRedis
from urllib.parse import urlparse
-redis_url = os.environ.get('REDISCLOUD_URL', 'redis://localhost:6379')
-redis_url_parse = urlparse(redis_url)
-redis_client = redis.StrictRedis(host=red... |
71b72c3f09af86da83a027502d28c9649db1cf86 | kai/controllers/tracs.py | kai/controllers/tracs.py | import logging
from pylons import config, tmpl_context as c
from pylons.controllers.util import abort
# Conditionally import the trac components in case things trac isn't installed
try:
import os
os.environ['TRAC_ENV_PARENT_DIR'] = '/usr/local/www'
os.environ['PYTHON_EGG_CACHE'] = os.path.join(config['pyl... | import logging
from pylons import config, tmpl_context as c
from pylons.controllers.util import abort
# Monkey patch the lazywriter, since mercurial needs that on the stdout
import paste.script.serve as serve
serve.LazyWriter.closed = False
# Conditionally import the trac components in case things trac isn't install... | Add monkey patch for mercurial trac | Add monkey patch for mercurial trac
| Python | bsd-3-clause | Pylons/kai,Pylons/kai | ---
+++
@@ -2,6 +2,10 @@
from pylons import config, tmpl_context as c
from pylons.controllers.util import abort
+
+# Monkey patch the lazywriter, since mercurial needs that on the stdout
+import paste.script.serve as serve
+serve.LazyWriter.closed = False
# Conditionally import the trac components in case thin... |
48213f561c802e5279770cc833a9a5a68575bf72 | inventory.py | inventory.py | from flask import Flask, render_template, url_for, redirect
from flask import session, escape, request
from peewee import *
#from datetime import date
app = Flask(__name__)
# http://docs.peewee-orm.com/en/latest/peewee/quickstart.html
database = SqliteDatabase('developmentData.db')
#class Device(Model):
# idNumber = ... | from flask import Flask, render_template, url_for, redirect
from flask import session, escape, request
from peewee import *
#from datetime import date
app = Flask(__name__)
# http://docs.peewee-orm.com/en/latest/peewee/quickstart.html
database = SqliteDatabase('developmentData.db')
#class Device(Model):
# idNumber = ... | Add debug code to test login post | Add debug code to test login post
| Python | mit | lcdi/Inventory,lcdi/Inventory,lcdi/Inventory,lcdi/Inventory | ---
+++
@@ -26,8 +26,8 @@
@app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
- session['username'] = request.form['username']
- return redirect(url_for('index'))
+ #session['username'] = request.form['username']
+ return "success"#redirect(url_for('index'))
return render... |
82d5276b6c9164e4b8bffe74dc3068ed3e6a967e | main.py | main.py | from jsonrpc import JSONRPCResponseManager
from funcs import d
def app(environ, start_response):
if 'POST'!=environ.get('REQUEST_METHOD'):
if 'OPTIONS'==environ.get('REQUEST_METHOD'):
start_response('200 OK',[('Access-Control-Allow-Origin','*'), ('Access-Control-Allow-Methods', 'POST')])
... | from jsonrpc import JSONRPCResponseManager
from funcs import d
def app(environ, start_response):
if 'POST'!=environ.get('REQUEST_METHOD'):
if 'OPTIONS'==environ.get('REQUEST_METHOD'):
start_response('200 OK',[
('Access-Control-Allow-Origin','*'),
('Access-Control... | Add allowed headers to preflight response. | Add allowed headers to preflight response. | Python | mit | 1stop-st/jsonrpc-calculator | ---
+++
@@ -4,7 +4,10 @@
def app(environ, start_response):
if 'POST'!=environ.get('REQUEST_METHOD'):
if 'OPTIONS'==environ.get('REQUEST_METHOD'):
- start_response('200 OK',[('Access-Control-Allow-Origin','*'), ('Access-Control-Allow-Methods', 'POST')])
+ start_response('200 OK',[
... |
793332d42c6568a79b321a1474f7aca6834e082e | main.py | main.py | #!/usr/bin/env python3
from flask import Flask
from flask import request
from flask import jsonify
from utils import download_file, create_temp_dir, zip_up_dir, delete_dir
from annotations import sort_annotations_by_time
from videoeditor import bake_annotations
app = Flask(__name__)
@app.route("/", methods=["POST"]... | #!/usr/bin/env python3
from flask import Flask
from flask import request
from flask import jsonify
from utils import download_file, create_temp_dir, zip_up_dir, delete_dir
from annotations import sort_annotations_by_time
from videoeditor import bake_annotations
app = Flask(__name__)
@app.route("/", methods=["POST"]... | Fix typo in output json message | Fix typo in output json message
| Python | mit | melonmanchan/achso-video-exporter,melonmanchan/achso-video-exporter | ---
+++
@@ -31,8 +31,7 @@
zip_up_dir(export_dir_name, 'video-exports/' + video_json["title"])
delete_dir(export_dir_name)
-
- return jsonify({"message": "Annotated video created succesfully"})
+ return jsonify({"message": "Annotated video created successfully"})
if __name__ == "__main__":... |
dcdfd994f1ab79a5fd8e50e7bf478100211a77aa | oscar_vat_moss/checkout/session.py | oscar_vat_moss/checkout/session.py | from django.core.urlresolvers import reverse
from django.utils.translation import ugettext_lazy as _
from oscar.apps.checkout import session, exceptions
from oscar_vat_moss import vat
class CheckoutSessionMixin(session.CheckoutSessionMixin):
def build_submission(self, **kwargs):
submission = super(Checko... | from django.core.urlresolvers import reverse
from django.utils.translation import ugettext_lazy as _
from oscar.apps.checkout import session, exceptions
from oscar_vat_moss import vat
class CheckoutSessionMixin(session.CheckoutSessionMixin):
def build_submission(self, **kwargs):
submission = super(Checko... | Add a "valid shipping address check" to account for VAT discrepancies | Add a "valid shipping address check" to account for VAT discrepancies
If we get a phone number and a city/country combination that yield
incompatible VAT results, we need to flag this to the user. The best
place to do this is, ironically, the shipping address check.
| Python | bsd-3-clause | hastexo/django-oscar-vat_moss,fghaas/django-oscar-vat_moss,arbrandes/django-oscar-vat_moss,fghaas/django-oscar-vat_moss,hastexo/django-oscar-vat_moss,arbrandes/django-oscar-vat_moss | ---
+++
@@ -27,6 +27,19 @@
submission['basket'], submission['shipping_charge'])
return submission
+ def check_a_valid_shipping_address_is_captured(self):
+ super(CheckoutSessionMixin, self)
+ shipping_address = self.get_shipping_address(
+ basket=self.request.ba... |
6fafe0e2d10229ac68fd5bc7857b938d7cd5b212 | wafer/talks/models.py | wafer/talks/models.py | from django.utils.translation import ugettext_lazy as _
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
from django.db import models
# constants to make things clearer elsewhere
ACCEPTED = 'A'
PENDING = 'P'
REJECTED = 'R'
class Talk(models.Model):
TALK_STATUS = (
... | from django.utils.translation import ugettext_lazy as _
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
from django.db import models
from wafer.snippets.markdown_field import MarkdownTextField
# constants to make things clearer elsewhere
ACCEPTED = 'A'
PENDING = 'P'
REJECTED ... | Make the abstract a Markdown field | Make the abstract a Markdown field
| Python | isc | CarlFK/wafer,CTPUG/wafer,CarlFK/wafer,CTPUG/wafer,CTPUG/wafer,CTPUG/wafer,CarlFK/wafer,CarlFK/wafer | ---
+++
@@ -2,6 +2,8 @@
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
from django.db import models
+
+from wafer.snippets.markdown_field import MarkdownTextField
# constants to make things clearer elsewhere
@@ -22,7 +24,7 @@
title = models.CharField(max_length... |
42d667c0478b5b500d765e3d70cc03ec7e7d84d3 | main.py | main.py | #!/usr/bin/env python3
from time import sleep
from utils.mqtt import publish
from weather import Weather
w = Weather()
while True:
publish(w.basics(),"stormfly")
sleep(600)
| #!/usr/bin/env python3
from time import sleep
from utils.mqtt import publish
from weather import Weather
w = Weather()
while True:
publish(w.basics(),"stormfly")
sleep(600)
w.refresh()
| FIX refresh data when running in loop | FIX refresh data when running in loop
| Python | mit | paulfantom/AGH-weather-mqtt | ---
+++
@@ -9,3 +9,4 @@
while True:
publish(w.basics(),"stormfly")
sleep(600)
+ w.refresh() |
d6e5b3835c7779a3fde7be7004b3d4975c4b9f1a | xbob/core/__init__.py | xbob/core/__init__.py | from ._convert import convert
from . import log
from . import random
from . import version
from .version import module as __version__
from .version import api as __api_version__
def get_include():
"""Returns the directory containing the C/C++ API include directives"""
return __import__('pkg_resources').resource_f... | from ._convert import convert
from . import log
from . import random
from . import version
from .version import module as __version__
from .version import api as __api_version__
def get_include():
"""Returns the directory containing the C/C++ API include directives"""
return __import__('pkg_resources').resource_f... | Add API number in get_config() | Add API number in get_config()
| Python | bsd-3-clause | tiagofrepereira2012/bob.core,tiagofrepereira2012/bob.core,tiagofrepereira2012/bob.core | ---
+++
@@ -21,7 +21,8 @@
this = packages[0]
deps = packages[1:]
- retval = "%s: %s (%s)\n" % (this.key, this.version, this.location)
+ retval = "%s: %s [api=0x%04x] (%s)\n" % (this.key, this.version,
+ version.api, this.location)
retval += " - c/c++ dependencies:\n"
for k in sorted(externals)... |
5d40ec75cd27e3bf9c5fad2a921db84f0b5d672d | linked_accounts/utils.py | linked_accounts/utils.py | from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from django.utils.importlib import import_module
from linked_accounts import LINKED_ACCOUNTS_HANDLERS
HANDLERS = getattr(
settings,
'LINKED_ACCOUNTS_HANDLERS',
LINKED_ACCOUNTS_HANDLERS
)
def get_profile(service=Non... | from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from django.utils.importlib import import_module
from linked_accounts import LINKED_ACCOUNTS_HANDLERS
HANDLERS = getattr(
settings,
'LINKED_ACCOUNTS_HANDLERS',
LINKED_ACCOUNTS_HANDLERS
)
def get_profile(service=Non... | Return profile from get_profile view instead of user | Return profile from get_profile view instead of user
| Python | mit | zen4ever/django-linked-accounts,zen4ever/django-linked-accounts | ---
+++
@@ -19,6 +19,6 @@
handler_class = getattr(import_module(module), handler)
handler = handler_class()
profile = handler.get_profile(token)
- return profile.user
+ return profile
else:
raise ImproperlyConfigured('No handler for service %s' % service) |
693f4f52bfed6d25fc32504fcfc8a57e466533a0 | list/list.py | list/list.py | #!/usr/local/bin/python
#a=[1,2,3,4,5,6,7,8,9,10]
#print a[:3]
#print a[-3:]
#print a[:]
#print a[::2]
#print a[8:3:-1]
#print [1,2,3]+[4,5,6]
#print ["Hi"]*3
#print 1 in a
#print max(a)
#print min(a)
#print len(a)
#print list("Hello")
#b=[1,3,5,7,9,8]
#b[1]=4
#print b
#del b[1]
#print b
c=list("Perl")
c[1:1]=list('yth... | #!/usr/local/bin/python
#a=[1,2,3,4,5,6,7,8,9,10]
#print a[:3]
#print a[-3:]
#print a[:]
#print a[::2]
#print a[8:3:-1]
#print [1,2,3]+[4,5,6]
#print ["Hi"]*3
#print 1 in a
#print max(a)
#print min(a)
#print len(a)
#print list("Hello")
#b=[1,3,5,7,9,8]
#b[1]=4
#print b
#del b[1]
#print b
#c=list("Perl")
#c[1:1]=list('y... | Use sort,pop,remove and so on. | Use sort,pop,remove and so on.
| Python | apache-2.0 | Vayne-Lover/Python | ---
+++
@@ -17,15 +17,36 @@
#print b
#del b[1]
#print b
-c=list("Perl")
-c[1:1]=list('ython')
-c[-4:]=[]
-c.append('n')
-print c.count('t')
-print c
-d=[1,2,3]
-d.extend([4,5,6])
-print d
-e=[7,8,9]
-print e+[10,11,12]
-print e
+#c=list("Perl")
+#c[1:1]=list('ython')
+#c[-4:]=[]
+#c.append('n')
+#print c.count('t'... |
2f6e13a868f18a516f0eb79efa70f3ae527c4aad | tinman/handlers/__init__.py | tinman/handlers/__init__.py | """Custom Tinman Handlers add wrappers to based functionality to speed
application development.
"""
from tinman.handlers.session import SessionRequestHandler
| """Custom Tinman Handlers add wrappers to based functionality to speed
application development.
"""
from tinman.handlers.base import RequestHandler
from tinman.handlers.session import SessionRequestHandler
| Make the base request handler available by default | Make the base request handler available by default
| Python | bsd-3-clause | lucius-feng/tinman,gmr/tinman,lucius-feng/tinman,gmr/tinman,lucius-feng/tinman | ---
+++
@@ -2,4 +2,5 @@
application development.
"""
+from tinman.handlers.base import RequestHandler
from tinman.handlers.session import SessionRequestHandler |
d937e254ce3c806300ac7763e30bd4303661cba6 | whaler/analysis.py | whaler/analysis.py | """
"""
import os
from whaler.dataprep import IO
class Analysis():
"""
"""
def __init__(self):
self.loc = os.getcwd()
self.structs = next(os.walk('.'))[1]
print(self.loc)
print(self.structs)
def groundstates_all(self):
"""Compares the energies of each... | """
"""
import os
import numpy as np
from whaler.dataprep import IO
class Analysis():
"""
"""
def __init__(self):
self.loc = os.getcwd()
self.structs = next(os.walk('.'))[1]
print(self.loc)
print(self.structs)
def groundstates_all(self, outname="groundstates.... | Set up data tabulation for gs | Set up data tabulation for gs
| Python | mit | tristanbrown/whaler | ---
+++
@@ -3,6 +3,7 @@
"""
import os
+import numpy as np
from whaler.dataprep import IO
class Analysis():
@@ -14,13 +15,20 @@
print(self.loc)
print(self.structs)
- def groundstates_all(self):
+ def groundstates_all(self, outname="groundstates.csv"):
"""Compares the ... |
7d81a2f27c0bf9ab57d046152981c3882016e013 | wordcloud/views.py | wordcloud/views.py | import os
from django.conf import settings
from django.http import HttpResponse
from django.utils import simplejson
from django.views.decorators.cache import cache_page
from .wordcloud import popular_words
@cache_page(60*60*4)
def wordcloud(request, max_entries=30):
""" Return tag cloud JSON results"""
cach... | import os
from django.conf import settings
from django.http import HttpResponse
from django.utils import simplejson
from django.views.decorators.cache import cache_page
from .wordcloud import popular_words
@cache_page(60*60*4)
def wordcloud(request, max_entries=30):
""" Return tag cloud JSON results"""
cach... | Use x-sendfile to serve pre-generated wordcloud JSON. | Use x-sendfile to serve pre-generated wordcloud JSON.
If we've pre-generated the wordcloud JSON file, use x-sendfile to
serve it rather than reading the file in Django.
| Python | agpl-3.0 | geoffkilpin/pombola,mysociety/pombola,mysociety/pombola,mysociety/pombola,geoffkilpin/pombola,geoffkilpin/pombola,mysociety/pombola,geoffkilpin/pombola,geoffkilpin/pombola,geoffkilpin/pombola,mysociety/pombola,mysociety/pombola | ---
+++
@@ -13,10 +13,12 @@
""" Return tag cloud JSON results"""
cache_path = settings.WORDCLOUD_CACHE_PATH
if os.path.exists(cache_path):
- with open(cache_path) as cached_file:
- content = cached_file.read()
- else:
- content = simplejson.dumps(popular_words(max_entries=ma... |
cca7e512061948abe05fd25111974f41fa6fb6ec | romanesco/plugins/swift/tests/swift_test.py | romanesco/plugins/swift/tests/swift_test.py | import romanesco
import unittest
class TestSwiftMode(unittest.TestCase):
def testSwiftMode(self):
task = {
'mode': 'swift',
'script': """
type file;
app (file out) echo_app (string s)
{
echo s stdout=filename(out);
}
string a = arg("a", "10");
file out <"out.csv">;
out = echo... | import romanesco
import unittest
class TestSwiftMode(unittest.TestCase):
def testSwiftMode(self):
task = {
'mode': 'swift',
'script': """
type file;
app (file out) echo_app (string s)
{
echo s stdout=filename(out);
}
string a = arg("a", "10");
file out <"out.csv">;
out = echo... | Remove comments that don't make sense | Remove comments that don't make sense
| Python | apache-2.0 | girder/girder_worker,girder/girder_worker,Kitware/romanesco,Kitware/romanesco,Kitware/romanesco,Kitware/romanesco,girder/girder_worker | ---
+++
@@ -39,10 +39,8 @@
}
}
- # Use user-specified filename
out = romanesco.run(task, inputs=inputs)
- # We bound _stderr as a task output, so it should be in the output
self.assertEqual(out, {
'out.csv': {
'data': 'a,b,c\n5,2,... |
9bf6aec99ac490fce1af2ea92bea57b7d1e9acd9 | heat/common/environment_format.py | heat/common/environment_format.py | # vim: tabstop=4 shiftwidth=4 softtabstop=4
#
# 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 applicab... | # vim: tabstop=4 shiftwidth=4 softtabstop=4
#
# 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 applicab... | Make the template and env yaml parsing more consistent | Make the template and env yaml parsing more consistent
in the environment_format.py use the same yaml_loader
Partial-bug: #1242155
Change-Id: I66b08415d450bd4758af648eaff0f20dd934a9cc
| Python | apache-2.0 | noironetworks/heat,ntt-sic/heat,openstack/heat,srznew/heat,dragorosson/heat,steveb/heat,gonzolino/heat,pratikmallya/heat,srznew/heat,redhat-openstack/heat,cryptickp/heat,pratikmallya/heat,cwolferh/heat-scratch,pshchelo/heat,NeCTAR-RC/heat,miguelgrinberg/heat,pshchelo/heat,dragorosson/heat,maestro-hybrid-cloud/heat,take... | ---
+++
@@ -14,6 +14,7 @@
# under the License.
from heat.common.template_format import yaml
+from heat.common.template_format import yaml_loader
SECTIONS = (PARAMETERS, RESOURCE_REGISTRY) = \
@@ -27,7 +28,7 @@
JSON or YAML format.
'''
try:
- env = yaml.safe_load(env_str)
+ env... |
f280bc260b8a48e7b9e5d5d6a4995ca721440712 | brume/template.py | brume/template.py | import boto3
import sys
from colors import green, red
from botocore.exceptions import ClientError
s3_client = boto3.client('s3')
class InvalidTemplateError(BaseException):
def __init__(self, m):
self.m = m
def __str__(self):
return self.m
class Template():
def __init__(self, file):
... | import boto3
import sys
from colors import green, red
from botocore.exceptions import ClientError
s3_client = boto3.client('s3')
class InvalidTemplateError(BaseException):
def __init__(self, m):
self.m = m
def __str__(self):
return self.m
class CfnTemplate():
def __init__(self, file):
... | Rename Template to CfnTemplate to avoid name collision | Rename Template to CfnTemplate to avoid name collision
| Python | mit | flou/brume,geronimo-iia/brume | ---
+++
@@ -14,7 +14,7 @@
return self.m
-class Template():
+class CfnTemplate():
def __init__(self, file):
self.file = file
try: |
6500d388fa894bb0ea8cb0ca1328a73cc54ba4e8 | Challenges/chall_02.py | Challenges/chall_02.py | #!/usr/local/bin/python3
# Python Challenge - 2
# http://www.pythonchallenge.com/pc/def/ocr.html
# Keyword: equality
def main():
alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'
letters = []
with open('garbage.txt', 'r') as garbage:
for line in garbage.readlines():
for... | #!/usr/local/bin/python3
# Python Challenge - 2
# http://www.pythonchallenge.com/pc/def/ocr.html
# Keyword: equality
import string
def main():
'''
Hint: recognize the characters. maybe they are in the book,
but MAYBE they are in the page source.
Page source text saved in garbage.txt
'''
alph... | Refactor code, add page hints | Refactor code, add page hints
| Python | mit | HKuz/PythonChallenge | ---
+++
@@ -3,15 +3,26 @@
# http://www.pythonchallenge.com/pc/def/ocr.html
# Keyword: equality
+import string
+
def main():
- alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'
- letters = []
+ '''
+ Hint: recognize the characters. maybe they are in the book,
+ but MAYBE they are ... |
5631276591cf2c4e3c83920da32857e47286d9c9 | wanikani/django.py | wanikani/django.py | from __future__ import absolute_import
import os
import logging
from django.http import HttpResponse
from django.views.generic.base import View
from icalendar import Calendar, Event
from wanikani.core import WaniKani, Radical, Kanji
CONFIG_PATH = os.path.join(os.path.expanduser('~'), '.wanikani')
with open(CONFI... |
from __future__ import absolute_import
from django.http import HttpResponse
from django.views.generic.base import View
from icalendar import Calendar, Event
from wanikani.core import WaniKani, Radical, Kanji
class WaniKaniView(View):
def get(self, request, **kwargs):
client = WaniKani(kwargs['api_key... | Switch to getting the API key from the URL instead of a config file. | Switch to getting the API key from the URL instead of a config file.
Allows other people to get their anki calendar if they want. | Python | mit | kfdm/wanikani,kfdm/wanikani | ---
+++
@@ -1,7 +1,5 @@
+
from __future__ import absolute_import
-
-import os
-import logging
from django.http import HttpResponse
from django.views.generic.base import View
@@ -11,23 +9,16 @@
from wanikani.core import WaniKani, Radical, Kanji
-CONFIG_PATH = os.path.join(os.path.expanduser('~'), '.wanikani'... |
1d9b7d855d633da6388daf663398449cfc0e6ab6 | StandaloneViewer/etc/redirectingSimpleServer.py | StandaloneViewer/etc/redirectingSimpleServer.py | import SimpleHTTPServer, SocketServer
import urlparse, os
PORT = 3000
class MyHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
def do_GET(self):
# Parse query data to find out what was requested
parsedParams = urlparse.urlparse(self.path)
# See if the file requested exists
if os.ac... | import SimpleHTTPServer, SocketServer
import urlparse, os
PORT = 3000
## Note: If you set this parameter, you can try to serve files
# at a subdirectory. You should use
# -u http://localhost:3000/subdirectory
# when building the application, which will set this as your
# ROOT_URL.
#URL_PATH="/subdirectory"
URL_PATH="... | Update Python simple server script to allow subdomains | Update Python simple server script to allow subdomains
| Python | mit | OHIF/Viewers,OHIF/Viewers,OHIF/Viewers | ---
+++
@@ -3,8 +3,22 @@
PORT = 3000
+## Note: If you set this parameter, you can try to serve files
+# at a subdirectory. You should use
+# -u http://localhost:3000/subdirectory
+# when building the application, which will set this as your
+# ROOT_URL.
+#URL_PATH="/subdirectory"
+URL_PATH=""
+
class MyHandler(... |
7a4aeffc89120d0d5de53837a71f62ee21ba9bd6 | app/backend/wells/apps.py | app/backend/wells/apps.py | """
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distri... | """
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
distri... | Remove redundant post migrate step for increasing well_tag_number count (no longer needed, data is no longer being replicated) | Remove redundant post migrate step for increasing well_tag_number count (no longer needed, data is no longer being replicated)
| Python | apache-2.0 | bcgov/gwells,bcgov/gwells,bcgov/gwells,bcgov/gwells | ---
+++
@@ -27,20 +27,6 @@
# Dynamic comments from models
db_actions.create_db_comments_from_models(db_actions.get_all_model_classes('wells.models'))
- # NOTE: This is a temporary measure to reduce issues surrounding the well_tag_number sequece being
- # incorrect after replication wells. This shoul... |
d113fd75456c14f651cb9769d922d9394b369d63 | tools/add_previews.py | tools/add_previews.py | import os
import sys
import django
sys.path.append("/var/projects/museum/")
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "museum.settings")
django.setup()
from museum_site.models import *
from museum_site.common import *
from museum_site.constants import *
def main():
articles = Article.objects.filter(previ... | import os
import sys
import django
sys.path.append("/var/projects/museum/")
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "museum.settings")
django.setup()
from museum_site.models import * # noqa: E402
from museum_site.common import * # noqa: E402
from museum_site.constants import * # noqa: E402
HELP = """This... | Add script explanation and message when script is complete. | Add script explanation and message when script is complete.
| Python | mit | DrDos0016/z2,DrDos0016/z2,DrDos0016/z2 | ---
+++
@@ -7,13 +7,22 @@
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "museum.settings")
django.setup()
-from museum_site.models import *
-from museum_site.common import *
-from museum_site.constants import *
+from museum_site.models import * # noqa: E402
+from museum_site.common import * # noqa: E402
+from... |
878811a673625f9dbe0f41dd0196887f612ecf2e | expand_region_handler.py | expand_region_handler.py | import re
try:
import javascript
import html
except:
from . import javascript
from . import html
def expand(string, start, end, extension=None):
if(re.compile("html|htm|xml").search(extension)):
return html.expand(string, start, end)
return javascript.expand(string, start, end) | import re
try:
import javascript
import html
except:
from . import javascript
from . import html
def expand(string, start, end, extension=""):
if(re.compile("html|htm|xml").search(extension)):
return html.expand(string, start, end)
return javascript.expand(string, start, end) | Set default file extension to empty string | Set default file extension to empty string
Because with a Bool the regex throws
| Python | mit | johyphenel/sublime-expand-region,johyphenel/sublime-expand-region,aronwoost/sublime-expand-region | ---
+++
@@ -7,7 +7,7 @@
from . import javascript
from . import html
-def expand(string, start, end, extension=None):
+def expand(string, start, end, extension=""):
if(re.compile("html|htm|xml").search(extension)):
return html.expand(string, start, end) |
582964f9da6029cd089117496babf9267c41ecd5 | evewspace/core/utils.py | evewspace/core/utils.py | # Eve W-Space
# Copyright (C) 2013 Andrew Austin and other contributors
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option... | # Eve W-Space
# Copyright (C) 2013 Andrew Austin and other contributors
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option... | Reduce queries used to lookup config | Reduce queries used to lookup config
| Python | apache-2.0 | evewspace/eve-wspace,nyrocron/eve-wspace,hybrid1969/eve-wspace,hybrid1969/eve-wspace,acdervis/eve-wspace,marbindrakon/eve-wspace,Unsettled/eve-wspace,proycon/eve-wspace,mmalyska/eve-wspace,evewspace/eve-wspace,gpapaz/eve-wspace,acdervis/eve-wspace,proycon/eve-wspace,marbindrakon/eve-wspace,Zumochi/eve-wspace,marbindrak... | ---
+++
@@ -21,11 +21,7 @@
Gets the correct config value for the given key name.
Value with the given user has priority over any default value.
"""
- if ConfigEntry.objects.filter(name=name, user=user).count() != 0:
+ try:
return ConfigEntry.objects.get(name=name, user=user)
-
- # No ... |
dcc2821cac0619fc2ca5f486ad30416f3c3cfda9 | ce/expr/parser.py | ce/expr/parser.py | #!/usr/bin/env python
# vim: set fileencoding=UTF-8 :
from ..semantics import mpq
from .common import OPERATORS, ADD_OP, MULTIPLY_OP
def try_to_number(s):
try:
return mpq(s)
except (ValueError, TypeError):
return s
def _parse_r(s):
s = s.strip()
bracket_level = 0
operator_pos =... | #!/usr/bin/env python
# vim: set fileencoding=UTF-8 :
import ast
from ..semantics import mpq
from .common import OPERATORS, ADD_OP, MULTIPLY_OP
def try_to_number(s):
try:
return mpq(s)
except (ValueError, TypeError):
return s
OPERATOR_MAP = {
ast.Add: ADD_OP,
ast.Mult: MULTIPLY_OP... | Replace parsing with Python's ast | Replace parsing with Python's ast
Allows greater flexibility and syntax checks
| Python | mit | admk/soap | ---
+++
@@ -1,6 +1,8 @@
#!/usr/bin/env python
# vim: set fileencoding=UTF-8 :
+
+import ast
from ..semantics import mpq
from .common import OPERATORS, ADD_OP, MULTIPLY_OP
@@ -13,20 +15,24 @@
return s
-def _parse_r(s):
- s = s.strip()
- bracket_level = 0
- operator_pos = -1
- for i, v ... |
920e75491f3aaa74980e11086cfebe911c2def4b | statsmodels/datasets/tests/test_data.py | statsmodels/datasets/tests/test_data.py | import numpy as np
import pandas as pd
import statsmodels.datasets as datasets
from statsmodels.datasets import co2
from statsmodels.datasets.utils import Dataset
def test_co2_python3():
# this failed in pd.to_datetime on Python 3 with pandas <= 0.12.0
dta = co2.load_pandas()
class TestDatasets(object):
... | import importlib
import numpy as np
import pandas as pd
import nose
import pytest
import statsmodels.datasets
from statsmodels.datasets.utils import Dataset
exclude = ['check_internet', 'clear_data_home', 'get_data_home',
'get_rdataset', 'tests', 'utils', 'webuse']
datasets = []
for dataset_name in dir(st... | Remove yield from datasets tests | TST: Remove yield from datasets tests
Remove yield which is pending deprecation in pytest
xref #4000
| Python | bsd-3-clause | josef-pkt/statsmodels,ChadFulton/statsmodels,jseabold/statsmodels,josef-pkt/statsmodels,statsmodels/statsmodels,bashtage/statsmodels,jseabold/statsmodels,bashtage/statsmodels,ChadFulton/statsmodels,statsmodels/statsmodels,jseabold/statsmodels,bashtage/statsmodels,statsmodels/statsmodels,statsmodels/statsmodels,statsmod... | ---
+++
@@ -1,37 +1,36 @@
+import importlib
+
import numpy as np
import pandas as pd
+import nose
+import pytest
-import statsmodels.datasets as datasets
-from statsmodels.datasets import co2
+import statsmodels.datasets
from statsmodels.datasets.utils import Dataset
-
-def test_co2_python3():
- # this fail... |
97badc176f4a8ac30eb3932359e2e132e36170c4 | docker/gunicorn_config.py | docker/gunicorn_config.py | import multiprocessing
from os import getenv
bind = '127.0.0.1:8001'
workers = multiprocessing.cpu_count() * 2
timeout = 60
threads = multiprocessing.cpu_count() * 2
max_requests = 1000
max_requests_jitter = 5
# Read the DEBUG setting from env var
try:
if getenv('DOCKER_SAL_DEBUG').lower() == 'true':
errorl... | import multiprocessing
from os import getenv
bind = '127.0.0.1:8001'
workers = multiprocessing.cpu_count() * 3
timeout = 60
threads = multiprocessing.cpu_count() * 3
max_requests = 500
max_requests_jitter = 5
# Read the DEBUG setting from env var
try:
if getenv('DOCKER_SAL_DEBUG').lower() == 'true':
errorlo... | Increase the number of workers | Increase the number of workers
| Python | apache-2.0 | sheagcraig/sal,chasetb/sal,sheagcraig/sal,erikng/sal,salopensource/sal,salopensource/sal,chasetb/sal,erikng/sal,chasetb/sal,erikng/sal,chasetb/sal,erikng/sal,sheagcraig/sal,salopensource/sal,salopensource/sal,sheagcraig/sal | ---
+++
@@ -1,10 +1,10 @@
import multiprocessing
from os import getenv
bind = '127.0.0.1:8001'
-workers = multiprocessing.cpu_count() * 2
+workers = multiprocessing.cpu_count() * 3
timeout = 60
-threads = multiprocessing.cpu_count() * 2
-max_requests = 1000
+threads = multiprocessing.cpu_count() * 3
+max_requests... |
15090b84e1c7359c49cb45aec4d9b4d492f855ac | tests/scoring_engine/engine/checks/test_smb.py | tests/scoring_engine/engine/checks/test_smb.py | from scoring_engine.engine.basic_check import CHECKS_BIN_PATH
from tests.scoring_engine.engine.checks.check_test import CheckTest
class TestSMBCheck(CheckTest):
check_name = 'SMBCheck'
required_properties = ['share', 'file', 'hash']
properties = {
'share': 'ScoringShare',
'file': 'flag.tx... | from scoring_engine.engine.basic_check import CHECKS_BIN_PATH
from tests.scoring_engine.engine.checks.check_test import CheckTest
class TestSMBCheck(CheckTest):
check_name = 'SMBCheck'
required_properties = ['share', 'file', 'hash']
properties = {
'share': 'ScoringShare',
'file': 'flag.tx... | Update smb test to include port parameter | Update smb test to include port parameter
| Python | mit | pwnbus/scoring_engine,pwnbus/scoring_engine,pwnbus/scoring_engine,pwnbus/scoring_engine | ---
+++
@@ -14,4 +14,4 @@
accounts = {
'pwnbus': 'pwnbuspass'
}
- cmd = CHECKS_BIN_PATH + "/smb_check --host '127.0.0.1' --user 'pwnbus' --pass 'pwnbuspass' --share 'ScoringShare' --file 'flag.txt' --hash '123456789'"
+ cmd = CHECKS_BIN_PATH + "/smb_check --host '127.0.0.1' --port 100 --user ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.