commit stringlengths 40 40 | subject stringlengths 4 1.73k | repos stringlengths 5 127k | old_file stringlengths 2 751 | new_file stringlengths 2 751 | new_contents stringlengths 1 8.98k | old_contents stringlengths 0 6.59k | license stringclasses 13
values | lang stringclasses 23
values |
|---|---|---|---|---|---|---|---|---|
6ece8b239a4edce1aa066c176293e9277eef466d | Fix default formatter | klen/muffin-admin,klen/muffin-admin,klen/muffin-admin | muffin_admin/formatters.py | muffin_admin/formatters.py | """Define formatters."""
import datetime as dt
from html import escape
def default_formatter(handler, item, value):
"""Default formatter. Convert value to string."""
if hasattr(value, '__unicode__'):
value = value.__unicode__()
return escape(str(value))
def bool_formatter(handler, item, value)... | """ Define formatters. """
import datetime as dt
from html import escape
def default_formatter(handler, item, value):
""" Default formatter. """
if hasattr(value, '__unicode__'):
value = value.__unicode__()
else:
value = str(value)
return escape(value)
def bool_formatter(handler, ite... | mit | Python |
6a6b7d35fde5dbca8486f1973e833075db47581a | Use CachingJSONCubeManager | Code4SA/municipal-data,Code4SA/municipal-data,Code4SA/municipal-data,Code4SA/municipal-data | municipal_finance/cubes.py | municipal_finance/cubes.py | from django.conf import settings
from sqlalchemy import create_engine
from babbage.manager import CachingJSONCubeManager
engine = create_engine(settings.DATABASE_URL)
models_directory = 'models/'
cube_manager = CachingJSONCubeManager(engine, models_directory)
| from django.conf import settings
from sqlalchemy import create_engine
from babbage.manager import JSONCubeManager
engine = create_engine(settings.DATABASE_URL)
models_directory = 'models/'
cube_manager = JSONCubeManager(engine, models_directory)
| mit | Python |
3264c2fd8c09cb1f012392209603426e5f0a0da7 | Remove unneccesary helpers import | qitianchan/hasjob,nhannv/hasjob,nhannv/hasjob,qitianchan/hasjob,hasgeek/hasjob,ashwin01/hasjob,sindhus/hasjob,ashwin01/hasjob,nhannv/hasjob,sindhus/hasjob,nhannv/hasjob,ashwin01/hasjob,sindhus/hasjob,hasgeek/hasjob,hasgeek/hasjob,ashwin01/hasjob,qitianchan/hasjob,ashwin01/hasjob,sindhus/hasjob,qitianchan/hasjob,hasgeek... | hasjob/__init__.py | hasjob/__init__.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from os import environ
from flask import Flask
from flask.ext.mail import Mail
from flask.ext.assets import Environment, Bundle
from coaster import configureapp
# First, make an app and config it
app = Flask(__name__, instance_relative_config=True)
configureapp(app, 'HAS... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from os import environ
from flask import Flask
from flask.ext.mail import Mail
from flask.ext.assets import Environment, Bundle
from coaster import configureapp
# First, make an app and config it
app = Flask(__name__, instance_relative_config=True)
configureapp(app, 'HAS... | agpl-3.0 | Python |
bd470428b527707594a6fe2e962f695af16f8671 | add tko_project_task_type in dependency | elego/tkobr-addons,thinkopensolutions/tkobr-addons,thinkopensolutions/tkobr-addons,elego/tkobr-addons,thinkopensolutions/tkobr-addons,elego/tkobr-addons,elego/tkobr-addons,thinkopensolutions/tkobr-addons | tko_project_task_type_stages/__manifest__.py | tko_project_task_type_stages/__manifest__.py | # -*- encoding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
# ThinkOpen Solutions Brasil
# Copyright (C) Thinkopen Solutions <http://www.tkobr.com>.
#
# This... | # -*- encoding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
# ThinkOpen Solutions Brasil
# Copyright (C) Thinkopen Solutions <http://www.tkobr.com>.
#
# This... | agpl-3.0 | Python |
ed6a43a530291ed7993bde0e7d28f7e7b3e0a863 | mend index name | anselmobd/fo2,anselmobd/fo2,anselmobd/fo2,anselmobd/fo2 | src/geral/urls.py | src/geral/urls.py | from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^deposito/$', views.deposito, name='deposito'),
url(r'^estagio/$', views.estagio, name='estagio'),
url(r'^painel/(?P<painel>[^/]*)/?$',
views.PainelView.as_view(), name='ger_painel... | from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.index, name='geral'),
url(r'^deposito/$', views.deposito, name='deposito'),
url(r'^estagio/$', views.estagio, name='estagio'),
url(r'^painel/(?P<painel>[^/]*)/?$',
views.PainelView.as_view(), name='ger_painel... | mit | Python |
c5141c58a46c48f384296d8fe7589d49da646ba7 | improve documentation | tomi77/python-t77-date | t77_date/date.py | t77_date/date.py | from datetime import timedelta
def start_of_day(date):
"""
Return a new datetime with values that represent a start of a day.
:param date: Date to ...
:type date: datetime.datetime
:rtype: datetime.datetime
"""
return date.replace(hour=0, minute=0, second=0, microsecond=0)
def end_of_day... | from datetime import timedelta
def start_of_day(date):
"""
:param date: Date to ...
:type date: datetime.datetime
:rtype: datetime.datetime
"""
return date.replace(hour=0, minute=0, second=0, microsecond=0)
def end_of_day(date):
"""
:param date: Date to ...
:type date: datetime... | mit | Python |
9c7c9384439949a341b4eff0f60c23a5883785c0 | fix a testdir stragler | erickt/pygments,erickt/pygments,erickt/pygments,erickt/pygments,erickt/pygments,erickt/pygments,erickt/pygments,erickt/pygments,erickt/pygments,erickt/pygments,erickt/pygments,erickt/pygments | tests/test_latex_formatter.py | tests/test_latex_formatter.py | # -*- coding: utf-8 -*-
"""
Pygments LaTeX formatter tests
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:copyright: 2006-2007 by Georg Brandl.
:license: BSD, see LICENSE for more details.
"""
import os
import unittest
import tempfile
from pygments.formatters import LatexFormatter
from pygments.lexers import Python... | # -*- coding: utf-8 -*-
"""
Pygments LaTeX formatter tests
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:copyright: 2006-2007 by Georg Brandl.
:license: BSD, see LICENSE for more details.
"""
import os
import unittest
import tempfile
from pygments.formatters import LatexFormatter
from pygments.lexers import Python... | bsd-2-clause | Python |
499ce52304b8994500ba0e81bd23d9ac6a2038cf | Remove unused compat entries | kennethreitz/tablib | tablib/compat.py | tablib/compat.py | # -*- coding: utf-8 -*-
"""
tablib.compat
~~~~~~~~~~~~~
Tablib compatiblity module.
"""
import sys
is_py3 = (sys.version_info[0] > 2)
try:
from collections import OrderedDict
except ImportError:
from tablib.packages.ordereddict import OrderedDict
if is_py3:
from io import BytesIO
from io impor... | # -*- coding: utf-8 -*-
"""
tablib.compat
~~~~~~~~~~~~~
Tablib compatiblity module.
"""
import sys
is_py3 = (sys.version_info[0] > 2)
try:
from collections import OrderedDict
except ImportError:
from tablib.packages.ordereddict import OrderedDict
if is_py3:
from io import BytesIO
from itertool... | mit | Python |
0c4867cd23186d25ba8440aaa6cf99f140cc47ce | allow direct setting and getting | bndl/bndl,bndl/bndl | bndl/util/conf.py | bndl/util/conf.py | _MISSING = object()
class Config(object):
def __init__(self, values={}):
self.values = values
def get(self, key, fmt=None, defaults=None):
value = self.values.get(key, _MISSING)
if value == _MISSING:
value = defaults.get(key, _MISSING)
if value == _MISSING:
... | _MISSING = object()
class Config(object):
def __init__(self, values={}):
self.values = values
def get(self, key, fmt=None, defaults=None):
value = self.values.get(key, _MISSING)
if value == _MISSING:
value = defaults.get(key, _MISSING)
if value == _MISSING:
... | apache-2.0 | Python |
50231418f162511aec0eb48b96bc0c6f92de744e | change path | dhzhd1/road_obj_detect,dhzhd1/road_obj_detect,dhzhd1/road_obj_detect,dhzhd1/road_obj_detect | rfcn/prepare_raw_data.py | rfcn/prepare_raw_data.py | import zipfile
import tarfile
import os
import urllib
class PrepareRawData:
def __init__(self):
self.file_list = []
self.dataset_path = './data/RoadImages/'
if not os.path.isdir(self.dataset_path):
print("Dataset folder {} is not existing. Creating...".format(self.dataset_path)... | import zipfile
import tarfile
import os
import urllib
class PrepareRawData:
def __init__(self):
self.file_list = []
self.dataset_path = '../dataset/'
if not os.path.isdir(self.dataset_path):
print("Dataset folder {} is not existing. Creating...".format(self.dataset_path))
... | apache-2.0 | Python |
51f3877ee1c4919f3cd570812aef884d913328bb | fix merge conflict | hickford/cython,hhsprings/cython,marscher/cython,andreasvc/cython,hickford/cython,slonik-az/cython,marscher/cython,fperez/cython,encukou/cython,marscher/cython,da-woods/cython,hhsprings/cython,encukou/cython,fperez/cython,mrGeen/cython,achernet/cython,hickford/cython,dahebolangkuan/cython,mrGeen/cython,acrispin/cython,... | Cython/__init__.py | Cython/__init__.py | from Cython.Shadow import __version__
# Void cython.* directives (for case insensitive operating systems).
from Cython.Shadow import *
| <<<<<<< HEAD
from Cython.Shadow import __version__
=======
__version__ = "0.17.4"
>>>>>>> bugs
# Void cython.* directives (for case insensitive operating systems).
from Cython.Shadow import *
| apache-2.0 | Python |
c18a69b8f2476215872d461e4520e30107c836b0 | Add debugging check | Chris-Johnston/Internet-Xmas-Tree,Chris-Johnston/Internet-Xmas-Tree,Chris-Johnston/Internet-Xmas-Tree,Chris-Johnston/Internet-Xmas-Tree | lights/patterns/blink.py | lights/patterns/blink.py | """
Blink Pattern
"""
from .pattern import Pattern
import time
class Blink(Pattern):
"""
Blink pattern class
"""
color_toggle = False
last_blink_time = 0
def __init__(self):
super(Pattern, self).__init__()
self.__set_time()
@staticmethod
def __get_time():
re... | """
Blink Pattern
"""
from .pattern import Pattern
import time
class Blink(Pattern):
"""
Blink pattern class
"""
color_toggle = False
last_blink_time = 0
def __init__(self):
super(Pattern, self).__init__()
self.__set_time()
@staticmethod
def __get_time():
re... | mit | Python |
e464ee8f418fa3fb222fd86407d7ef2bdded2f88 | Remove debug print | alanc10n/py-rau | rau.py | rau.py | import argparse
from redis import StrictRedis
from rau.commands import Command
def delete(args, command):
""" Execute the delete command """
command.delete(args.pattern)
def keys(args, command):
""" Execute the keys command """
command.keys(args.pattern, args.details)
def parse_args():
parser ... | import argparse
from redis import StrictRedis
from rau.commands import Command
def delete(args, command):
""" Execute the delete command """
command.delete(args.pattern)
def keys(args, command):
""" Execute the keys command """
command.keys(args.pattern, args.details)
def parse_args():
parser ... | mit | Python |
c4e497f24818169e8c59c07246582223c8214e45 | Allow values of BitFormField's to be integers (for legacy compatibility in some apps) | moggers87/django-bitfield,joshowen/django-bitfield,Elec/django-bitfield,budlight/django-bitfield,disqus/django-bitfield | bitfield/forms.py | bitfield/forms.py | from django.forms import CheckboxSelectMultiple, IntegerField, ValidationError
from django.utils.encoding import force_unicode
from .types import BitHandler
class BitFieldCheckboxSelectMultiple(CheckboxSelectMultiple):
def render(self, name, value, attrs=None, choices=()):
if isinstance(value, BitHandler... | from django.forms import CheckboxSelectMultiple, IntegerField, ValidationError
from django.utils.encoding import force_unicode
from .types import BitHandler
class BitFieldCheckboxSelectMultiple(CheckboxSelectMultiple):
def render(self, name, value, attrs=None, choices=()):
if isinstance(value, BitHandler... | apache-2.0 | Python |
d534b02d729d1fcbf6c6c025e78a1a75886c3726 | add can_deliver_to_user_with_username to DukeDS init | Duke-GCB/DukeDSClient,Duke-GCB/DukeDSClient | DukeDS/__init__.py | DukeDS/__init__.py | from ddsc.sdk.dukeds import DukeDS
list_projects = DukeDS.list_projects
create_project = DukeDS.create_project
delete_project = DukeDS.delete_project
list_files = DukeDS.list_files
download_file = DukeDS.download_file
upload_file = DukeDS.upload_file
delete_file = DukeDS.delete_file
can_deliver_to_user_with_email = Duk... | from ddsc.sdk.dukeds import DukeDS
list_projects = DukeDS.list_projects
create_project = DukeDS.create_project
delete_project = DukeDS.delete_project
list_files = DukeDS.list_files
download_file = DukeDS.download_file
upload_file = DukeDS.upload_file
delete_file = DukeDS.delete_file
can_deliver_to_user_with_email = Duk... | mit | Python |
67d178b949dc880a3640603e87625c3debd36478 | fix Livestreams with status 1 (set Referer) | gravyboat/streamlink,chhe/streamlink,melmorabity/streamlink,bastimeyer/streamlink,beardypig/streamlink,chhe/streamlink,streamlink/streamlink,streamlink/streamlink,bastimeyer/streamlink,melmorabity/streamlink,beardypig/streamlink,gravyboat/streamlink | src/streamlink/plugins/bilibili.py | src/streamlink/plugins/bilibili.py | import re
from streamlink.plugin import Plugin
from streamlink.plugin.api import validate, useragents
from streamlink.stream import HTTPStream
API_URL = "https://api.live.bilibili.com/room/v1/Room/playUrl"
ROOM_API = "https://api.live.bilibili.com/room/v1/Room/room_init?id={}"
SHOW_STATUS_OFFLINE = 0
SHOW_STATUS_ONLI... | import re
from requests.adapters import HTTPAdapter
from streamlink.plugin import Plugin
from streamlink.plugin.api import validate, useragents
from streamlink.stream import HTTPStream
API_URL = "https://api.live.bilibili.com/room/v1/Room/playUrl?cid={0}&quality=4&platform=web"
ROOM_API = "https://api.live.bilibili.c... | bsd-2-clause | Python |
72a2e4e2e6d603be65b7b750d32d8b9f7f945f52 | update to dev.3 | gepd/Deviot,gepd/Deviot | libraries/__init__.py | libraries/__init__.py | VERSION = (2, 2, 0, '-dev.3')
__version__ = ".".join([str(s) for s in VERSION[:3]])
if(len(VERSION) > 3):
__version__ += VERSION[3]
__title__ = "Deviot"
__description__ = (
"Plugin for IoT development based in the platformIO ecosystem."
"More info about platformIO visit: . http://platformio.org"
)
__url__ ... | VERSION = (2, 1, 5, '-dev.2')
__version__ = ".".join([str(s) for s in VERSION[:3]])
if(len(VERSION) > 3):
__version__ += VERSION[3]
__title__ = "Deviot"
__description__ = (
"Plugin for IoT development based in the platformIO ecosystem."
"More info about platformIO visit: . http://platformio.org"
)
__url__ ... | apache-2.0 | Python |
656b854bc0632028789ce3e077aafdd47dcf1dcf | Print posts as raw JSON | graue/tentrss | tentrss.py | tentrss.py | import re
from flask import Flask, request as flask_request
import requests
app = Flask(__name__)
tent_mime = 'application/vnd.tent.v0+json'
@app.route('/')
def front_page():
return 'TentRSS!'
@app.route('/feed')
def user_feed():
tent_uri = flask_request.args.get('uri', '')
app.logger.debug('tent_uri ... | import re
from flask import Flask, request as flask_request
import requests
app = Flask(__name__)
@app.route('/')
def front_page():
return 'TentRSS!'
@app.route('/feed')
def user_feed():
tent_uri = flask_request.args.get('uri', '')
app.logger.debug('tent_uri is %s' % tent_uri)
if tent_uri == '':
... | mit | Python |
52464199362c21a09ffe1b67dfb1beb4a8969d57 | Rewrite btsethttpseeds in keeping with btreannounce/btcopyannounce | jakesyl/BitTornado | btsethttpseeds.py | btsethttpseeds.py | #!/usr/bin/env python
# Written by Henry 'Pi' James and Bram Cohen
# multitracker extensions by John Hoffman
# see LICENSE.txt for license information
import sys
import os
import getopt
from BitTornado.bencode import bencode, bdecode
def main(argv):
program, ext = os.path.splitext(os.path.basename(argv[0]))
... | #!/usr/bin/env python
# Written by Henry 'Pi' James and Bram Cohen
# multitracker extensions by John Hoffman
# see LICENSE.txt for license information
from sys import argv,exit
from os.path import split
from BitTornado.bencode import bencode, bdecode
if len(argv) < 3:
a,b = split(argv[0])
print ('Usage: ' + ... | mit | Python |
1c52aa6c850d91e2b7fd08f1f5cc9e32201b20d7 | Fix typo | Beacon-Unime/Federation-Agent,Beacon-Unime/Federation-Agent | netfa/fa_ovn_controller.py | netfa/fa_ovn_controller.py | import uuid
import os
from netfa.fa_sdn_controller import FaSdnController
from netfa.fa_sdn_controller import EventRegisterVNIDReq
from ryu.controller.handler import MAIN_DISPATCHER
from ryu.controller.handler import set_ev_cls
import ryu.lib.ovs.vsctl as ovs_vsctl
from ryu import cfg
class OvnController(FaSdnControll... | import uuid
import os
from netfa.fa_sdn_controller import FaSdnController
from netfa.fa_sdn_controller import EventRegisterVNIDReq
from ryu.controller.handler import MAIN_DISPATCHER
from ryu.controller.handler import set_ev_cls
import ryu.lib.ovs.vsctl as ovs_vsctl
from ryu import cfg
class OvnController(FaSdnControll... | apache-2.0 | Python |
150c1ac956d756c6ebdc2058f4fab2e8bdc09b88 | Update __init__.py | seandsanders/coreproxy | brave/__init__.py | brave/__init__.py | try: # pragma: no cover
__import__('pkg_resources').declare_namespace(__name__)
except ImportError: # pragma: no cover
__import__('pkgutil').extend_path(__path__, __name__)
| mit | Python | |
f223f741771dab92d9e1b59dba6106240aae0351 | add command line arguments to specify protocol | TornikeNatsvlishvili/speech.ge,TornikeNatsvlishvili/speech.ge,TornikeNatsvlishvili/speech.ge | run.py | run.py | import sys
from app.app import app
if len(sys.argv) == 1:
print("Requires an argument: http or https")
else:
if sys.argv[1] == 'http':
app.run(host='127.0.0.1', port=8080)
elif sys.argv[1] == 'https':
context = ('domain.crt', 'domain.key')
app.run(host='0.0.0.0', debug=True, port=80... | from app.app import app
context = ('domain.crt', 'domain.key')
app.run(host='0.0.0.0', debug=True, port=8080, ssl_context=context) | mit | Python |
00fa4aafdd84af5588c3f830a4089c3fcf7ee06d | Generalize clean up script | henningjp/CoolProp,CoolProp/CoolProp,CoolProp/CoolProp,CoolProp/CoolProp,henningjp/CoolProp,CoolProp/CoolProp,CoolProp/CoolProp,CoolProp/CoolProp,CoolProp/CoolProp,henningjp/CoolProp,henningjp/CoolProp,henningjp/CoolProp,henningjp/CoolProp,henningjp/CoolProp,CoolProp/CoolProp,henningjp/CoolProp | dev/clean_up_json.py | dev/clean_up_json.py | import json, sys, glob, os
here = os.path.dirname(os.path.abspath(__file__))
sys.path.append(here+'/..')
from package_json import json_options
for fluid in glob.glob(here+'/fluids/*.json'):
print(fluid)
j = json.load(open(fluid, 'r'))
fp = open(fluid, 'w')
fp.write(json.dumps(j, **json_options))
... | import json, sys, glob, os
here = os.path.dirname(__file__)
sys.path.append(here+'/..')
from package_json import json_options
for fluid in glob.glob(here+'/fluids/*.json'):
print(fluid)
j = json.load(open(fluid, 'r'))
fp = open(fluid, 'w')
fp.write(json.dumps(j, **json_options))
fp.close()
| mit | Python |
7b3aacaec5ca1363cd51afc4f0ac12d980b7bd65 | Bump version | shosca/django-rest-witchcraft | rest_witchcraft/__version__.py | rest_witchcraft/__version__.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import, print_function, unicode_literals
__author__ = 'Serkan Hosca'
__author_email__ = 'serkan@hosca.com'
__version__ = '0.0.6'
__description__ = 'SQLAlchemy specific things for django-rest-framework'
| # -*- coding: utf-8 -*-
from __future__ import absolute_import, print_function, unicode_literals
__author__ = 'Serkan Hosca'
__author_email__ = 'serkan@hosca.com'
__version__ = '0.0.5'
__description__ = 'SQLAlchemy specific things for django-rest-framework'
| mit | Python |
dc1e416dabf978343113a919647999bc5cb98928 | Remove trailing whitespaces | miguelgrinberg/python-socketio,miguelgrinberg/python-socketio | socketio/__init__.py | socketio/__init__.py | import sys
from .middleware import Middleware
from .base_manager import BaseManager
from .pubsub_manager import PubSubManager
from .kombu_manager import KombuManager
from .redis_manager import RedisManager
from .kafka_manager import KafkaManager
from .zmq_manager import ZmqManager
from .server import Server
from .name... | import sys
from .middleware import Middleware
from .base_manager import BaseManager
from .pubsub_manager import PubSubManager
from .kombu_manager import KombuManager
from .redis_manager import RedisManager
from .kafka_manager import KafkaManager
from .zmq_manager import ZmqManager
from .server import Server
from .name... | mit | Python |
b0560715b9864c9bf604b4a1151e054d2db5cfb8 | add data_server param in testing.py and fix false ko test | GuillaumeMorini/roomfinder,Guismo1/roomfinder,Guismo1/roomfinder,Guismo1/roomfinder,GuillaumeMorini/roomfinder,GuillaumeMorini/roomfinder | testing.py | testing.py | import unittest
import sys
sys.path.append('roomfinder_web/roomfinder_web')
import web_server
class FlaskTestCase(unittest.TestCase):
def setUp(self):
sys.stderr.write('Setup testing.')
web_server.app.config['TESTING'] = True
web_server.data_server=sys.argv[1]
self.app = web_server... | import unittest
import sys
sys.path.append('roomfinder_web/roomfinder_web')
import web_server
class FlaskTestCase(unittest.TestCase):
def setUp(self):
sys.stderr.write('Setup testing.')
web_server.app.config['TESTING'] = True
self.app = web_server.app.test_client()
def test_correct_h... | apache-2.0 | Python |
8b3d2e6b526db26048dcef44a52281071282a81f | Make sure getters and setters on python SharedBackendConf are consistent with scala counterpart (#1789) | h2oai/sparkling-water,h2oai/sparkling-water,h2oai/sparkling-water,h2oai/sparkling-water | py/tests/unit/with_runtime_clientless_sparkling/test_security.py | py/tests/unit/with_runtime_clientless_sparkling/test_security.py | # Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
i... | # Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
i... | apache-2.0 | Python |
19da6c14a5063d3d0361b9b887fd0e4ed8d7a83d | Update SeasonInfo database table info | prcutler/nflpool,prcutler/nflpool | nflpool/data/seasoninfo.py | nflpool/data/seasoninfo.py | from nflpool.data.modelbase import SqlAlchemyBase
import sqlalchemy
class SeasonInfo(SqlAlchemyBase):
__tablename__ = 'SeasonInfo'
id = sqlalchemy.Column(sqlalchemy.Integer, primary_key=True, autoincrement=True)
current_season = sqlalchemy.Column(sqlalchemy.Integer)
season_start_date = sqlalchemy.Colu... | from nflpool.data.modelbase import SqlAlchemyBase
import sqlalchemy
class SeasonInfo(SqlAlchemyBase):
__tablename__ = 'SeasonInfo'
id = sqlalchemy.Column(sqlalchemy.Integer, primary_key=True, autoincrement=True)
current_season = sqlalchemy.Column(sqlalchemy.Integer)
season_start_date = sqlalchemy.Colu... | mit | Python |
84298c790d53ef1c4750e0e06d40a8d8bcba71ed | Update P5_readDocx.py added docstrings | JoseALermaIII/python-tutorials,JoseALermaIII/python-tutorials | pythontutorials/books/AutomateTheBoringStuff/Ch13/P5_readDocx.py | pythontutorials/books/AutomateTheBoringStuff/Ch13/P5_readDocx.py | #! python3
"""Read docx
Accepts a filename of a .docx file and returns a single string value of its text.
Note:
* Example .docx files can be downloaded from http://nostarch.com/automatestuff/
"""
import docx
def getText(filename: str) -> str:
"""Get text
Gets text from a given .docx file.
Args:
... | #! python3
# P5_readDocx.py - Accepts a filename of a .docx file and returns a single
# string value of its text.
#
# Note:
# - Example .docx files can be downloaded from http://nostarch.com/automatestuff/
import docx
def getText(filename):
doc = docx.Document(filename)
fullText = []
for para in doc.para... | mit | Python |
fb1a651ddf50d9732cd61ef65719256cdb68407a | Bump version to 0.13.0.dev | tempbottle/eventlet,collinstocks/eventlet,lindenlab/eventlet,tempbottle/eventlet,lindenlab/eventlet,lindenlab/eventlet,collinstocks/eventlet | eventlet/__init__.py | eventlet/__init__.py | version_info = (0, 13, 0, "dev")
__version__ = ".".join(map(str, version_info))
try:
from eventlet import greenthread
from eventlet import greenpool
from eventlet import queue
from eventlet import timeout
from eventlet import patcher
from eventlet import convenience
import greenlet
sle... | version_info = (0, 12, 0)
__version__ = ".".join(map(str, version_info))
try:
from eventlet import greenthread
from eventlet import greenpool
from eventlet import queue
from eventlet import timeout
from eventlet import patcher
from eventlet import convenience
import greenlet
sleep = gr... | mit | Python |
a9268e13553c4506ea0d7126829bd9b33e62296e | Fix SQL query to return 10 rows & simplify [(#1041)](https://github.com/GoogleCloudPlatform/python-docs-samples/issues/1041) | googleapis/python-bigquery,googleapis/python-bigquery | samples/snippets/simple_app.py | samples/snippets/simple_app.py | #!/usr/bin/env python
# Copyright 2016 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required... | #!/usr/bin/env python
# Copyright 2016 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required... | apache-2.0 | Python |
caf69988f05e3807a47b4a7c59a3423b9c749918 | add another note to model | viviangb/startupeducationdo,elpargo/startupweekenddo,viviangb/startupeducationdo,elpargo/startupweekenddo,viviangb/startupeducationdo,elpargo/startupweekenddo | app/collaborators/models.py | app/collaborators/models.py | from django.db import models
# Create your models here.
class Collaborators(models.Model):
"""All the colaboratos goes here without exception"""
full_name = models.CharField(max_length=40)
mini_bio = models.TextField()
image = models.ImageField(upload_to="img")
twitter = models.URLField()
linkedin = models.U... | from django.db import models
# Create your models here.
class Collaborators(models.Model):
full_name = models.CharField(max_length=40)
mini_bio = models.TextField()
image = models.ImageField(upload_to="img")
twitter = models.URLField()
linkedin = models.URLField()
email = models.EmailField()
category = models.... | mit | Python |
4ca38ab97449624366455b00012e8a3976fa6270 | update models.py to be consistent with database | hep-gc/cloudscheduler,hep-gc/cloudscheduler,hep-gc/cloudscheduler,hep-gc/cloudscheduler | web_frontend/cloudscheduler/csv2/models.py | web_frontend/cloudscheduler/csv2/models.py | from django.db import models
from django.contrib.auth.models import User
import datetime
# Create your models here.
class user(models.Model):
username = models.CharField(max_length=32, primary_key=True)
cert_cn = models.CharField(max_length=128, null=True, default=None)
password = models.CharField(max_... | from django.db import models
from django.contrib.auth.models import User
import datetime
# Create your models here.
class user(models.Model):
username = models.CharField(max_length=32)
cert_cn = models.CharField(max_length=128, null=True, default=None)
password = models.CharField(max_length=128, defaul... | apache-2.0 | Python |
8bd43bc16e83707ec4eac3c6abee88f1c8526945 | Change string representation for a WebdriverActionRequest object; this makes it clearer in the shell that the request received is not a simple GET request but in fact a request for a Selenium webdriver in-page action. | zipfworks/scrapy-webdriver,JeffAMcGee/scrapy-webdriver | scrapy_webdriver/http.py | scrapy_webdriver/http.py | from scrapy.http import Request, TextResponse
from selenium.webdriver.common.action_chains import ActionChains
class WebdriverRequest(Request):
"""A Request needed when using the webdriver download handler."""
WAITING = None
def __init__(self, url, manager=None, **kwargs):
super(WebdriverRequest,... | from scrapy.http import Request, TextResponse
from selenium.webdriver.common.action_chains import ActionChains
class WebdriverRequest(Request):
"""A Request needed when using the webdriver download handler."""
WAITING = None
def __init__(self, url, manager=None, **kwargs):
super(WebdriverRequest,... | mit | Python |
0b304029f6155a66ef6ee5db361371efe05bfa57 | mark module as non-installable | it-projects-llc/website-addons,it-projects-llc/website-addons,it-projects-llc/website-addons | website_sale_checkout_store/__openerp__.py | website_sale_checkout_store/__openerp__.py | # -*- coding: utf-8 -*-
{
'name': """Pickup and pay at store""",
'summary': """Simplify checkout process by excluding shipping and/or payment information""",
'category': 'eCommerce',
'images': ['images/1.png'],
'version': '1.0.1',
'author': 'IT-Projects LLC',
"support": "apps@it-projects.in... | # -*- coding: utf-8 -*-
{
'name': """Pickup and pay at store""",
'summary': """Simplify checkout process by excluding shipping and/or payment information""",
'category': 'eCommerce',
'images': ['images/1.png'],
'version': '1.0.1',
'author': 'IT-Projects LLC',
"support": "apps@it-projects.in... | mit | Python |
eed97d89386bd043e013e09ecad1f4c541b794ed | Add missing ‘self’ parameter to ‘close’ method | gizmo-cda/g2x,gizmo-cda/g2x,gizmo-cda/g2x,thelonious/g2x,gizmo-cda/g2x,thelonious/g2x | scratchpad/mockcamera.py | scratchpad/mockcamera.py | from fractions import Fraction
class PiCamera:
def __init__(self):
self.analog_gain = 0
self.annotate_text = ""
self.annotate_text_size = 32
self.awb_gains = (Fraction(0,1), Fraction(0,1))
self.awb_mode = "auto"
self.brightness = 50
self.color_eff... | from fractions import Fraction
class PiCamera:
def __init__(self):
self.analog_gain = 0
self.annotate_text = ""
self.annotate_text_size = 32
self.awb_gains = (Fraction(0,1), Fraction(0,1))
self.awb_mode = "auto"
self.brightness = 50
self.color_eff... | mit | Python |
3fab7730397cdaf0a5ea60578337e58dac6a3ead | Make Brainfuck cell count scale with memory limit; #338 | DMOJ/judge,DMOJ/judge,DMOJ/judge | dmoj/executors/BF.py | dmoj/executors/BF.py | import itertools
import six
from six.moves import map
from dmoj.executors.C import Executor as CExecutor
from dmoj.error import CompileError
template = b'''\
#define _GNU_SOURCE
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/mman.h>
int main(int argc, char **argv) {
char *p;
size_t ... | import itertools
import six
from six.moves import map
from dmoj.executors.C import Executor as CExecutor
from dmoj.error import CompileError
template = b'''\
#include <stdio.h>
char array[16777216];
int main() {
char *ptr = array;
%s
}
'''
trans = {b'>': b'++ptr;', b'<': b'--ptr;',
b'+': b'++*ptr... | agpl-3.0 | Python |
3e1f2fb1ba8778f8acab1c958d868c5fce87b8d5 | use python 3.6 as intersphinx mapping | sony/nnabla,sony/nnabla,sony/nnabla | doc/conf.py | doc/conf.py | # Copyright (c) 2017 Sony Corporation. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicabl... | # Copyright (c) 2017 Sony Corporation. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicabl... | apache-2.0 | Python |
63ba00378d38a6c2e54a1003e54b1aee933c0f0f | update copyright (#120) | all-umass/metric-learn,terrytangyuan/metric-learn | doc/conf.py | doc/conf.py | # -*- coding: utf-8 -*-
extensions = [
'sphinx.ext.autodoc',
'sphinx.ext.autosummary',
'sphinx.ext.todo',
'sphinx.ext.viewcode',
'sphinx.ext.mathjax',
'numpydoc',
]
templates_path = ['_templates']
source_suffix = '.rst'
master_doc = 'index'
# General information about the project.
project = u... | # -*- coding: utf-8 -*-
extensions = [
'sphinx.ext.autodoc',
'sphinx.ext.autosummary',
'sphinx.ext.todo',
'sphinx.ext.viewcode',
'sphinx.ext.mathjax',
'numpydoc',
]
templates_path = ['_templates']
source_suffix = '.rst'
master_doc = 'index'
# General information about the project.
project = u... | mit | Python |
8ee1257b8456bcc9cb451a8118bb7dff5b2d8a48 | fix db client call | aloverso/loanbot | databaseClient.py | databaseClient.py | from pymongo import MongoClient
import os
'''
the class sructure used for the User in the Mongo database
'''
class User:
def __init__(self, sender_id):
self.sender_id = sender_id
self.tools = []
self.temp_tools = []
self.stage = 0
'''
A client which connects to Mongo and deals with... | from pymongo import MongoClient
import os
'''
the class sructure used for the User in the Mongo database
'''
class User:
def __init__(self, sender_id):
self.sender_id = sender_id
self.tools = []
self.temp_tools = []
self.stage = NO_CONTACT
'''
A client which connects to Mongo and d... | mit | Python |
84b349308866da57806e0ec4316a9ab9349bed49 | add dictionary validation script | nakagami/janome,nakagami/janome,mocobeta/janome,mocobeta/janome | ipadic/validate.py | ipadic/validate.py | import os, sys
parent_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, parent_dir)
from dic import SystemDictionary
SYS_DIC = SystemDictionary(".")
import struct
import logging
import sys
if __name__ == '__main__':
logging.basicConfig(level=logging.DEBUG)
words_file = sys.a... | __author__ = 'moco'
| apache-2.0 | Python |
6362c73b84799097456b01e535ba85fb96db0ea5 | Replace non-ascii character for single quote | GetBlimp/boards-backend,jessamynsmith/boards-backend,jessamynsmith/boards-backend | blimp_boards/files/utils.py | blimp_boards/files/utils.py | import json
import base64
import datetime
import hmac
import hashlib
import uuid
from django.utils.encoding import smart_bytes
from django.utils.timezone import now
def generate_policy(bucket, mime_type, file_size):
"""
Returns a Base64-encoded policy document that applies rules
to file uploads sent by t... | import json
import base64
import datetime
import hmac
import hashlib
import uuid
from django.utils.encoding import smart_bytes
from django.utils.timezone import now
def generate_policy(bucket, mime_type, file_size):
"""
Returns a Base64-encoded policy document that applies rules
to file uploads sent by t... | agpl-3.0 | Python |
e6a431d61645e1549dc38984dd49ebaced35d56f | Update header handling | c-bata/kobin-example,c-bata/kobin-example,c-bata/kobin-example | app/views/tasks.py | app/views/tasks.py | from kobin import response, request, HTTPError
import json
from .. import app, models
from ..service import task as task_service
def task_list():
response.headers.add_header('Content-Type', 'application/json; charset=utf-8')
session = app.config["DB"]["SESSION"]
tasks = [t.serialize for t in session.quer... | from kobin import response, request, HTTPError
import json
from .. import app, models
from ..service import task as task_service
def task_list():
response.add_header('Content-Type', 'application/json; charset=utf-8')
session = app.config["DB"]["SESSION"]
tasks = [t.serialize for t in session.query(models... | mit | Python |
b8b6f19485488f8f10e793483b16cb5ff982783e | Update version | SpamScope/mail-parser | mailparser/version.py | mailparser/version.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Copyright 2016 Fedele Mantuano (https://twitter.com/fedelemantuano)
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/lice... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Copyright 2016 Fedele Mantuano (https://twitter.com/fedelemantuano)
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/lice... | apache-2.0 | Python |
fb584eb26ccc711bcda7da6d84343c34476c5945 | add docstrings to EventsConsumer | edmorley/treeherder,adusca/treeherder,sylvestre/treeherder,gbrmachado/treeherder,jgraham/treeherder,wlach/treeherder,moijes12/treeherder,gbrmachado/treeherder,vaishalitekale/treeherder,avih/treeherder,jgraham/treeherder,gbrmachado/treeherder,adusca/treeherder,avih/treeherder,wlach/treeherder,tojonmz/treeherder,moijes12... | treeherder/events/consumer.py | treeherder/events/consumer.py | from kombu.mixins import ConsumerMixin
from kombu import Connection, Exchange, Consumer, Queue
class EventsConsumer(ConsumerMixin):
"""
A specialized message consumer for the 'events' exchange.
The subscription mechanism is based on a simple routing key with the
following structure:
[ * | try | ... | from kombu.mixins import ConsumerMixin
from kombu import Connection, Exchange, Consumer, Queue
class EventsConsumer(ConsumerMixin):
def __init__(self, connection):
self.connection = connection
self.exchange = Exchange("events", type="topic")
self.consumers = []
def get_consumers(sel... | mpl-2.0 | Python |
246a5d950b7f8865b09643c9c0726b5393f8b127 | allow a fixed image range | imcgreer/rapala,legacysurvey/rapala,legacysurvey/rapala | bokpipe/tools/bokfits2im.py | bokpipe/tools/bokfits2im.py | #!/usr/bin/env python
import matplotlib
# Force matplotlib to not use any Xwindows backend.
matplotlib.use('Agg')
import argparse
from bokpipe.bokmkimage import make_fov_image_fromfile
parser = argparse.ArgumentParser()
parser.add_argument("fitsFile",type=str,
help="input FITS image")
parser.add... | #!/usr/bin/env python
import matplotlib
# Force matplotlib to not use any Xwindows backend.
matplotlib.use('Agg')
import argparse
from bokpipe.bokmkimage import make_fov_image_fromfile
parser = argparse.ArgumentParser()
parser.add_argument("fitsFile",type=str,
help="input FITS image")
parser.add... | bsd-3-clause | Python |
252a56980e02f544fdbee106ea5b381ba82c8b62 | Add backend processing progress as a property to BackendProxy | onitake/Uranium,onitake/Uranium | UM/Qt/Bindings/BackendProxy.py | UM/Qt/Bindings/BackendProxy.py | from PyQt5.QtCore import QObject, pyqtSignal, pyqtProperty
from UM.Application import Application
class BackendProxy(QObject):
def __init__(self, parent = None):
super().__init__(parent)
self._backend = Application.getInstance().getBackend()
self._progress = -1;
if self._backend:
... | from PyQt5.QtCore import QObject, pyqtSignal
from UM.Application import Application
class BackendProxy(QObject):
def __init__(self, parent = None):
super().__init__(parent)
self._backend = Application.getInstance().getBackend()
if self._backend:
self._backend.processingProgress... | agpl-3.0 | Python |
9ed92d2a7c6613cbb8d169c6583c7af0defad150 | Bump wirecloud version | jpajuelo/wirecloud,jpajuelo/wirecloud,jpajuelo/wirecloud,rockneurotiko/wirecloud,rockneurotiko/wirecloud,rockneurotiko/wirecloud,rockneurotiko/wirecloud,jpajuelo/wirecloud | src/wirecloud/platform/__init__.py | src/wirecloud/platform/__init__.py | # -*- coding: utf-8 -*-
# Copyright (c) 2011-2013 CoNWeT Lab., Universidad Politécnica de Madrid
# This file is part of Wirecloud.
# Wirecloud is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either v... | # -*- coding: utf-8 -*-
# Copyright (c) 2011-2013 CoNWeT Lab., Universidad Politécnica de Madrid
# This file is part of Wirecloud.
# Wirecloud is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either v... | agpl-3.0 | Python |
6bc1bb0dafeca73b25ed346af47d28ef1ca6e651 | handle the swift.authorize hook. | rzarzynski/rgwift | middleware/wsgi_relay.py | middleware/wsgi_relay.py | import wsgiproxy.app
import wsgiproxy.exactproxy
import sys
from swift.common.swob import Request, Response
from swift.proxy.controllers.base import _set_info_cache
def druk(s):
with open('/tmp/zupa', 'a') as f:
f.write(s + "\n")
class Application(object):
def __init__(self, conf):
self.reche... | import wsgiproxy.app
import wsgiproxy.exactproxy
import sys
from swift.common.swob import Request, Response
from swift.proxy.controllers.base import _set_info_cache
def druk(s):
with open('/tmp/zupa', 'a') as f:
f.write(s + "\n")
class Application(object):
def __init__(self, conf):
self.reche... | apache-2.0 | Python |
85de4ba8e67ad2483ebfad1d7ff5553d89a6d771 | Fix few errors in env_dump.py. | M4sse/chromium.src,ChromiumWebApps/chromium,ondra-novak/chromium.src,fujunwei/chromium-crosswalk,axinging/chromium-crosswalk,Jonekee/chromium.src,ChromiumWebApps/chromium,Chilledheart/chromium,hgl888/chromium-crosswalk-efl,hgl888/chromium-crosswalk-efl,dednal/chromium.src,Just-D/chromium-1,Jonekee/chromium.src,Chromium... | build/env_dump.py | build/env_dump.py | #!/usr/bin/python
# Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
# This script can either source a file and dump the enironment changes done by
# it, or just simply dump the current environment as JSON in... | #!/usr/bin/python
# Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
# This script can either source a file and dump the enironment changes done by
# it, or just simply dump the current environment as JSON in... | bsd-3-clause | Python |
e44e1c1cab7e7ed660daf00a34d077474506e04e | Bump version | theonion/django-bulbs,theonion/django-bulbs,theonion/django-bulbs,theonion/django-bulbs,theonion/django-bulbs | bulbs/__init__.py | bulbs/__init__.py | __version__ = "3.13.0"
| __version__ = "3.12.4"
| mit | Python |
685a5ab6b111685c3429b953adafcbf8293069be | make it a bit more robust | akrherz/iem,akrherz/iem,akrherz/iem,akrherz/iem,akrherz/iem | scripts/week/plot_obs.py | scripts/week/plot_obs.py | # Generate analysis of precipitation
import sys, os, random
sys.path.append("../lib/")
import iemplot
import mx.DateTime
now = mx.DateTime.now()
from pyIEM import iemdb
i = iemdb.iemdb()
iem = i['iem']
# Compute normal from the climate database
sql = """
select station,
x(geom) as lon, y(geom) as lat,
sum(pda... | # Generate analysis of precipitation
import sys, os, random
sys.path.append("../lib/")
import iemplot
import mx.DateTime
now = mx.DateTime.now()
from pyIEM import iemdb
i = iemdb.iemdb()
iem = i['iem']
# Compute normal from the climate database
sql = """
select station,
x(geom) as lon, y(geom) as lat,
sum(pda... | mit | Python |
0428522c8df724ce49a32686676b2c5345abfda9 | Add format parameter to strf functions | ivanprjcts/sdklib,ivanprjcts/sdklib | sdklib/util/timetizer.py | sdklib/util/timetizer.py | import time
import datetime
def get_current_utc(time_format="%Y-%m-%d %H:%M:%S"):
"""
@return a string representation of the current time in UTC.
"""
return time.strftime(time_format, time.gmtime())
def today_strf(format="%d/%m/%Y"):
t = datetime.date.today()
return t.strftime(format)
def ... | import time
import datetime
def get_current_utc(time_format="%Y-%m-%d %H:%M:%S"):
"""
@return a string representation of the current time in UTC.
"""
return time.strftime(time_format, time.gmtime())
def today_strf():
t = datetime.date.today()
return t.strftime("%d/%m/%Y")
def tomorrow_strf... | bsd-2-clause | Python |
24dd06300216f865d829eb45776675faf0badc1f | Improve on parsing logic. | TeskaLabs/SeaCat-Client-Python3 | seacat/spdy/spd3_ping.py | seacat/spdy/spd3_ping.py | import struct
from .spdy import *
def build_ping_frame(frame, ping_id):
frame_len = struct.calcsize('!HHII')
assert((frame.position + frame_len) <= frame.capacity)
struct.pack_into('!HHII', frame.data, frame.position,
CNTL_FRAME_VERSION_SPD3, CNTL_FRAME_TYPE_PING,
(frame_len - SPDY_HEADER_SIZE) & 0x00FFFFFF,
... | import struct
from .spdy import *
def build_ping_frame(frame, ping_id):
frame_len = struct.calcsize('!HHII')
assert((frame.position + frame_len) <= frame.capacity)
struct.pack_into('!HHII', frame.data, frame.position,
CNTL_FRAME_VERSION_SPD3, CNTL_FRAME_TYPE_PING,
(frame_len - SPDY_HEADER_SIZE) & 0x00FFFFFF,
... | bsd-3-clause | Python |
ae40b1f5cc31b452fcd65eaa55fa00a050f5e3ec | Add a scalar time independent observable to the example run_h5md | khinsen/pyh5md,MrTheodor/pyh5md | examples/run_h5md.py | examples/run_h5md.py | # Copyright 2012-2013 Pierre de Buyl
#
# This file is part of pyh5md
#
# pyh5md is free software and is licensed under the modified BSD license (see
# LICENSE file).
import numpy as np
import pyh5md
f = pyh5md.H5MD_File('particles_3d.h5', 'w', creator='run_h5md', creator_version='0', author='Pierre de Buyl')
# Creat... | # Copyright 2012-2013 Pierre de Buyl
#
# This file is part of pyh5md
#
# pyh5md is free software and is licensed under the modified BSD license (see
# LICENSE file).
import numpy as np
import pyh5md
f = pyh5md.H5MD_File('particles_3d.h5', 'w', creator='run_h5md', creator_version='0', author='Pierre de Buyl')
# Creat... | bsd-3-clause | Python |
347f0cf562c366b33e293770953d100fa9d3bb96 | Fix examples/run_quil.py | rigetticomputing/pyquil | examples/run_quil.py | examples/run_quil.py | #!/usr/bin/env python
"""
This module runs basic Quil text files against the Forest QVM API.
"""
from __future__ import print_function
from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter
from pyquil import Program, get_qc
help_string = "Script takes two arguments. Quil program filename is required as ... | #!/usr/bin/env python
"""
This module runs basic Quil text files against the Forest QVM API.
"""
from __future__ import print_function
from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter
from pyquil.quil import Program
from pyquil import api
qvm = api.QVMConnection()
help_string = "Script takes two a... | apache-2.0 | Python |
22751313f6e221c009aeb0673e531894d1645c41 | Use 1080p as default window size | Contraz/demosys-py | examples/settings.py | examples/settings.py | import os
PROJECT_DIR = os.path.dirname(os.path.abspath(__file__))
SCREENSHOT_PATH = None
OPENGL = {
"version": (3, 3),
}
WINDOW = {
"class": "demosys.context.pyqt.Window",
"size": (1920, 1080),
"aspect_ratio": 16 / 9,
"fullscreen": False,
"resizable": False,
"title": "Examples",
"vsy... | import os
PROJECT_DIR = os.path.dirname(os.path.abspath(__file__))
SCREENSHOT_PATH = None
OPENGL = {
"version": (3, 3),
}
WINDOW = {
"class": "demosys.context.pyqt.Window",
"size": (1280, 720),
"aspect_ratio": 16 / 9,
"fullscreen": False,
"resizable": False,
"title": "Examples",
"vsyn... | isc | Python |
c04872d00a26e9bf0f48eeacb360b37ce0fba01e | Use new interface for twine | relekang/python-semantic-release,relekang/python-semantic-release | semantic_release/pypi.py | semantic_release/pypi.py | """PyPI
"""
from invoke import run
from twine import settings
from twine.commands import upload as twine_upload
def upload_to_pypi(
dists: str = 'sdist bdist_wheel',
username: str = None,
password: str = None,
skip_existing: bool = False
):
"""Creates the wheel and uploads to pypi ... | """PyPI
"""
from invoke import run
from twine.commands import upload as twine_upload
def upload_to_pypi(
dists: str = 'sdist bdist_wheel',
username: str = None,
password: str = None,
skip_existing: bool = False
):
"""Creates the wheel and uploads to pypi with twine.
:param dis... | mit | Python |
fd0dad58403f34338b85edd83641e65a68779705 | Fix error when making first migrations in a new project | joshuaprince/Cassoundra,joshuaprince/Cassoundra,joshuaprince/Cassoundra | casslist/views.py | casslist/views.py | from django.db import OperationalError
from django.views import generic
from django.db.models import Sum
from cassupload import models
class CassListView(generic.ListView):
template_name = 'casslist/index.html'
context_object_name = 'cass_sound_list'
try:
total_plays = models.Sound.objects.all()... | from django.views import generic
from django.db.models import Sum
from cassupload import models
class CassListView(generic.ListView):
template_name = 'casslist/index.html'
context_object_name = 'cass_sound_list'
total_plays = models.Sound.objects.all().aggregate(Sum('play_count'))['play_count__sum']
... | mit | Python |
8b5d2c3a0a670c78b289fd2fc69a3b12be728298 | Add constructor | ganemone/ontheside,ganemone/ontheside,ganemone/ontheside | server/db/models/User.py | server/db/models/User.py | from app_factory import db
from db.models.Session import Session
class User(db.Model):
__tablename__ = 'users'
id = db.Column(db.Integer, primary_key=True)
name = db.Column('name', db.String(50))
username = db.Column('username', db.String(50))
password = db.Column('password', db.String(50))
em... | from app_factory import db
from db.models.Session import Session
class User(db.Model):
__tablename__ = 'users'
id = db.Column(db.Integer, primary_key=True)
name = db.Column('name', db.String(50))
username = db.Column('username', db.String(50))
password = db.Column('password', db.String(50))
em... | mit | Python |
cd516f95227fc24575127b2cb5813abc5cc399d9 | Fix _create_invoice on sale_order_invoicing_grouping_criteria | OCA/account-invoicing,OCA/account-invoicing | sale_order_invoicing_grouping_criteria/models/sale_order.py | sale_order_invoicing_grouping_criteria/models/sale_order.py | # Copyright 2019-2020 Tecnativa - Pedro M. Baeza
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import models
class SaleOrder(models.Model):
_inherit = "sale.order"
def _get_grouping_partner(self):
"""
Get the partner who contains the grouping criteria.
On ... | # Copyright 2019-2020 Tecnativa - Pedro M. Baeza
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import models
class SaleOrder(models.Model):
_inherit = "sale.order"
def _get_grouping_partner(self):
"""
Get the partner who contains the grouping criteria.
On ... | agpl-3.0 | Python |
598e958ae96f8112e4ea1d08f10d7d67a9a1944b | Exclude Mock()s from being accepted by the static_mocker | zhilts/pymockito,zhilts/pymockito | mockito/static_mocker.py | mockito/static_mocker.py | import inspect
import mock
class StaticMocker:
"""Deals with static methods AND class methods AND with module functions.
As they all are just static, procedural-like functions, hence StaticMocker"""
def __init__(self):
self.originals = []
self.static_mocks = {}
def stub(self, stubbe... | import inspect
class StaticMocker:
"""Deals with static methods AND class methods AND with module functions.
As they all are just static, procedural-like functions, hence StaticMocker"""
def __init__(self):
self.originals = []
self.static_mocks = {}
def stub(self, stubbed_invocation)... | mit | Python |
ec87da73eb30f744f1241d3f67882d640df63ac2 | Bump version to v0.7.3. | memmett/PyWENO,memmett/PyWENO,memmett/PyWENO | version.py | version.py | version = '0.7.3'
| version = '0.7.2'
| bsd-3-clause | Python |
2139bf720e12b557db922f1811d559d7cfad233a | Set version as 1.0.1 - fix #22 | Alignak-monitoring-contrib/alignak-module-logs,Alignak-monitoring-contrib/alignak-module-log,Alignak-monitoring-contrib/alignak-module-logs,Alignak-monitoring-contrib/alignak-module-log | version.py | version.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2015-2017:
# Frédéric Mohier, frederic.mohier@alignak.net
#
"""
Alignak - Broker module for the monitoring logs
"""
# Package name
__pkg_name__ = u"alignak_module_logs"
# Module type for PyPI keywords
# Used for:
# - PyPI keywords
__module_types__ =... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2015-2017:
# Frédéric Mohier, frederic.mohier@alignak.net
#
"""
Alignak - Broker module for the monitoring logs
"""
# Package name
__pkg_name__ = u"alignak_module_logs"
# Module type for PyPI keywords
# Used for:
# - PyPI keywords
__module_types__ =... | agpl-3.0 | Python |
50b66566abc0199c2f81eb8ddae9c321eba982bf | Bump version | coders4help/volunteer_planner,coders4help/volunteer_planner,coders4help/volunteer_planner,christophmeissner/volunteer_planner,christophmeissner/volunteer_planner,christophmeissner/volunteer_planner,coders4help/volunteer_planner,christophmeissner/volunteer_planner | version.py | version.py | __version_info__ = ("4", "2", "1")
__version__ = ".".join(__version_info__)
| __version_info__ = ("4", "2", "0")
__version__ = ".".join(__version_info__)
| agpl-3.0 | Python |
e9c8d289f491a0bfc3247ef57fbab43d97522b09 | Set version as 0.4.0 | Alignak-monitoring-contrib/alignak-checks-nrpe,Alignak-monitoring-contrib/alignak-checks-nrpe | version.py | version.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2015-2017:
# Frederic Mohier, frederic.mohier@alignak.net
#
"""
Alignak - Checks pack for NRPE monitored Linux hosts/services
"""
# Package name
__pkg_name__ = u"alignak_checks_nrpe"
# Checks types for PyPI keywords
# Used for:
# - PyPI keywords
# -... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2015-2017:
# Frederic Mohier, frederic.mohier@alignak.net
#
"""
Alignak - Checks pack for NRPE monitored Linux hosts/services
"""
# Package name
__pkg_name__ = u"alignak_checks_nrpe"
# Checks types for PyPI keywords
# Used for:
# - PyPI keywords
# -... | agpl-3.0 | Python |
41f75ee9a29ca901b08261cc884c94dc3f1b2322 | Fix bad partial commit | goldsborough/changes | changes/config.py | changes/config.py | from os.path import exists, join
import click
from giturlparse import parse
from plumbum.cmd import git
import yaml
CONFIG_FILE = '.changes'
DEFAULTS = {
'changelog': 'CHANGELOG.md',
'readme': 'README.md',
}
class CLI(object):
test_command = None
pypi = None
skip_changelog = None
def __init... | from os.path import exists, join
import click
from giturlparse import parse
from plumbum.cmd import git
import yaml
CONFIG_FILE = '.changes'
DEFAULTS = {
'changelog': 'CHANGELOG.md',
'readme': 'README.md',
}
class CLI(object):
test_command = None
pypi = None
skip_changelog = None
def __init... | mit | Python |
4d1cf7fcedaab64a77ec19ad3ad8e28314f52f95 | clean up stray print statements | dedupeio/dedupe,datamade/dedupe,tfmorris/dedupe,datamade/dedupe,pombredanne/dedupe,tfmorris/dedupe,pombredanne/dedupe,dedupeio/dedupe | dedupe/labeler.py | dedupe/labeler.py | from __future__ import division
import numpy
import rlr
import random
class ActiveLearner(rlr.RegularizedLogisticRegression):
def __init__(self, data_model, candidates):
super(ActiveLearner, self).__init__()
self.data_model = data_model
self.candidates = candidates
self.d... | from __future__ import division
import numpy
import rlr
import random
class ActiveLearner(rlr.RegularizedLogisticRegression):
def __init__(self, data_model, candidates):
super(ActiveLearner, self).__init__()
self.data_model = data_model
self.candidates = candidates
self.d... | mit | Python |
372ac75f34b3ccb6dab9c6ebd1f66abb9aa2670a | fix help on spam cleanup | extertioner/django-blog-zinnia,ghachey/django-blog-zinnia,petecummings/django-blog-zinnia,marctc/django-blog-zinnia,bywbilly/django-blog-zinnia,dapeng0802/django-blog-zinnia,bywbilly/django-blog-zinnia,Fantomas42/django-blog-zinnia,Zopieux/django-blog-zinnia,extertioner/django-blog-zinnia,1844144/django-blog-zinnia,Zul... | zinnia/management/commands/spam_cleanup.py | zinnia/management/commands/spam_cleanup.py | """Spam cleanup command module for Zinnia"""
from django.contrib import comments
from django.contrib.contenttypes.models import ContentType
from django.core.management.base import NoArgsCommand
from zinnia.models.entry import Entry
class Command(NoArgsCommand):
"""
Command object for removing comments
ma... | """Spam cleanup command module for Zinnia"""
from django.contrib import comments
from django.contrib.contenttypes.models import ContentType
from django.core.management.base import NoArgsCommand
from zinnia.models.entry import Entry
class Command(NoArgsCommand):
"""
Command object for removing comments
ma... | bsd-3-clause | Python |
52b398fff97c7b2ae67c1df3f9cafb14da2c6427 | include the absolute url to the onsite page | dstufft/jutils | crate_project/apps/packages/api.py | crate_project/apps/packages/api.py | from tastypie import fields
from tastypie.resources import ModelResource
from packages.models import Package, Release
class PackageResource(ModelResource):
releases = fields.ToManyField("packages.api.ReleaseResource", "releases")
class Meta:
allowed_methods = ["get"]
include_absolute_url = T... | from tastypie import fields
from tastypie.resources import ModelResource
from packages.models import Package, Release
class PackageResource(ModelResource):
releases = fields.ToManyField("packages.api.ReleaseResource", "releases")
class Meta:
allowed_methods = ["get"]
queryset = Package.objec... | bsd-2-clause | Python |
2f4b57b2b7c5b391af615a204ad85dd04cc780d3 | Load profiles on the order page | sonicyang/chiphub,sonicyang/chiphub,sonicyang/chiphub | chatroom/views.py | chatroom/views.py | from django.shortcuts import render, redirect
from django.http import HttpResponse
from django.http import HttpResponseRedirect
from login.views import isLogin
from login import auth
def index(request):
return render(request, 'index.html')
def append(request):
# open("data", "a").write(str(request.args.get("m... | from django.shortcuts import render
from django.http import HttpResponse
from django.http import HttpResponseRedirect
def index(request):
return render(request, 'index.html')
def append(request):
# open("data", "a").write(str(request.args.get("msg")) + "\n\r")
open("/tmp/data", "ab").write(request.GET['ms... | mit | Python |
b00bd11fb0730688a8dde1a51c28c10b6d42d2c6 | use CharField | sitcon-tw/arcane,m85091081/arcane,sitcon-tw/arcane,sitcon-tw/arcane,Zekt/arcane,Zekt/arcane,andy0130tw/arcane,m85091081/arcane,andy0130tw/arcane | app/user/forms.py | app/user/forms.py | from django import forms
class LoginForm(forms.Form):
password = forms.CharField(label="勇者密碼", widget=forms.PasswordInput(), help_text="應該會在識別證的前後左右 :)")
| from django import forms
class LoginForm(forms.Form):
password = forms.IntegerField(label="勇者密碼", widget=forms.PasswordInput(), help_text="應該會在識別證的前後左右 :)", max_value=999999, min_value=100000)
| agpl-3.0 | Python |
070b02c17e423e446562828af3ef69d06667472b | Add better exception to viewer resolver | ncrmro/reango,ncrmro/reango,ncrmro/ango,ncrmro/reango,ncrmro/ango,ncrmro/ango | server/users/schema/queries.py | server/users/schema/queries.py | from django.contrib.auth import get_user_model
from graphene import AbstractType, Field, String
from users.jwt_util import get_token_user_id
from .definitions import Viewer
class UserQueries(AbstractType):
viewer = Field(Viewer)
@staticmethod
def resolve_viewer(self, args, context, info):
users ... | from django.contrib.auth import get_user_model
from graphene import AbstractType, Field, String
from users.jwt_util import get_token_user_id
from .definitions import Viewer
class UserQueries(AbstractType):
viewer = Field(Viewer)
@staticmethod
def resolve_viewer(self, args, context, info):
try:
... | mit | Python |
269ba01cf6abbef6ce1f45049fd1fe8e9a774737 | add back preparer (#10558) | Azure/azure-sdk-for-python,Azure/azure-sdk-for-python,Azure/azure-sdk-for-python,Azure/azure-sdk-for-python | sdk/textanalytics/azure-ai-textanalytics/tests/test_auth_async.py | sdk/textanalytics/azure-ai-textanalytics/tests/test_auth_async.py | # coding=utf-8
# ------------------------------------
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
# ------------------------------------
import pytest
from azure.core.pipeline.transport import AioHttpTransport
from multidict import CIMultiDict, CIMultiDictProxy
from azure.ai.textanalytics... | # coding=utf-8
# ------------------------------------
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
# ------------------------------------
import pytest
from azure.core.pipeline.transport import AioHttpTransport
from multidict import CIMultiDict, CIMultiDictProxy
from azure.ai.textanalytics... | mit | Python |
44cdb4632eb927db36ead31a9963e945d21e1fc3 | clarify absolute paths and uris of static files | felliott/modular-file-renderer,CenterForOpenScience/modular-file-renderer,TomBaxter/modular-file-renderer,TomBaxter/modular-file-renderer,CenterForOpenScience/modular-file-renderer,felliott/modular-file-renderer,CenterForOpenScience/modular-file-renderer,mfraezz/modular-file-renderer,TomBaxter/modular-file-renderer,Add... | mfr_tabular/render.py | mfr_tabular/render.py | import json
import os
import mfr
from .exceptions import TableTooBigException, EmptyTableException, MissingRequirementsException
from mfr.core import RenderResult, get_file_extension
from mako.template import Template
from .configuration import config
def render_html(fp, src=None):
"""Render a tabular file to htm... | import json
import os
import mfr
from .exceptions import TableTooBigException, EmptyTableException, MissingRequirementsException
from mfr.core import RenderResult, get_file_extension
from mako.template import Template
from .configuration import config
def render_html(fp, src=None):
"""Render a tabular file to htm... | apache-2.0 | Python |
c203cd61738b4cbcd86d180caed1b9cbb7cce59e | Update url filtering | tobi-wan-kenobi/bumblebee-status,tobi-wan-kenobi/bumblebee-status | bumblebee/modules/pacman.py | bumblebee/modules/pacman.py | # pylint: disable=C0111,R0903
"""Displays update information per repository for pacman."
Requires the following executables:
* fakeroot
* pacman
"""
import os
import threading
import bumblebee.input
import bumblebee.output
import bumblebee.engine
#list of repositories.
#the last one sould always be other
r... | # pylint: disable=C0111,R0903
"""Displays update information per repository for pacman."
Requires the following executables:
* fakeroot
* pacman
"""
import os
import threading
import bumblebee.input
import bumblebee.output
import bumblebee.engine
#list of repositories.
#the last one sould always be other
r... | mit | Python |
8f79ac25cd29169da6385e97cfe17937aeceb542 | Reorder functions in json.py | rec/BiblioPixel,ManiacalLabs/BiblioPixel,ManiacalLabs/BiblioPixel,rec/BiblioPixel,ManiacalLabs/BiblioPixel,rec/BiblioPixel,ManiacalLabs/BiblioPixel,rec/BiblioPixel | bibliopixel/util/json.py | bibliopixel/util/json.py | import json, os, sys, yaml
# Allow open to be patched for tests.
open = __builtins__['open']
def dumps(data, **kwds):
"""
Dumps data into a nicely formatted JSON string.
:param dict data: a dictionary to dump
:param kwds: keywords to pass to json.dumps
:returns: a string with formatted data
... | import json, os, sys, yaml
# Allow open to be patched for tests.
open = __builtins__['open']
def dumps(data, **kwds):
"""
Dumps data into a nicely formatted JSON string.
:param dict data: a dictionary to dump
:param kwds: keywords to pass to json.dumps
:returns: a string with formatted data
... | mit | Python |
2e3dbbb582dc1c42774497e678218bee9e35b153 | Add experience table | Ditoeight/Pyranitar | experience_tables.py | experience_tables.py | """Pokemon Experience Tables
"""
class ExperienceTables:
'The table is a dictionary of the groups with a dictionary of levels'
def __init__(self):
#Level 1 included by default.
self.exp_tables = {'erratic' : {0 : 1},
'fast' : {0 : 1},
... | """Experience Tables
"""
#Build out experience tables for use in the experience module
| mit | Python |
e696fa2d398eb331cd5e25b2085b9d5c1e892aa1 | Add test to validate time ranges | CartoDB/geocoder-api,CartoDB/dataservices-api,CartoDB/dataservices-api,CartoDB/geocoder-api,CartoDB/geocoder-api,CartoDB/dataservices-api,CartoDB/geocoder-api,CartoDB/dataservices-api | server/lib/python/cartodb_services/test/test_mapboxtrueisoline.py | server/lib/python/cartodb_services/test/test_mapboxtrueisoline.py | import unittest
from mock import Mock
from cartodb_services.mapbox.true_isolines import MapboxTrueIsolines, DEFAULT_PROFILE
from cartodb_services.tools import Coordinate
from credentials import mapbox_api_key
VALID_ORIGIN = Coordinate(-73.989, 40.733)
class MapboxTrueIsolinesTestCase(unittest.TestCase):
def se... | import unittest
from mock import Mock
from cartodb_services.mapbox.true_isolines import MapboxTrueIsolines, DEFAULT_PROFILE
from cartodb_services.tools import Coordinate
from credentials import mapbox_api_key
VALID_ORIGIN = Coordinate(-73.989, 40.733)
class MapboxTrueIsolinesTestCase(unittest.TestCase):
def se... | bsd-3-clause | Python |
553a037a2c52b2d4361577245943dc5eabdceb39 | Make view predicates check for CSRF after rework | matslindh/kimochi,matslindh/kimochi | kimochi/views/site.py | kimochi/views/site.py | from pyramid.view import (
view_config,
)
from pyramid.httpexceptions import (
HTTPBadRequest,
HTTPSeeOther,
)
from ..models import (
User,
Site,
DBSession,
)
from pyramid.security import (
authenticated_userid,
)
@view_config(route_name='index', renderer='kimochi:templates/index.ma... | from pyramid.view import (
view_config,
)
from pyramid.httpexceptions import (
HTTPBadRequest,
HTTPSeeOther,
)
from ..models import (
User,
Site,
DBSession,
)
from pyramid.security import (
authenticated_userid,
)
@view_config(route_name='index', renderer='kimochi:templates/index.ma... | mit | Python |
a2c0253eab3803f39320741f9e47041b22af1cd4 | fix flake8 | hydroshare/hydroshare,hydroshare/hydroshare,hydroshare/hydroshare,hydroshare/hydroshare,hydroshare/hydroshare | hs_core/management/commands/solr_sort.py | hs_core/management/commands/solr_sort.py | """
This tests sorting of SOLR resources.
"""
from django.core.management.base import BaseCommand
from haystack.query import SearchQuerySet
def debug_harvest():
sqs = SearchQuerySet().all().order_by('author_lower')
for s in sqs:
print("author: " + s.author)
print("author_lower: " + s.author_l... | """
This tests sorting of SOLR resources.
"""
from django.core.management.base import BaseCommand
from django.db.models import Q
from hs_core.models import BaseResource
from hs_core.search_indexes import BaseResourceIndex
from pprint import pprint
from haystack.query import SearchQuerySet
def debug_harvest():
s... | bsd-3-clause | Python |
af97343e3920409de559954d4b1f811711deed5f | Remove debugging statement | snowball-one/cid | cid/middleware.py | cid/middleware.py | from django.conf import settings
from cid.locals import generate_new_cid
from cid.locals import get_cid
from cid.locals import set_cid
class CidMiddleware:
"""
Middleware class to extract the correlation id from incoming headers
and add them to outgoing headers
"""
def __init__(self, get_respons... | from django.conf import settings
from cid.locals import generate_new_cid
from cid.locals import get_cid
from cid.locals import set_cid
class CidMiddleware:
"""
Middleware class to extract the correlation id from incoming headers
and add them to outgoing headers
"""
def __init__(self, get_respons... | bsd-3-clause | Python |
828740ee0f2e62799b955378efebce8f5fb28176 | Fix path | muescha/hutmap,dylanfprice/hutmap,muescha/hutmap,muescha/hutmap,dylanfprice/hutmap,dylanfprice/hutmap,dylanfprice/hutmap,muescha/hutmap | huts/management/commands/dumphutsjson.py | huts/management/commands/dumphutsjson.py | import os
from optparse import make_option
from django.conf import settings
from django.core.management.base import BaseCommand
from huts.utils import export
class Command(BaseCommand):
option_list = BaseCommand.option_list + (
make_option(
'--update',
action='store_true',
... | import os
from optparse import make_option
from django.conf import settings
from django.core.management.base import BaseCommand
from huts.utils import export
class Command(BaseCommand):
option_list = BaseCommand.option_list + (
make_option(
'--update',
action='store_true',
... | mit | Python |
cf11903f15d25ee3a6028046b9405b11cc786acd | Update cached.py | Coal0/Utilities | cached/cached.py | cached/cached.py | import functools
def cached(name):
def wrapper(function):
@functools.wraps(function)
def call(self, *args, **kwargs):
if not hasattr(self, name):
return_value = function(self, *args, **kwargs)
setattr(self, name, return_value)
return getattr(s... | def cached(name):
def wrapper(function):
def call(self, *args, **kwargs):
if not hasattr(self, name):
return_value = function(self, *args, **kwargs)
setattr(self, name, return_value)
return getattr(self, name)
return call
return wrapper
| mit | Python |
6c1f5dc57d11edb30c2e0fcd9b9aa77c77a68f12 | Update running code | will-hart/twitter_sentiment,will-hart/twitter_sentiment | classifier/run.py | classifier/run.py | import time
from clean_tweet import TweetClassifier as TC
from gather_data import GatherData
def run_test(val, expected):
print "{0} (exp {1}) >> {2}".format(t.predict(val), expected, val)
# Start by gathering some data
g = GatherData()
g.gather_tweets()
g.write_tweets("train_data.txt")
time.sleep(3)
g.gather_... | import time
from clean_tweet import TweetClassifier as TC
from gather_data import GatherData
def run_test(val, expected):
print "{0} (exp {1}) >> {2}".format(t.predict(val), expected, val)
# Start by gathering some data
g = GatherData()
g.gather_tweets()
g.write_tweets("train_data.txt")
time.sleep(3)
g.gather_... | mit | Python |
1e28f1c3c6eb6f9e57d6de9c5c22b409502b073c | Remove redundant print | atugushev/django-static-pages | static_pages/tests/tests.py | static_pages/tests/tests.py | import codecs
import os
import shutil
from django.conf import settings
from django.core.management import CommandError
from django.test import SimpleTestCase
from django.test.utils import override_settings
from django.utils.encoding import force_text
from static_pages.management.commands import generate_static_pages
... | import codecs
import os
import shutil
from django.conf import settings
from django.core.management import CommandError
from django.test import SimpleTestCase
from django.test.utils import override_settings
from django.utils.encoding import force_text
from static_pages.management.commands import generate_static_pages
... | mit | Python |
4171d2868d457f8f5d0f449df9c3505154f9a101 | Update __init__.py | h2non/filetype.py | filetype/__init__.py | filetype/__init__.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import
from .filetype import * # noqa
from .helpers import * # noqa
from .match import * # noqa
# Current package semver version
__version__ = version = '1.0.9'
| # -*- coding: utf-8 -*-
from __future__ import absolute_import
from .filetype import * # noqa
from .helpers import * # noqa
from .match import * # noqa
# Current package semver version
__version__ = version = '1.0.8'
| mit | Python |
79812c28e33677e0e63e0064ba9466c71a5d8448 | use old layout in test settings | praekelt/molo-tuneme,praekelt/molo-tuneme,praekelt/molo-tuneme,praekelt/molo-tuneme | test_settings.py | test_settings.py | from tuneme.settings import * # noqa
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'ndohyep_test.db',
}
}
WAGTAILSEARCH_BACKENDS = {
'default': {
'BACKEND': 'wagtail.wagtailsearch.backends.db.DBSearch',
}
}
DEBUG = True
CELERY_ALWAYS_EAGER = True
S... | from tuneme.settings import * # noqa
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'ndohyep_test.db',
}
}
WAGTAILSEARCH_BACKENDS = {
'default': {
'BACKEND': 'wagtail.wagtailsearch.backends.db.DBSearch',
}
}
DEBUG = True
CELERY_ALWAYS_EAGER = True
| bsd-2-clause | Python |
944a724235515423eb56ccc8ded3f91163b38315 | update test settings | Miserlou/Zappa,pjz/Zappa,pjz/Zappa,longzhi/Zappa,longzhi/Zappa,mathom/Zappa,scoates/Zappa,michi88/Zappa,anush0247/Zappa,michi88/Zappa,scoates/Zappa,parroyo/Zappa,mathom/Zappa,Miserlou/Zappa,parroyo/Zappa,anush0247/Zappa | test_settings.py | test_settings.py | APP_MODULE = 'tests.test_app'
APP_FUNCTION = 'hello_world'
DEBUG = 'True'
LOG_LEVEL = 'DEBUG'
SCRIPT_NAME = 'hello_world'
DOMAIN = None
API_STAGE = 'ttt555'
def prebuild_me():
print("This is a prebuild script!")
| APP_MODULE = 'tests.test_app'
APP_FUNCTION = 'hello_world'
DEBUG = 'True'
LOG_LEVEL = 'DEBUG'
SCRIPT_NAME = 'hello_world'
def prebuild_me():
print("This is a prebuild script!")
| mit | Python |
9224718eb4a690f5389f2b4b54f690c9b1681dae | Fix map() usage on Py3. | HIPS/autograd,hips/autograd,hips/autograd,HIPS/autograd | autograd/errors.py | autograd/errors.py | import sys
import re
from future.utils import raise_from, raise_
class AutogradHint(Exception):
def __init__(self, message, subexception_type=None, subexception_val=None):
self.message = message
self.subexception_type = subexception_type
self.subexception_val = subexception_val
def __s... | import sys
import re
from future.utils import raise_from, raise_
class AutogradHint(Exception):
def __init__(self, message, subexception_type=None, subexception_val=None):
self.message = message
self.subexception_type = subexception_type
self.subexception_val = subexception_val
def __s... | mit | Python |
4c102ee3ffc9990c5e810d59849927505da4e288 | update information | erlinux/ToolsProject,erlinux/ToolsProject | Data/collectionhouse/mayi/contect_of_url.py | Data/collectionhouse/mayi/contect_of_url.py | #!/bin/env python3
import bs4,requests,re,time
def writeList(location="./"):
response = requests.get("http://www.mayi.com/shanghai/1")
response.encoding="utf-8"
soup = bs4.BeautifulSoup(response.content,"lxml")
for i2031 in set(soup.select('#page > input[type="hidden"]')):
# 话说我在弄一个个人的房屋项目,计算什么... | #!/bin/env python3
# -*- coding:utf-8 -*-
import bs4,requests,re,time
def writeList(location="./"):
response = requests.get("http://www.mayi.com/shanghai/1")
soup = bs4.BeautifulSoup(response.content,"lxml")
for i2031 in soup.select("#page > a:nth-of-type(7)"): i2034 = int(i2031.get_text())
for i2036 i... | mit | Python |
3bf5d36237e6d0cf666f57c17982599e85e9c0cf | Make some variables and messages not specific to OPLS (#154) | mosdef-hub/foyer,mosdef-hub/foyer,iModels/foyer,iModels/foyer | foyer/tests/utils.py | foyer/tests/utils.py | import glob
from os.path import join, split, abspath
import numpy as np
def atomtype(structure, forcefield, non_atomistic=False):
"""Compare known atomtypes to those generated by foyer.
Parameters
----------
structure : parmed.Structure
A parmed structure with `atom.type` attributes.
for... | import glob
from os.path import join, split, abspath
import numpy as np
def atomtype(structure, forcefield, non_atomistic=False):
"""Compare known atomtypes to those generated by foyer.
Parameters
----------
structure : parmed.Structure
A parmed structure with `atom.type` attributes.
for... | mit | Python |
eb51e20d5519e472ed45a2fc53c6963705494620 | Improve setup.py with more package information. | chandler14362/Bamboo,chandler14362/Bamboo,chandler14362/Bamboo | bindings/python/setup.py | bindings/python/setup.py | #!/usr/bin/python
from distutils.core import setup, Extension
import os
scriptDir = os.path.dirname(os.path.realpath(__file__))
buildDir = os.path.join(scriptDir, '../../build')
includeDirs = [buildDir, os.path.join(scriptDir, '../../src')]
libraryDirs = [buildDir]
module = Extension('bamboo',
include_dirs = incl... | #!/usr/bin/python
from distutils.core import setup, Extension
import os
scriptDir = os.path.dirname(os.path.realpath(__file__))
buildDir = os.path.join(scriptDir, '../../build')
includeDirs = [buildDir, os.path.join(scriptDir, '../../src')]
libraryDirs = [buildDir]
module = Extension('bamboo',
include_dirs = incl... | bsd-3-clause | Python |
197ba561ba3ff113969f2c2c1ce1308acc7b1e92 | use spherical if so | adrn/gala,adrn/gary,adrn/gary,adrn/gala,adrn/gary,adrn/gala | streamteam/potential/apw.py | streamteam/potential/apw.py | # coding: utf-8
""" Potential used in Price-Whelan et al. (in prep.) TODO """
from __future__ import division, print_function
__author__ = "adrn <adrn@astro.columbia.edu>"
# Third-party
from astropy.constants import G
import numpy as np
# Project
# from .core import CartesianCompositePotential
from .cpotential imp... | # coding: utf-8
""" Potential used in Price-Whelan et al. (in prep.) TODO """
from __future__ import division, print_function
__author__ = "adrn <adrn@astro.columbia.edu>"
# Third-party
from astropy.constants import G
import numpy as np
# Project
# from .core import CartesianCompositePotential
from .cpotential imp... | mit | Python |
41b66fa93edc1c5dcd3d4cc28750971fc33eb6a1 | Create attachment class | lises/sheldon | sheldon/basic_classes.py | sheldon/basic_classes.py | # -*- coding: utf-8 -*-
"""
Declaration of classes needed for bot working:
Adapter class, Plugin class
@author: Lises team
@contact: zhidkovseva@gmail.com
@license: The MIT license
Copyright (C) 2015
"""
from time import sleep
class Adapter:
"""
Adapter class contains information about adapter:
name, ... | # -*- coding: utf-8 -*-
"""
Declaration of classes needed for bot working:
Adapter class, Plugin class
@author: Lises team
@contact: zhidkovseva@gmail.com
@license: The MIT license
Copyright (C) 2015
"""
from time import sleep
class Adapter:
"""
Adapter class contains information about adapter:
name, ... | mit | Python |
c7d2a70c02ab2565a134cd0937ac5ba42437fea6 | fix test | eEcoLiDAR/eEcoLiDAR | laserchicken/feature_extractor/test_percentile.py | laserchicken/feature_extractor/test_percentile.py | import os
import random
import unittest
from laserchicken import read_las
from laserchicken.feature_extractor.percentile_feature_extractor import PercentileFeatureExtractor
class TestPercentileFeatureExtractor(unittest.TestCase):
def test_percentile(self):
print(os.getcwd())
print(os.path.exists(... | import os
import random
import unittest
from laserchicken import read_las
from laserchicken.feature_extractor.percentile_feature_extractor import PercentileFeatureExtractor
class TestPercentileFeatureExtractor(unittest.TestCase):
def test_percentile(self):
print(os.getcwd())
print(os.path.exists(... | apache-2.0 | Python |
0ff41ef99e348022f8f46ff7935ed6d4bad1b08c | Add alternative string for email icon | edwinksl/edwinksl.github.io,edwinksl/edwinksl.github.io,edwinksl/edwinksl.github.io,edwinksl/edwinksl.github.io | pelicanconf.py | pelicanconf.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
AUTHOR = 'Edwin Khoo'
SITENAME = 'Edwin Khoo'
SITEURL = ''
PATH = 'content'
TIMEZONE = 'America/New_York'
DEFAULT_LANG = 'en'
# Feed generation is usually not desired when developing
FEED_ALL_ATOM = None
CATEGORY_FEED_ATOM = None
TRANSLATION_FEED_ATOM = None
AUTHOR_FEE... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
AUTHOR = 'Edwin Khoo'
SITENAME = 'Edwin Khoo'
SITEURL = ''
PATH = 'content'
TIMEZONE = 'America/New_York'
DEFAULT_LANG = 'en'
# Feed generation is usually not desired when developing
FEED_ALL_ATOM = None
CATEGORY_FEED_ATOM = None
TRANSLATION_FEED_ATOM = None
AUTHOR_FEE... | mit | Python |
597fbe0a22f9c3333c330c8091a232a69e7ac3fd | Add CORS | nlesc-ave/ave-rest-service | avedata/avedata.py | avedata/avedata.py | import os
import connexion
from flask import Flask, request, session, g, redirect, url_for, abort, \
render_template, flash
from flask_corse import CORS
connexion_app = connexion.App(__name__, specification_dir='../')
app = connexion_app.app
CORS(app)
app.config.update(dict(
DATABASE='ave.db'
))
app.conf... | import os
import connexion
from flask import Flask, request, session, g, redirect, url_for, abort, \
render_template, flash
connexion_app = connexion.App(__name__, specification_dir='../')
app = connexion_app.app
app.config.update(dict(
DATABASE='ave.db'
))
app.config.from_pyfile(os.path.join(os.getcwd(... | apache-2.0 | Python |
bdab267bda771ba002f9172b93ec05d20ad05cef | Add GeoDjango to INSTALLED_APPS | LitPalimpsest/parser-api-search,LitPalimpsest/parser-api-search,LitPalimpsest/parser-api-search | site/litlong/settings.py | site/litlong/settings.py | """
Django settings for litlong project.
For more information on this file, see
https://docs.djangoproject.com/en/1.7/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.7/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
im... | """
Django settings for litlong project.
For more information on this file, see
https://docs.djangoproject.com/en/1.7/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.7/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
im... | mit | Python |
b09161bbff481d67de6d4b838b68e7fb64582be0 | Make utils.now() timezone aware. | thiderman/piper | piper/utils.py | piper/utils.py | import os
import errno
import subprocess as sub
import datetime
from collections import OrderedDict
class LimitedSizeDict(OrderedDict): # pragma: nocover
"""
A dict that pops items when it reaches a set size.
This can be used as a cache that will not expontentially grow forever.
http://stackoverflow... | import os
import errno
import subprocess as sub
import datetime
from collections import OrderedDict
class LimitedSizeDict(OrderedDict): # pragma: nocover
"""
A dict that pops items when it reaches a set size.
This can be used as a cache that will not expontentially grow forever.
http://stackoverflow... | mit | Python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.