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
56186c985b87fbbf0a7ea0f04c8b089a13b29fe3
execute_all_tests.py
execute_all_tests.py
#! /bin/python3 """ 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) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. """ import os import sys from coalib.tests.TestHelper import TestHelper def show_help(): print("Usage: {name} [OPTIONS]".format(name=sys.argv[0])) print() print("--help : Show this help text") print("--cover : Use coverage to get statement and branch coverage of tests") if __name__ == '__main__': use_coverage = False for arg in sys.argv[1:]: arg = str(arg).strip().lower() if arg == "--cover" and not use_coverage: use_coverage = True else: show_help() exit() test_dir = os.path.abspath("coalib/tests") files = TestHelper.get_test_files(test_dir) exit(TestHelper.execute_python3_files(files, use_coverage))
#! /bin/python3 """ 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) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. """ import os import sys from coalib.tests.TestHelper import TestHelper def show_help(): print("Usage: {name} [OPTIONS]".format(name=sys.argv[0])) print() print("--help : Show this help text") print("--cover : Use coverage to get statement and branch coverage of tests") if __name__ == '__main__': use_coverage = False for arg in sys.argv[1:]: arg = str(arg).strip().lower() if arg == "--cover" and not use_coverage: use_coverage = True else: show_help() exit() files = TestHelper.get_test_files(os.path.abspath("coalib/tests")) exit(TestHelper.execute_python3_files(files, use_coverage))
Test execution: Remove unneeded variable
Test execution: Remove unneeded variable
Python
agpl-3.0
Tanmay28/coala,Tanmay28/coala,meetmangukiya/coala,arush0311/coala,NalinG/coala,Tanmay28/coala,incorrectusername/coala,yashtrivedi96/coala,shreyans800755/coala,sagark123/coala,jayvdb/coala,MariosPanag/coala,Nosferatul/coala,vinc456/coala,damngamerz/coala,MattAllmendinger/coala,ManjiriBirajdar/coala,andreimacavei/coala,rresol/coala,AdeshAtole/coala,kartikeys98/coala,NalinG/coala,karansingh1559/coala,coala/coala,SambitAcharya/coala,Uran198/coala,Tanmay28/coala,nemaniarjun/coala,coala/coala,jayvdb/coala,netman92/coala,lonewolf07/coala,andreimacavei/coala,SanketDG/coala,d6e/coala,NiklasMM/coala,tltuan/coala,SanketDG/coala,refeed/coala,rimacone/testing2,SambitAcharya/coala,abhiroyg/coala,arush0311/coala,svsn2117/coala,shreyans800755/coala,sils1297/coala,arjunsinghy96/coala,rresol/coala,AbdealiJK/coala,tushar-rishav/coala,AdeshAtole/coala,NiklasMM/coala,arafsheikh/coala,scriptnull/coala,aptrishu/coala,scriptnull/coala,MattAllmendinger/coala,yland/coala,AbdealiJK/coala,SambitAcharya/coala,ayushin78/coala,arjunsinghy96/coala,yashtrivedi96/coala,FeodorFitsner/coala,SanketDG/coala,andreimacavei/coala,sils1297/coala,JohnS-01/coala,nemaniarjun/coala,mr-karan/coala,rimacone/testing2,karansingh1559/coala,incorrectusername/coala,yashLadha/coala,coala-analyzer/coala,NalinG/coala,NiklasMM/coala,saurabhiiit/coala,saurabhiiit/coala,MattAllmendinger/coala,NalinG/coala,karansingh1559/coala,Nosferatul/coala,Nosferatul/coala,ayushin78/coala,CruiseDevice/coala,d6e/coala,djkonro/coala,ManjiriBirajdar/coala,rimacone/testing2,sagark123/coala,SambitAcharya/coala,RJ722/coala,stevemontana1980/coala,kartikeys98/coala,NalinG/coala,Asnelchristian/coala,Tanmay28/coala,Uran198/coala,Shade5/coala,stevemontana1980/coala,incorrectusername/coala,Balaji2198/coala,RJ722/coala,swatilodha/coala,ManjiriBirajdar/coala,Tanmay28/coala,MariosPanag/coala,aptrishu/coala,sophiavanvalkenburg/coala,sils1297/coala,coala-analyzer/coala,RJ722/coala,arush0311/coala,saurabhiiit/coala,svsn2117/coala,vinc456/coala,refeed/coala,sophiavanvalkenburg/coala,impmihai/coala,meetmangukiya/coala,yashLadha/coala,djkonro/coala,svsn2117/coala,Shade5/coala,netman92/coala,scriptnull/coala,abhiroyg/coala,JohnS-01/coala,damngamerz/coala,tushar-rishav/coala,arafsheikh/coala,abhiroyg/coala,CruiseDevice/coala,lonewolf07/coala,ayushin78/coala,SambitAcharya/coala,sagark123/coala,tushar-rishav/coala,yland/coala,jayvdb/coala,shreyans800755/coala,JohnS-01/coala,Balaji2198/coala,impmihai/coala,swatilodha/coala,sophiavanvalkenburg/coala,stevemontana1980/coala,dagdaggo/coala,CruiseDevice/coala,coala/coala,netman92/coala,scriptnull/coala,scottbelden/coala,tltuan/coala,Asalle/coala,sudheesh001/coala,Uran198/coala,MariosPanag/coala,djkonro/coala,mr-karan/coala,SambitAcharya/coala,coala-analyzer/coala,meetmangukiya/coala,scriptnull/coala,swatilodha/coala,dagdaggo/coala,Tanmay28/coala,scottbelden/coala,impmihai/coala,dagdaggo/coala,FeodorFitsner/coala,vinc456/coala,AbdealiJK/coala,rresol/coala,NalinG/coala,d6e/coala,Shade5/coala,Asalle/coala,Tanmay28/coala,nemaniarjun/coala,Balaji2198/coala,lonewolf07/coala,arjunsinghy96/coala,yashtrivedi96/coala,aptrishu/coala,Asnelchristian/coala,yashLadha/coala,NalinG/coala,scriptnull/coala,arafsheikh/coala,scottbelden/coala,scriptnull/coala,kartikeys98/coala,yland/coala,AdeshAtole/coala,tltuan/coala,refeed/coala,Asnelchristian/coala,damngamerz/coala,mr-karan/coala,FeodorFitsner/coala,sudheesh001/coala,Asalle/coala,sudheesh001/coala,SambitAcharya/coala
--- +++ @@ -37,6 +37,5 @@ show_help() exit() - test_dir = os.path.abspath("coalib/tests") - files = TestHelper.get_test_files(test_dir) + files = TestHelper.get_test_files(os.path.abspath("coalib/tests")) exit(TestHelper.execute_python3_files(files, use_coverage))
39f327bb9e37d6d290eb3f3179f7e79d60b5ab6d
model.py
model.py
from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import create_engine engine = create_engine('postgresql://wn:wn@localhost:5432/wndb') Base = declarative_base() from sqlalchemy import Column, Integer, Float, DateTime, Boolean, String class Observation(Base): __tablename__ = 'obs' id = Column(Integer, primary_key=True) station_name = Column(String) x = Column(Float) y = Column(Float) z = Column(Float) jam_indicator = Column(Boolean) jam_intensity = Column(Float) date_time = Column(DateTime) def __repr__(self): return "<Observation(station_name='%r', x='%f', y='%f', z='%f', jam_indicator='%r', jam_intensity='%f', date_time='%r')>" % ( self.station_name, self.x, self.y, self.z, self.jam_indicator, self.jam_intensity, self.date_time) Base.metadata.create_all(engine)
from sqlalchemy import create_engine engine = create_engine('postgresql://wn:wn@localhost:5432/wndb') from sqlalchemy import Column, Integer, Float, DateTime, Boolean, String, MetaData metadata = MetaData() table = Table('obs', metadata, Column(Integer, primary_key=True), Column('station_name',String), Column('x',Float), Column('y',Float), Column('z',Float), Column('jam_indicator',Boolean), Column('jam_intensity',Float), Column('date_time',DateTime) )
Switch from ORM to Core
Switch from ORM to Core
Python
mit
labhack/whiskeynovember,labhack/whiskeynovember,labhack/whiskeynovember
--- +++ @@ -1,26 +1,16 @@ -from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import create_engine engine = create_engine('postgresql://wn:wn@localhost:5432/wndb') -Base = declarative_base() +from sqlalchemy import Column, Integer, Float, DateTime, Boolean, String, MetaData -from sqlalchemy import Column, Integer, Float, DateTime, Boolean, String -class Observation(Base): - __tablename__ = 'obs' - - id = Column(Integer, primary_key=True) - station_name = Column(String) - x = Column(Float) - y = Column(Float) - z = Column(Float) - jam_indicator = Column(Boolean) - jam_intensity = Column(Float) - date_time = Column(DateTime) - - def __repr__(self): - return "<Observation(station_name='%r', x='%f', y='%f', z='%f', jam_indicator='%r', jam_intensity='%f', date_time='%r')>" % ( - self.station_name, self.x, self.y, self.z, self.jam_indicator, self.jam_intensity, self.date_time) - -Base.metadata.create_all(engine) - +metadata = MetaData() +table = Table('obs', metadata, Column(Integer, primary_key=True), + Column('station_name',String), + Column('x',Float), + Column('y',Float), + Column('z',Float), + Column('jam_indicator',Boolean), + Column('jam_intensity',Float), + Column('date_time',DateTime) + )
a5b89ed7aa9e2fe4305f6431a3bdd675a7eda03f
web/__init__.py
web/__init__.py
# -*- coding: utf-8 -*- from os import path from flask import Flask PACKAGE_DIR = path.dirname(path.realpath(__file__)) ROOT_DIR = path.realpath(path.join(PACKAGE_DIR, '..')) ROOT_URL = 'http://pythoncz.herokuapp.com' GITHUB_URL = ( 'https://github.com/honzajavorek/python.cz/' 'blob/master/{template_folder}/{filename}' ) app = Flask('web', static_folder=path.join(ROOT_DIR, 'files'), static_url_path='', template_folder=path.join(ROOT_DIR, 'pages')) app.config.from_object(__name__) from . import views # NOQA
# -*- coding: utf-8 -*- from os import path from flask import Flask PACKAGE_DIR = path.dirname(path.realpath(__file__)) ROOT_DIR = path.realpath(path.join(PACKAGE_DIR, '..')) ROOT_URL = 'http://pythoncz.herokuapp.com' GITHUB_URL = ( 'https://github.com/honzajavorek/python.cz/' 'blob/master/{template_folder}/{filename}' ) app = Flask('web', static_folder=path.join(ROOT_DIR, 'files'), static_url_path='', template_folder=path.join(ROOT_DIR, 'pages')) app.config.from_object(__name__) from . import views # NOQA
Fix newline at the end of file.
Fix newline at the end of file.
Python
mit
honzajavorek/python.cz,honzajavorek/python.cz,honzajavorek/python.cz,honzajavorek/python.cz
5f716da231aa3f338300295695b1513aa404ae7d
lino_xl/lib/appypod/__init__.py
lino_xl/lib/appypod/__init__.py
# Copyright 2014-2019 Rumma & Ko Ltd # License: BSD (see file COPYING for details) """ Adds functionality for generating printable documents using LibreOffice and the `appy.pod <http://appyframework.org/pod.html>`__ package. See also :ref:`lino.admin.appypod` and :doc:`/specs/appypod`. """ import six from lino.api import ad, _ class Plugin(ad.Plugin): verbose_name = _("Appy POD") def get_requirements(self, site): try: import appy # leave unchanged if it is already installed except ImportError: if six.PY3: # yield "-e svn+https://svn.forge.pallavi.be/appy-dev/dev1#egg=appy" yield "svn+https://svn.forge.pallavi.be/appy-dev/dev1#egg=appy" else: yield "appy" def get_used_libs(self, html=None): try: # ~ import appy from appy import version version = version.verbose except ImportError: version = self.site.not_found_msg yield ("Appy", version, "http://appyframework.org/pod.html")
# Copyright 2014-2019 Rumma & Ko Ltd # License: BSD (see file COPYING for details) """ Adds functionality for generating printable documents using LibreOffice and the `appy.pod <http://appyframework.org/pod.html>`__ package. See also :ref:`lino.admin.appypod` and :doc:`/specs/appypod`. """ import six from lino.api import ad, _ class Plugin(ad.Plugin): verbose_name = _("Appy POD") def get_requirements(self, site): try: import appy # leave unchanged if it is already installed except ImportError: if six.PY3: # yield "-e svn+https://svn.forge.pallavi.be/appy-dev/dev1#egg=appy" yield "svn+http://svn.forge.pallavi.be/appy-dev/dev1#egg=appy" else: yield "appy" def get_used_libs(self, html=None): try: # ~ import appy from appy import version version = version.verbose except ImportError: version = self.site.not_found_msg yield ("Appy", version, "http://appyframework.org/pod.html")
Use http instead of https
Use http instead of https
Python
bsd-2-clause
lino-framework/xl,lino-framework/xl,lino-framework/xl,lino-framework/xl
--- +++ @@ -23,7 +23,7 @@ except ImportError: if six.PY3: # yield "-e svn+https://svn.forge.pallavi.be/appy-dev/dev1#egg=appy" - yield "svn+https://svn.forge.pallavi.be/appy-dev/dev1#egg=appy" + yield "svn+http://svn.forge.pallavi.be/appy-dev/dev1#egg=appy" else: yield "appy"
b49f733d675d537779bed931d0a079888a83a735
mpfmonitor/_version.py
mpfmonitor/_version.py
# mpf-monitor __version__ = '0.3.0-dev.1' __short_version__ = '0.3' __bcp_version__ = '1.1' __config_version__ = '4' __mpf_version_required__ = '0.33.0' version = "MPF Monitor v{} (config_version={}, BCP v{}, Requires MPF v{})".format( __version__, __config_version__, __bcp_version__, __mpf_version_required__)
# mpf-monitor __version__ = '0.2.0-dev.3' __short_version__ = '0.2' __bcp_version__ = '1.1' __config_version__ = '4' __mpf_version_required__ = '0.33.0.dev15' version = "MPF Monitor v{} (config_version={}, BCP v{}, Requires MPF v{})".format( __version__, __config_version__, __bcp_version__, __mpf_version_required__)
Revert "Bump dev version to 0.3.0-dev.1"
Revert "Bump dev version to 0.3.0-dev.1" This reverts commit facc1caaca87e680321be0654882d6c5570bc2ad.
Python
mit
missionpinball/mpf-monitor
--- +++ @@ -1,9 +1,9 @@ # mpf-monitor -__version__ = '0.3.0-dev.1' -__short_version__ = '0.3' +__version__ = '0.2.0-dev.3' +__short_version__ = '0.2' __bcp_version__ = '1.1' __config_version__ = '4' -__mpf_version_required__ = '0.33.0' +__mpf_version_required__ = '0.33.0.dev15' version = "MPF Monitor v{} (config_version={}, BCP v{}, Requires MPF v{})".format( __version__, __config_version__, __bcp_version__, __mpf_version_required__)
3af2a5b6eda4af972e3a208e727483384f313cb9
octotribble/csv2tex.py
octotribble/csv2tex.py
#!/usr/bin/env python """Convert a CSV table into a latex tabular using pandas.""" import argparse import pandas as pd def convert(filename, transpose=False): """convert csv to tex table.""" df = pd.read_csv(filename) if transpose: df = df.transpose() tex_name = filename.replace(".csv", "_transpose.tex") else: tex_name = filename.replace(".csv", ".tex") with open(tex_name, "w") as f: f.write(r"\begin{table}") f.write("\n") f.write(r"\label{}") f.write("\n") f.write(r"\caption{}") f.write("\n") f.write(df.to_latex(na_rep="-")) f.write(r"\end{table}") f.write("\n") if __name__ == "__main__": parser = argparse.ArgumentParser(description="Convert csv to latex tabular") parser.add_argument("filename", help="Name of csv file", type=str) parser.add_argument( "-t", "--transpose", help="Transpose table", action="store_true" ) args = parser.parse_args() convert(args.filename, args.transpose)
#!/usr/bin/env python """Convert a CSV table into a latex tabular using pandas.""" import argparse import pandas as pd def convert(filename, transpose=False): """convert csv to tex table.""" df = pd.read_csv(filename) if transpose: df = df.transpose() tex_name = filename.replace(".csv", "_transpose.tex") index = True else: tex_name = filename.replace(".csv", ".tex") index=False assert tex_name != filename, "This will overwrite the file, did you pass in a csv?" latex = df.to_latex(na_rep="-", index=index) with open(tex_name, "w") as f: f.write(r"\begin{table}") f.write("\n") f.write(r"\label{}") f.write("\n") f.write(r"\caption{}") f.write("\n") f.write(latex) f.write(r"\end{table}") f.write("\n") if __name__ == "__main__": parser = argparse.ArgumentParser(description="Convert csv to latex tabular") parser.add_argument("filename", help="Name of csv file", type=str) parser.add_argument( "-t", "--transpose", help="Transpose table", action="store_true" ) args = parser.parse_args() convert(args.filename, args.transpose)
Remove index and check filename
Remove index and check filename
Python
mit
jason-neal/equanimous-octo-tribble,jason-neal/equanimous-octo-tribble,jason-neal/equanimous-octo-tribble
--- +++ @@ -12,8 +12,16 @@ if transpose: df = df.transpose() tex_name = filename.replace(".csv", "_transpose.tex") + index = True else: tex_name = filename.replace(".csv", ".tex") + index=False + + assert tex_name != filename, "This will overwrite the file, did you pass in a csv?" + + + latex = df.to_latex(na_rep="-", index=index) + with open(tex_name, "w") as f: f.write(r"\begin{table}") f.write("\n") @@ -22,7 +30,7 @@ f.write(r"\caption{}") f.write("\n") - f.write(df.to_latex(na_rep="-")) + f.write(latex) f.write(r"\end{table}") f.write("\n")
75b50ffcb6575e38e6792356dd58612089ee4f55
django_mercadopago/views.py
django_mercadopago/views.py
import logging from django.conf import settings from django.http import HttpResponse from django.views.decorators.csrf import csrf_exempt from .models import Notification, Account logger = logging.getLogger(__name__) # Maybe use a form for this? :D @csrf_exempt def create_notification(request, slug): topic = request.GET.get('topic', None) resource_id = request.GET.get('id', None) if topic is None: return HttpResponse( '<h1>400 Bad Request.</h1>' 'Missing parameter topic', status=400 ) if resource_id is None: return HttpResponse( '<h1>400 Bad Request.</h1>' 'Missing parameter id', status=400 ) if topic == 'merchant_order': topic = Notification.TOPIC_ORDER elif topic == 'payment': topic = Notification.TOPIC_PAYMENT else: return HttpResponse('invalid topic', status=400) owner = Account.objects.get(slug=slug) notification, created = Notification.objects.get_or_create( topic=topic, resource_id=resource_id, owner=owner, ) if not created: notification.processed = False notification.save() if not settings.MERCADOPAGO_ASYNC: notification.process() # TODO: Else add to some queue? return HttpResponse("<h1>200 OK</h1>", status=201)
import logging from django.conf import settings from django.http import HttpResponse from django.views.decorators.csrf import csrf_exempt from .models import Notification, Account logger = logging.getLogger(__name__) # Maybe use a form for this? :D @csrf_exempt def create_notification(request, slug): topic = request.GET.get('topic', None) resource_id = request.GET.get('id', None) if topic is None: return HttpResponse( '<h1>400 Bad Request.</h1>' 'Missing parameter topic', status=400 ) if resource_id is None: return HttpResponse( '<h1>400 Bad Request.</h1>' 'Missing parameter id', status=400 ) if topic == 'merchant_order': topic = Notification.TOPIC_ORDER elif topic == 'payment': topic = Notification.TOPIC_PAYMENT else: return HttpResponse('invalid topic', status=400) try: owner = Account.objects.get(slug=slug) except Account.DoesNotExist: return HttpResponse('Unknown account/slug', status=400) notification, created = Notification.objects.get_or_create( topic=topic, resource_id=resource_id, owner=owner, ) if not created: notification.processed = False notification.save() if not settings.MERCADOPAGO_ASYNC: notification.process() # TODO: Else add to some queue? return HttpResponse("<h1>200 OK</h1>", status=201)
Return 400 for inexistant accounts
Return 400 for inexistant accounts
Python
isc
asermax/django-mercadopago
--- +++ @@ -36,7 +36,11 @@ else: return HttpResponse('invalid topic', status=400) - owner = Account.objects.get(slug=slug) + try: + owner = Account.objects.get(slug=slug) + except Account.DoesNotExist: + return HttpResponse('Unknown account/slug', status=400) + notification, created = Notification.objects.get_or_create( topic=topic, resource_id=resource_id,
b639e094f0ac9feb008c0d13deb26c55bbb50793
git_gutter_change.py
git_gutter_change.py
import sublime import sublime_plugin try: from GitGutter.view_collection import ViewCollection except ImportError: from view_collection import ViewCollection class GitGutterBaseChangeCommand(sublime_plugin.WindowCommand): def lines_to_blocks(self, lines): blocks = [] last_line = -2 for line in lines: if line > last_line+1: blocks.append(line) last_line = line return blocks def run(self): view = self.window.active_view() inserted, modified, deleted = ViewCollection.diff(view) inserted = self.lines_to_blocks(inserted) modified = self.lines_to_blocks(modified) all_changes = sorted(inserted + modified + deleted) row, col = view.rowcol(view.sel()[0].begin()) current_row = row + 1 line = self.jump(all_changes, current_row) self.window.active_view().run_command("goto_line", {"line": line}) class GitGutterNextChangeCommand(GitGutterBaseChangeCommand): def jump(self, all_changes, current_row): return next((change for change in all_changes if change > current_row), current_row) class GitGutterPrevChangeCommand(GitGutterBaseChangeCommand): def jump(self, all_changes, current_row): return next((change for change in reversed(all_changes) if change < current_row), current_row)
import sublime import sublime_plugin try: from GitGutter.view_collection import ViewCollection except ImportError: from view_collection import ViewCollection class GitGutterBaseChangeCommand(sublime_plugin.WindowCommand): def lines_to_blocks(self, lines): blocks = [] last_line = -2 for line in lines: if line > last_line+1: blocks.append(line) last_line = line return blocks def run(self): view = self.window.active_view() inserted, modified, deleted = ViewCollection.diff(view) inserted = self.lines_to_blocks(inserted) modified = self.lines_to_blocks(modified) all_changes = sorted(inserted + modified + deleted) row, col = view.rowcol(view.sel()[0].begin()) current_row = row + 1 line = self.jump(all_changes, current_row) self.window.active_view().run_command("goto_line", {"line": line}) class GitGutterNextChangeCommand(GitGutterBaseChangeCommand): def jump(self, all_changes, current_row): return next((change for change in all_changes if change > current_row), all_changes[0]) class GitGutterPrevChangeCommand(GitGutterBaseChangeCommand): def jump(self, all_changes, current_row): return next((change for change in reversed(all_changes) if change < current_row), all_changes[-1])
Make jumping between changes loop back around
Make jumping between changes loop back around
Python
mit
michaelhogg/GitGutter,biodamasceno/GitGutter,biodamasceno/GitGutter,robfrawley/sublime-git-gutter,robfrawley/sublime-git-gutter,robfrawley/sublime-git-gutter,robfrawley/sublime-git-gutter,biodamasceno/GitGutter,natecavanaugh/GitGutter,tushortz/GitGutter,michaelhogg/GitGutter,akpersad/GitGutter,akpersad/GitGutter,natecavanaugh/GitGutter,akpersad/GitGutter,tushortz/GitGutter,akpersad/GitGutter,michaelhogg/GitGutter,tushortz/GitGutter,jisaacks/GitGutter,biodamasceno/GitGutter,natecavanaugh/GitGutter,michaelhogg/GitGutter,tushortz/GitGutter,natecavanaugh/GitGutter
--- +++ @@ -34,10 +34,10 @@ class GitGutterNextChangeCommand(GitGutterBaseChangeCommand): def jump(self, all_changes, current_row): return next((change for change in all_changes - if change > current_row), current_row) + if change > current_row), all_changes[0]) class GitGutterPrevChangeCommand(GitGutterBaseChangeCommand): def jump(self, all_changes, current_row): return next((change for change in reversed(all_changes) - if change < current_row), current_row) + if change < current_row), all_changes[-1])
6a7fb1ff05202f60c7036db369926e3056372123
tests/chainer_tests/functions_tests/math_tests/test_sqrt.py
tests/chainer_tests/functions_tests/math_tests/test_sqrt.py
import unittest import numpy import chainer.functions as F from chainer import testing def make_data(dtype, shape): x = numpy.random.uniform(0.1, 5, shape).astype(dtype) gy = numpy.random.uniform(-1, 1, shape).astype(dtype) return x, gy # # sqrt @testing.math_function_test(F.Sqrt(), make_data=make_data) class TestSqrt(unittest.TestCase): pass # # rsqrt def rsqrt(x, dtype=numpy.float32): return numpy.reciprocal(numpy.sqrt(x, dtype=dtype)) # TODO(takagi) Fix test of rsqrt not to use this decorator. @testing.math_function_test(F.rsqrt, func_expected=rsqrt, make_data=make_data) class TestRsqrt(unittest.TestCase): pass testing.run_module(__name__, __file__)
import unittest import numpy import chainer.functions as F from chainer import testing # # sqrt def make_data(dtype, shape): x = numpy.random.uniform(0.1, 5, shape).astype(dtype) gy = numpy.random.uniform(-1, 1, shape).astype(dtype) return x, gy @testing.math_function_test(F.Sqrt(), make_data=make_data) class TestSqrt(unittest.TestCase): pass # # rsqrt def rsqrt(x): return numpy.reciprocal(numpy.sqrt(x)) class TestRsqrt(unittest.TestCase): def test_rsqrt(self): x = numpy.random.uniform(0.1, 5, (3, 2)).astype(numpy.float32) testing.assert_allclose(F.rsqrt(x).data, rsqrt(x)) testing.run_module(__name__, __file__)
Simplify test of rsqrt function.
Simplify test of rsqrt function.
Python
mit
chainer/chainer,niboshi/chainer,hvy/chainer,hvy/chainer,anaruse/chainer,ktnyt/chainer,jnishi/chainer,pfnet/chainer,keisuke-umezawa/chainer,cupy/cupy,ysekky/chainer,kashif/chainer,keisuke-umezawa/chainer,ronekko/chainer,niboshi/chainer,wkentaro/chainer,cupy/cupy,kiyukuta/chainer,okuta/chainer,delta2323/chainer,hvy/chainer,ktnyt/chainer,keisuke-umezawa/chainer,niboshi/chainer,hvy/chainer,ktnyt/chainer,aonotas/chainer,rezoo/chainer,okuta/chainer,jnishi/chainer,cupy/cupy,ktnyt/chainer,keisuke-umezawa/chainer,wkentaro/chainer,okuta/chainer,wkentaro/chainer,niboshi/chainer,tkerola/chainer,chainer/chainer,okuta/chainer,jnishi/chainer,jnishi/chainer,wkentaro/chainer,chainer/chainer,cupy/cupy,chainer/chainer
--- +++ @@ -6,14 +6,14 @@ from chainer import testing +# +# sqrt + def make_data(dtype, shape): x = numpy.random.uniform(0.1, 5, shape).astype(dtype) gy = numpy.random.uniform(-1, 1, shape).astype(dtype) return x, gy - -# -# sqrt @testing.math_function_test(F.Sqrt(), make_data=make_data) class TestSqrt(unittest.TestCase): @@ -23,14 +23,15 @@ # # rsqrt -def rsqrt(x, dtype=numpy.float32): - return numpy.reciprocal(numpy.sqrt(x, dtype=dtype)) +def rsqrt(x): + return numpy.reciprocal(numpy.sqrt(x)) -# TODO(takagi) Fix test of rsqrt not to use this decorator. -@testing.math_function_test(F.rsqrt, func_expected=rsqrt, make_data=make_data) class TestRsqrt(unittest.TestCase): - pass + + def test_rsqrt(self): + x = numpy.random.uniform(0.1, 5, (3, 2)).astype(numpy.float32) + testing.assert_allclose(F.rsqrt(x).data, rsqrt(x)) testing.run_module(__name__, __file__)
63bf9c267ff891f1a2bd1f472a5d77f8df1e0209
tests/iam/test_iam_valid_json.py
tests/iam/test_iam_valid_json.py
"""Test IAM Policy templates are valid JSON.""" import jinja2 from foremast.iam.construct_policy import render_policy_template from foremast.utils.templates import LOCAL_TEMPLATES def iam_templates(): """Generate list of IAM templates.""" jinjaenv = jinja2.Environment(loader=jinja2.FileSystemLoader([LOCAL_TEMPLATES])) iam_template_names = jinjaenv.list_templates(filter_func=lambda x: all([ x.startswith('infrastructure/iam/'), 'trust' not in x, 'wrapper' not in x, ])) for iam_template_name in iam_template_names: yield iam_template_name items = ['resource1', 'resource2'] if service == 'rds-db': items = { 'resource1': 'user1', 'resource2': 'user2', } rendered = render_policy_template( account_number='', app='coreforrest', env='dev', group='forrest', items=items, pipeline_settings={ 'lambda': { 'vpc_enabled': False, }, }, region='us-east-1', service=service) assert isinstance(rendered, list)
"""Test IAM Policy templates are valid JSON.""" import json import jinja2 import pytest from foremast.iam.construct_policy import render_policy_template from foremast.utils.templates import LOCAL_TEMPLATES def iam_templates(): """Generate list of IAM templates.""" jinjaenv = jinja2.Environment(loader=jinja2.FileSystemLoader([LOCAL_TEMPLATES])) iam_template_names = jinjaenv.list_templates(filter_func=lambda x: all([ x.startswith('infrastructure/iam/'), 'trust' not in x, 'wrapper' not in x, ])) for iam_template_name in iam_template_names: yield iam_template_name @pytest.mark.parametrize(argnames='template_name', argvalues=iam_templates()) def test_all_iam_templates(template_name): """Verify all IAM templates render as proper JSON.""" *_, service_json = template_name.split('/') service, *_ = service_json.split('.') items = ['resource1', 'resource2'] if service == 'rds-db': items = { 'resource1': 'user1', 'resource2': 'user2', } try: rendered = render_policy_template( account_number='', app='coreforrest', env='dev', group='forrest', items=items, pipeline_settings={ 'lambda': { 'vpc_enabled': False, }, }, region='us-east-1', service=service) except json.decoder.JSONDecodeError: pytest.fail('Bad template: {0}'.format(template_name), pytrace=False) assert isinstance(rendered, list)
Split IAM template tests with paramtrize
test: Split IAM template tests with paramtrize See also: #208
Python
apache-2.0
gogoair/foremast,gogoair/foremast
--- +++ @@ -1,5 +1,8 @@ """Test IAM Policy templates are valid JSON.""" +import json + import jinja2 +import pytest from foremast.iam.construct_policy import render_policy_template from foremast.utils.templates import LOCAL_TEMPLATES @@ -18,15 +21,21 @@ yield iam_template_name +@pytest.mark.parametrize(argnames='template_name', argvalues=iam_templates()) +def test_all_iam_templates(template_name): + """Verify all IAM templates render as proper JSON.""" + *_, service_json = template_name.split('/') + service, *_ = service_json.split('.') - items = ['resource1', 'resource2'] + items = ['resource1', 'resource2'] - if service == 'rds-db': - items = { - 'resource1': 'user1', - 'resource2': 'user2', - } + if service == 'rds-db': + items = { + 'resource1': 'user1', + 'resource2': 'user2', + } + try: rendered = render_policy_template( account_number='', app='coreforrest', @@ -40,5 +49,7 @@ }, region='us-east-1', service=service) + except json.decoder.JSONDecodeError: + pytest.fail('Bad template: {0}'.format(template_name), pytrace=False) - assert isinstance(rendered, list) + assert isinstance(rendered, list)
79158c269669fcbe506ae83e803ef58ba1b40913
examples/olfaction/data/gen_olf_input.py
examples/olfaction/data/gen_olf_input.py
#!/usr/bin/env python """ Generate sample olfactory model stimulus. """ import numpy as np import h5py osn_num = 1375 dt = 1e-4 # time step Ot = 2000 # number of data point during reset period Rt = 1000 # number of data point during odor delivery period Nt = 4*Ot + 3*Rt # number of data points in time t = np.arange(0, dt*Nt, dt) I = -1.*0.0195 # amplitude of odorant concentration u_on = I*np.ones(Ot, dtype=np.float64) u_off = np.zeros(Ot, dtype=np.float64) u_reset = np.zeros(Rt, dtype=np.float64) u = np.concatenate((u_off, u_reset, u_on, u_reset, u_off, u_reset, u_on)) u_all = np.transpose(np.kron(np.ones((osn_num, 1)), u)) with h5py.File('olfactory_input.h5', 'w') as f: f.create_dataset('real', (Nt, osn_num), dtype=np.float64, data=u_all)
#!/usr/bin/env python """ Generate sample olfactory model stimulus. """ import numpy as np import h5py osn_num = 1375 dt = 1e-4 # time step Ot = 2000 # number of data point during reset period Rt = 1000 # number of data point during odor delivery period Nt = 4*Ot + 3*Rt # number of data points in time t = np.arange(0, dt*Nt, dt) I = 10.0 # amplitude of odorant concentration u_on = I*np.ones(Ot, dtype=np.float64) u_off = np.zeros(Ot, dtype=np.float64) u_reset = np.zeros(Rt, dtype=np.float64) u = np.concatenate((u_off, u_reset, u_on, u_reset, u_off, u_reset, u_on)) u_all = np.transpose(np.kron(np.ones((osn_num, 1)), u)) with h5py.File('olfactory_input.h5', 'w') as f: f.create_dataset('real', (Nt, osn_num), dtype=np.float64, data=u_all)
Tweak olfactory input stimulus to produce more interesting output.
Tweak olfactory input stimulus to produce more interesting output.
Python
bsd-3-clause
cerrno/neurokernel
--- +++ @@ -15,7 +15,7 @@ Nt = 4*Ot + 3*Rt # number of data points in time t = np.arange(0, dt*Nt, dt) -I = -1.*0.0195 # amplitude of odorant concentration +I = 10.0 # amplitude of odorant concentration u_on = I*np.ones(Ot, dtype=np.float64) u_off = np.zeros(Ot, dtype=np.float64) u_reset = np.zeros(Rt, dtype=np.float64)
0ff797d60c2ddc93579e7c486e8ebb77593014d8
apiclient/__init__.py
apiclient/__init__.py
"""Retain apiclient as an alias for googleapiclient.""" import googleapiclient from googleapiclient import channel from googleapiclient import discovery from googleapiclient import errors from googleapiclient import http from googleapiclient import mimeparse from googleapiclient import model from googleapiclient import sample_tools from googleapiclient import schema __version__ = googleapiclient.__version__
"""Retain apiclient as an alias for googleapiclient.""" import googleapiclient try: import oauth2client except ImportError: raise RuntimeError( 'Previous version of google-api-python-client detected; due to a ' 'packaging issue, we cannot perform an in-place upgrade. To repair, ' 'remove and reinstall this package, along with oauth2client and ' 'uritemplate. One can do this with pip via\n' ' pip install -I google-api-python-client' ) from googleapiclient import channel from googleapiclient import discovery from googleapiclient import errors from googleapiclient import http from googleapiclient import mimeparse from googleapiclient import model from googleapiclient import sample_tools from googleapiclient import schema __version__ = googleapiclient.__version__
Add another check for a failed googleapiclient upgrade.
Add another check for a failed googleapiclient upgrade. This adds one more check for a failed 1.2 -> 1.3 upgrade, specifically in the `apiclient` import (which was the only import available in 1.2). Even combined with the check in setup.py, this won't catch everything, but it now covers all the most common cases.
Python
apache-2.0
googleapis/google-api-python-client,googleapis/google-api-python-client
--- +++ @@ -1,6 +1,17 @@ """Retain apiclient as an alias for googleapiclient.""" import googleapiclient + +try: + import oauth2client +except ImportError: + raise RuntimeError( + 'Previous version of google-api-python-client detected; due to a ' + 'packaging issue, we cannot perform an in-place upgrade. To repair, ' + 'remove and reinstall this package, along with oauth2client and ' + 'uritemplate. One can do this with pip via\n' + ' pip install -I google-api-python-client' + ) from googleapiclient import channel from googleapiclient import discovery
2995f15c1bcb1bc85d83c7407be199b27882a215
examples/translations/japanese_test_1.py
examples/translations/japanese_test_1.py
# Japanese Language Test - Python 3 Only! from seleniumbase.translate.japanese import セレンテストケース # noqa class テストクラス(セレンテストケース): # noqa def test_例1(self): self.URLを開く("https://ja.wikipedia.org/wiki/") self.テキストを確認する("ウィキペディア") self.要素を確認する('[title="メインページに移動する"]') self.テキストを更新("#searchInput", "アニメ") self.クリックして("#searchButton") self.テキストを確認する("アニメ", "#firstHeading") self.テキストを更新("#searchInput", "寿司") self.クリックして("#searchButton") self.テキストを確認する("寿司", "#firstHeading") self.要素を確認する('img[alt="握り寿司"]')
# Japanese Language Test - Python 3 Only! from seleniumbase.translate.japanese import セレニウムテストケース # noqa class テストクラス(セレニウムテストケース): # noqa def test_例1(self): self.URLを開く("https://ja.wikipedia.org/wiki/") self.テキストを確認する("ウィキペディア") self.要素を確認する('[title="メインページに移動する"]') self.テキストを更新("#searchInput", "アニメ") self.クリックして("#searchButton") self.テキストを確認する("アニメ", "#firstHeading") self.テキストを更新("#searchInput", "寿司") self.クリックして("#searchButton") self.テキストを確認する("寿司", "#firstHeading") self.要素を確認する('img[alt="握り寿司"]')
Update for fixing odd Japanese
Update for fixing odd Japanese Selenium is "セレニウム" in Japanese. (Most people don't write Selenium in Japanese, by the way)
Python
mit
mdmintz/SeleniumBase,seleniumbase/SeleniumBase,seleniumbase/SeleniumBase,mdmintz/SeleniumBase,mdmintz/SeleniumBase,seleniumbase/SeleniumBase,seleniumbase/SeleniumBase,mdmintz/SeleniumBase
--- +++ @@ -1,8 +1,8 @@ # Japanese Language Test - Python 3 Only! -from seleniumbase.translate.japanese import セレンテストケース # noqa +from seleniumbase.translate.japanese import セレニウムテストケース # noqa -class テストクラス(セレンテストケース): # noqa +class テストクラス(セレニウムテストケース): # noqa def test_例1(self): self.URLを開く("https://ja.wikipedia.org/wiki/")
decb9212a5e0adae31d8e7562fa8258c222aae23
dbmigrator/__init__.py
dbmigrator/__init__.py
# -*- coding: utf-8 -*- import logging import sys logger = logging.getLogger('dbmigrator') logger.setLevel(logging.INFO) handler = logging.StreamHandler(sys.stdout) handler.setFormatter(logging.Formatter('[%(levelname)s] %(name)s (%(filename)s) - %(message)s')) logger.addHandler(handler)
Add a logger for dbmigrator that writes to stdout
Add a logger for dbmigrator that writes to stdout For example in a migration file 20160128111115_mimetype_removal_from_module_files.py: ``` from dbmigrator import logger logger.info('message from migration') ``` You will see this when you run the migration: ``` [INFO] dbmigrator (20160128111115_mimetype_removal_from_module_files.py) - message from migration ``` Close #3
Python
agpl-3.0
karenc/db-migrator
--- +++ @@ -0,0 +1,11 @@ +# -*- coding: utf-8 -*- + +import logging +import sys + +logger = logging.getLogger('dbmigrator') +logger.setLevel(logging.INFO) + +handler = logging.StreamHandler(sys.stdout) +handler.setFormatter(logging.Formatter('[%(levelname)s] %(name)s (%(filename)s) - %(message)s')) +logger.addHandler(handler)
e15fb53c0fd63942cafd3a6f11418447df6b6800
siphon/cdmr/tests/test_coveragedataset.py
siphon/cdmr/tests/test_coveragedataset.py
# Copyright (c) 2016 Unidata. # Distributed under the terms of the MIT License. # SPDX-License-Identifier: MIT import warnings from siphon.testing import get_recorder from siphon.cdmr.coveragedataset import CoverageDataset recorder = get_recorder(__file__) # Ignore warnings about CoverageDataset warnings.simplefilter('ignore') @recorder.use_cassette('hrrr_cdmremotefeature') def test_simple_cdmremotefeature(): 'Just a smoke test for CDMRemoteFeature' cd = CoverageDataset('http://localhost:8080/thredds/cdmrfeature/grid/' 'test/HRRR_CONUS_2p5km_20160309_1600.grib2') assert cd.grids
# Copyright (c) 2016 Unidata. # Distributed under the terms of the MIT License. # SPDX-License-Identifier: MIT import warnings from siphon.testing import get_recorder from siphon.cdmr.coveragedataset import CoverageDataset recorder = get_recorder(__file__) # Ignore warnings about CoverageDataset warnings.simplefilter('ignore') @recorder.use_cassette('hrrr_cdmremotefeature') def test_simple_cdmremotefeature(): 'Just a smoke test for CDMRemoteFeature' cd = CoverageDataset('http://localhost:8080/thredds/cdmrfeature/grid/' 'test/HRRR_CONUS_2p5km_20160309_1600.grib2') assert cd.grids @recorder.use_cassette('hrrr_cdmremotefeature') def test_simple_cdmremotefeature_str(): 'Just a smoke test for converting CoverageDataset to str' cd = CoverageDataset('http://localhost:8080/thredds/cdmrfeature/grid/' 'test/HRRR_CONUS_2p5km_20160309_1600.grib2') assert str(cd)
Add smoketest for convering CoverageDataset to str.
Add smoketest for convering CoverageDataset to str.
Python
bsd-3-clause
dopplershift/siphon,dopplershift/siphon,Unidata/siphon
--- +++ @@ -18,3 +18,11 @@ cd = CoverageDataset('http://localhost:8080/thredds/cdmrfeature/grid/' 'test/HRRR_CONUS_2p5km_20160309_1600.grib2') assert cd.grids + + +@recorder.use_cassette('hrrr_cdmremotefeature') +def test_simple_cdmremotefeature_str(): + 'Just a smoke test for converting CoverageDataset to str' + cd = CoverageDataset('http://localhost:8080/thredds/cdmrfeature/grid/' + 'test/HRRR_CONUS_2p5km_20160309_1600.grib2') + assert str(cd)
95add18b382898eb82c7ff3dd0aa0fd6db0f5cb9
setup.py
setup.py
""" Flask-MongoKit -------------- Flask-MongoKit simplifies to use MongoKit, a powerful MongoDB ORM in Flask applications. Links ````` * `documentation <http://packages.python.org/Flask-MongoKit>`_ * `development version <http://github.com/jarus/flask-mongokit/zipball/master#egg=Flask-MongoKit-dev>`_ * `MongoKit <http://namlook.github.com/mongokit/>`_ * `Flask <http://flask.pocoo.org>`_ """ from setuptools import setup setup( name='Flask-MongoKit', version='0.6', url='http://github.com/jarus/flask-mongokit', license='BSD', author='Christoph Heer', author_email='Christoph.Heer@googlemail.com', description='A Flask extension simplifies to use MongoKit', long_description=__doc__, py_modules=['flask_mongokit'], zip_safe=False, platforms='any', install_requires=[ 'Flask', 'MongoKit' ], test_suite='tests.suite', classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Internet :: WWW/HTTP :: Dynamic Content', 'Topic :: Software Development :: Libraries :: Python Modules' ] )
""" Flask-MongoKit -------------- Flask-MongoKit simplifies to use MongoKit, a powerful MongoDB ORM in Flask applications. Links ````` * `documentation <http://packages.python.org/Flask-MongoKit>`_ * `development version <http://github.com/jarus/flask-mongokit/zipball/master#egg=Flask-MongoKit-dev>`_ * `MongoKit <http://namlook.github.com/mongokit/>`_ * `Flask <http://flask.pocoo.org>`_ """ import sys from setuptools import setup install_requires = [ "Flask", "MongoKit" ] if sys.version_info < (2, 6): install_requires.append('simplejson') setup( name='Flask-MongoKit', version='0.6', url='http://github.com/jarus/flask-mongokit', license='BSD', author='Christoph Heer', author_email='Christoph.Heer@googlemail.com', description='A Flask extension simplifies to use MongoKit', long_description=__doc__, py_modules=['flask_mongokit'], zip_safe=False, platforms='any', install_requires=install_requires, test_suite='tests.suite', classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Internet :: WWW/HTTP :: Dynamic Content', 'Topic :: Software Development :: Libraries :: Python Modules' ] )
Add simplejson as requirement for python 2.5
Add simplejson as requirement for python 2.5
Python
bsd-3-clause
jarus/flask-mongokit,VishvajitP/flask-mongokit,jarus/flask-mongokit,VishvajitP/flask-mongokit
--- +++ @@ -2,7 +2,7 @@ Flask-MongoKit -------------- -Flask-MongoKit simplifies to use MongoKit, a powerful MongoDB ORM in Flask +Flask-MongoKit simplifies to use MongoKit, a powerful MongoDB ORM in Flask applications. Links @@ -14,8 +14,16 @@ * `Flask <http://flask.pocoo.org>`_ """ +import sys from setuptools import setup +install_requires = [ + "Flask", + "MongoKit" +] + +if sys.version_info < (2, 6): + install_requires.append('simplejson') setup( name='Flask-MongoKit', @@ -29,10 +37,7 @@ py_modules=['flask_mongokit'], zip_safe=False, platforms='any', - install_requires=[ - 'Flask', - 'MongoKit' - ], + install_requires=install_requires, test_suite='tests.suite', classifiers=[ 'Development Status :: 4 - Beta',
c575d69ce253f9eb4d9beb6ffcd3e8a57ed804f0
setup.py
setup.py
from setuptools import setup, find_packages setup(name='diaspy', version='0.1.0', author='Moritz Kiefer', author_email='moritz.kiefer@gmail.com', url='https://github.com/Javafant/diaspora-api', description='A python api to the social network diaspora', packages=find_packages(), install_requires=['requests'] )
from setuptools import setup, find_packages setup(name='diaspy', version='0.2.0', author='Moritz Kiefer', author_email='moritz.kiefer@gmail.com', url='https://github.com/Javafant/diaspora-api', description='A python api to the social network diaspora', packages=find_packages(), install_requires=['requests'] )
Update to version 0.2.0 (according with semantic versioning)
Update to version 0.2.0 (according with semantic versioning)
Python
mit
marekjm/diaspy
--- +++ @@ -1,6 +1,6 @@ from setuptools import setup, find_packages setup(name='diaspy', - version='0.1.0', + version='0.2.0', author='Moritz Kiefer', author_email='moritz.kiefer@gmail.com', url='https://github.com/Javafant/diaspora-api',
535ac4c6eae416461e11f33c1a1ef67e92c73914
tests/test_exception_wrapping.py
tests/test_exception_wrapping.py
import safe def test_simple_exception(): class MockReponse(object): def json(self): return {'status': False, 'method': 'synchronize', 'module': 'cluster', 'error': {'message': 'Example error'}} exception = safe.library.raise_from_json(MockReponse()) assert str(exception) == 'Example error'
import safe class MockResponse(object): def __init__(self, data): self.data = data def json(self): return self.data def test_basic_exception(): error_message = 'Example error' response = MockResponse({ 'status': False, 'method': 'synchronize', 'module': 'cluster', 'error': {'message': error_message} }) exception = safe.library.raise_from_json(response) assert str(exception) == error_message def test_commit_failed_exception(): error_message = 'Default ipv4 gateway is not on eth0 subnet' response = MockResponse({ 'status': False, 'type': 'configuration', 'method': 'smartapply', 'module': 'nsc', 'error': { 'message': 'Apply configuration failed.', 'reason': [{ 'url': '/SAFe/sng_network_config/modify/network', 'obj_type': 'configuration', 'type': 'ERROR', 'description': error_message, 'module': 'network' }] } }) exception = safe.library.raise_from_json(response) assert isinstance(exception, safe.CommitFailed) assert str(exception) == 'Apply changes failed: ' + error_message assert len(exception.reasons) == 1 reason = exception.reasons[0] assert reason.obj == 'configuration' assert reason.module == 'network' assert reason.description == error_message
Add a commit failed test
Add a commit failed test
Python
mpl-2.0
sangoma/safepy2,leonardolang/safepy2
--- +++ @@ -1,13 +1,52 @@ import safe -def test_simple_exception(): - class MockReponse(object): - def json(self): - return {'status': False, - 'method': 'synchronize', - 'module': 'cluster', - 'error': {'message': 'Example error'}} +class MockResponse(object): + def __init__(self, data): + self.data = data - exception = safe.library.raise_from_json(MockReponse()) - assert str(exception) == 'Example error' + def json(self): + return self.data + + +def test_basic_exception(): + error_message = 'Example error' + response = MockResponse({ + 'status': False, + 'method': 'synchronize', + 'module': 'cluster', + 'error': {'message': error_message} + }) + + exception = safe.library.raise_from_json(response) + assert str(exception) == error_message + + +def test_commit_failed_exception(): + error_message = 'Default ipv4 gateway is not on eth0 subnet' + response = MockResponse({ + 'status': False, + 'type': 'configuration', + 'method': 'smartapply', + 'module': 'nsc', + 'error': { + 'message': 'Apply configuration failed.', + 'reason': [{ + 'url': '/SAFe/sng_network_config/modify/network', + 'obj_type': 'configuration', + 'type': 'ERROR', + 'description': error_message, + 'module': 'network' + }] + } + }) + + exception = safe.library.raise_from_json(response) + assert isinstance(exception, safe.CommitFailed) + assert str(exception) == 'Apply changes failed: ' + error_message + assert len(exception.reasons) == 1 + + reason = exception.reasons[0] + assert reason.obj == 'configuration' + assert reason.module == 'network' + assert reason.description == error_message
73d69274a21818830b3a0b87ad574321c958c0f7
setup.py
setup.py
from setuptools import setup setup( name="pytest-cpp", version='0.4', packages=['pytest_cpp'], entry_points={ 'pytest11': ['cpp = pytest_cpp.plugin'], }, install_requires=['pytest', 'colorama'], # metadata for upload to PyPI author="Bruno Oliveira", author_email="nicoddemus@gmail.com", description="Use pytest's runner to discover and execute C++ tests", long_description=open('README.rst').read(), license="MIT", keywords="pytest test unittest", url="http://github.com/pytest-dev/pytest-cpp", classifiers=[ 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: C++', 'Topic :: Software Development :: Quality Assurance', 'Topic :: Software Development :: Testing', ], )
from setuptools import setup setup( name="pytest-cpp", version='0.4', packages=['pytest_cpp'], entry_points={ 'pytest11': ['cpp = pytest_cpp.plugin'], }, install_requires=['pytest', 'colorama'], # metadata for upload to PyPI author="Bruno Oliveira", author_email="nicoddemus@gmail.com", description="Use pytest's runner to discover and execute C++ tests", long_description=open('README.rst').read(), license="MIT", keywords="pytest test unittest", url="http://github.com/pytest-dev/pytest-cpp", classifiers=[ 'Development Status :: 4 - Beta', 'Framework :: Pytest', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Programming Language :: C++', 'Topic :: Software Development :: Quality Assurance', 'Topic :: Software Development :: Testing', ], )
Add Framework::Pytest to list of classifiers
Add Framework::Pytest to list of classifiers
Python
mit
pytest-dev/pytest-cpp,pytest-dev/pytest-cpp,pytest-dev/pytest-cpp
--- +++ @@ -19,7 +19,8 @@ keywords="pytest test unittest", url="http://github.com/pytest-dev/pytest-cpp", classifiers=[ - 'Development Status :: 3 - Alpha', + 'Development Status :: 4 - Beta', + 'Framework :: Pytest', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent',
6e57b110750e3e871156a7716e95ffed3adf2cd1
setup.py
setup.py
import os, io from setuptools import setup, find_packages long_description = ( io.open('README.rst', encoding='utf-8').read() + '\n' + io.open('CHANGES.txt', encoding='utf-8').read()) setup(name='more.chameleon', version='0.3.dev0', description="Chameleon template integration for Morepath", long_description=long_description, author="Martijn Faassen", author_email="faassen@startifact.com", keywords='morepath chameleon', license="BSD", url="http://pypi.python.org/pypi/more.chameleon", namespace_packages=['more'], packages=find_packages(), include_package_data=True, zip_safe=False, install_requires=[ 'setuptools', 'morepath >= 0.10', 'chameleon >= 2.20' ], extras_require = dict( test=['pytest >= 2.6.0', 'pytest-cov', 'WebTest'], ), )
import io from setuptools import setup, find_packages long_description = '\n'.join(( io.open('README.rst', encoding='utf-8').read(), io.open('CHANGES.txt', encoding='utf-8').read() )) setup(name='more.chameleon', version='0.3.dev0', description="Chameleon template integration for Morepath", long_description=long_description, author="Martijn Faassen", author_email="faassen@startifact.com", keywords='morepath chameleon', license="BSD", url="http://pypi.python.org/pypi/more.chameleon", namespace_packages=['more'], packages=find_packages(), include_package_data=True, zip_safe=False, install_requires=[ 'setuptools', 'morepath >= 0.10', 'chameleon >= 2.20' ], extras_require=dict( test=['pytest >= 2.6.0', 'pytest-cov', 'WebTest'], ), )
Use io.open with encoding='utf-8' and flake8 compliance
Use io.open with encoding='utf-8' and flake8 compliance
Python
bsd-3-clause
morepath/more.chameleon
--- +++ @@ -1,10 +1,10 @@ -import os, io +import io from setuptools import setup, find_packages -long_description = ( - io.open('README.rst', encoding='utf-8').read() - + '\n' + - io.open('CHANGES.txt', encoding='utf-8').read()) +long_description = '\n'.join(( + io.open('README.rst', encoding='utf-8').read(), + io.open('CHANGES.txt', encoding='utf-8').read() +)) setup(name='more.chameleon', version='0.3.dev0', @@ -24,7 +24,7 @@ 'morepath >= 0.10', 'chameleon >= 2.20' ], - extras_require = dict( + extras_require=dict( test=['pytest >= 2.6.0', 'pytest-cov', 'WebTest'],
d5d359c5ec0f1735e97355839f1a12c6ea45c460
polygamy/pygit2_git.py
polygamy/pygit2_git.py
from __future__ import absolute_import import pygit2 from .base_git import NoSuchRemote from .plain_git import PlainGit class Pygit2Git(PlainGit): @staticmethod def is_on_branch(path): repo = pygit2.Repository(path) return not (repo.head_is_detached or repo.head_is_unborn) @staticmethod def get_remote_url(path, remote_name): repo = pygit2.Repository(path) for remote in repo.remotes: if remote.name == remote_name: break else: raise NoSuchRemote() return remote.url
from __future__ import absolute_import import pygit2 from .base_git import NoSuchRemote from .plain_git import PlainGit class Pygit2Git(PlainGit): @staticmethod def is_on_branch(path): repo = pygit2.Repository(path) return not (repo.head_is_detached or repo.head_is_unborn) @staticmethod def get_remote_url(path, remote_name): repo = pygit2.Repository(path) for remote in repo.remotes: if remote.name == remote_name: break else: raise NoSuchRemote() return remote.url @staticmethod def add_remote(path, remote_name, remote_url): repo = pygit2.Repository(path) repo.create_remote(remote_name, remote_url)
Add add_remote to pygit2 implementation
Add add_remote to pygit2 implementation
Python
bsd-3-clause
solarnz/polygamy,solarnz/polygamy
--- +++ @@ -24,3 +24,8 @@ raise NoSuchRemote() return remote.url + + @staticmethod + def add_remote(path, remote_name, remote_url): + repo = pygit2.Repository(path) + repo.create_remote(remote_name, remote_url)
5fc65183e40dd1d06bd6ae3e4e7ba0f0a0e2bdd6
alg_check_dag.py
alg_check_dag.py
from __future__ import absolute_import from __future__ import print_function from __future__ import division def _previsit(): pass def _postvisit(): pass def _dfs_explore(): pass def check_dag(): """Check Directed Acyclic Graph (DAG).""" pass def main(): # DAG. dag_adj_d = { 'A': ['D'], 'B': ['D'], 'C': ['D'], 'D': ['E', 'G'], 'E': ['J'], 'F': ['G'], 'G': ['I'], 'I': ['J'], 'J': [] } if __name__ == '__main__': main()
from __future__ import absolute_import from __future__ import print_function from __future__ import division def _previsit(): pass def _postvisit(): pass def _dfs_explore(): pass def check_dag(): """Check Directed Acyclic Graph (DAG).""" pass def main(): # Graph adjacency dictionary for DAG. dag_adj_d = { 'A': ['D'], 'B': ['D'], 'C': ['D'], 'D': ['E', 'G'], 'E': ['J'], 'F': ['G'], 'G': ['I'], 'I': ['J'], 'J': [] } # Graph adjacency dictionary for non-DAG. nondag_adj_d = { 'A': ['B'], 'B': ['C', 'E'], 'C': ['C', 'F'], 'D': ['B', 'G'], 'E': ['A', 'D'], 'F': ['H'], 'G': ['E'], 'H': ['I'], 'I': ['F'] } if __name__ == '__main__': main()
Add DAG & non-DAG adjacency dicts
Add DAG & non-DAG adjacency dicts
Python
bsd-2-clause
bowen0701/algorithms_data_structures
--- +++ @@ -18,7 +18,7 @@ def main(): - # DAG. + # Graph adjacency dictionary for DAG. dag_adj_d = { 'A': ['D'], 'B': ['D'], @@ -31,5 +31,18 @@ 'J': [] } + # Graph adjacency dictionary for non-DAG. + nondag_adj_d = { + 'A': ['B'], + 'B': ['C', 'E'], + 'C': ['C', 'F'], + 'D': ['B', 'G'], + 'E': ['A', 'D'], + 'F': ['H'], + 'G': ['E'], + 'H': ['I'], + 'I': ['F'] + } + if __name__ == '__main__': main()
4b665bb2e85994e3df0324afacb2453b8f4998a1
contact_map/tests/test_dask_runner.py
contact_map/tests/test_dask_runner.py
# pylint: disable=wildcard-import, missing-docstring, protected-access # pylint: disable=attribute-defined-outside-init, invalid-name, no-self-use # pylint: disable=wrong-import-order, unused-wildcard-import from .utils import * from contact_map.dask_runner import * class TestDaskContactFrequency(object): def test_dask_integration(self): # this is an integration test to check that dask works dask = pytest.importorskip('dask') # pylint: disable=W0612 distributed = pytest.importorskip('dask.distributed') # Explicitly set only 4 workers on Travis instead of 31 # Fix copied from https://github.com/spencerahill/aospy/pull/220/files cluster = distributed.LocalCluster(n_workers=4) client = distributed.Client(cluster) filename = find_testfile("trajectory.pdb") dask_freq = DaskContactFrequency(client, filename, cutoff=0.075, n_neighbors_ignored=0) client.close() assert dask_freq.n_frames == 5
# pylint: disable=wildcard-import, missing-docstring, protected-access # pylint: disable=attribute-defined-outside-init, invalid-name, no-self-use # pylint: disable=wrong-import-order, unused-wildcard-import from .utils import * from contact_map.dask_runner import * def dask_setup_test_cluster(distributed, n_workers=4, n_attempts=3): """Set up a test cluster using dask.distributed. Try up to n_attempts times, and skip the test if all attempts fail. """ cluster = None for _ in range(n_attempts): try: cluster = distributed.LocalCluster(n_workers=n_workers) except distributed.TimeoutError: continue else: return cluster # only get here if all retries fail pytest.skip("Failed to set up distributed LocalCluster") class TestDaskContactFrequency(object): def test_dask_integration(self): # this is an integration test to check that dask works dask = pytest.importorskip('dask') # pylint: disable=W0612 distributed = pytest.importorskip('dask.distributed') # Explicitly set only 4 workers on Travis instead of 31 # Fix copied from https://github.com/spencerahill/aospy/pull/220/files cluster = dask_setup_test_cluster(distributed) client = distributed.Client(cluster) filename = find_testfile("trajectory.pdb") dask_freq = DaskContactFrequency(client, filename, cutoff=0.075, n_neighbors_ignored=0) client.close() assert dask_freq.n_frames == 5
Handle dask TimeoutError exception in tests
Handle dask TimeoutError exception in tests
Python
lgpl-2.1
dwhswenson/contact_map,dwhswenson/contact_map
--- +++ @@ -6,6 +6,22 @@ from .utils import * from contact_map.dask_runner import * +def dask_setup_test_cluster(distributed, n_workers=4, n_attempts=3): + """Set up a test cluster using dask.distributed. Try up to n_attempts + times, and skip the test if all attempts fail. + """ + cluster = None + for _ in range(n_attempts): + try: + cluster = distributed.LocalCluster(n_workers=n_workers) + except distributed.TimeoutError: + continue + else: + return cluster + # only get here if all retries fail + pytest.skip("Failed to set up distributed LocalCluster") + + class TestDaskContactFrequency(object): def test_dask_integration(self): # this is an integration test to check that dask works @@ -13,7 +29,7 @@ distributed = pytest.importorskip('dask.distributed') # Explicitly set only 4 workers on Travis instead of 31 # Fix copied from https://github.com/spencerahill/aospy/pull/220/files - cluster = distributed.LocalCluster(n_workers=4) + cluster = dask_setup_test_cluster(distributed) client = distributed.Client(cluster) filename = find_testfile("trajectory.pdb")
e4dd1da8f2fdfa2f4071ab1796b31147f12d00a0
setup.py
setup.py
from setuptools import setup setup(name='covenant', version='0.1.0', description='Code contracts for Python 3', author='Kamil Kisiel', author_email='kamil@kamilkisiel.net', url='http://pypi.python.org/pypi/covenant', license="BSD License", packages=["covenant"], keywords="contract", platforms=["All"], install_requires=["decorator"], classifiers=['Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Natural Language :: English', 'Operating System :: OS Independent', 'Programming Language :: Python :: 3', 'Topic :: Software Development :: Libraries', 'Topic :: Utilities'], )
from setuptools import setup setup(name='covenant', version='0.1.0', description='Code contracts for Python 3', author='Kamil Kisiel', author_email='kamil@kamilkisiel.net', url='http://pypi.python.org/pypi/covenant', license="BSD License", packages=["covenant"], keywords="contract", platforms=["All"], install_requires=["decorator"], classifiers=['Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Natural Language :: English', 'Operating System :: OS Independent', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.2', 'Topic :: Software Development :: Libraries', 'Topic :: Utilities'], )
Add Python 3.2 trove classifier
Add Python 3.2 trove classifier
Python
mit
kisielk/covenant,kisielk/covenant
--- +++ @@ -17,6 +17,7 @@ 'Natural Language :: English', 'Operating System :: OS Independent', 'Programming Language :: Python :: 3', + 'Programming Language :: Python :: 3.2', 'Topic :: Software Development :: Libraries', 'Topic :: Utilities'], )
44b9649df3418713b8ef5ae8e1f2990a92a48907
setup.py
setup.py
from setuptools import setup setup( name='icapservice', version='0.2.0', description='ICAP service library for Python', author='Giles Brown', author_email='giles_brown@hotmail.com', url='https://github.com/gilesbrown/icapservice', license='MIT', packages=['icapservice'], zip_safe=False, install_requires=['six', 'brotlipy'], include_package_data=True, package_data={'': ['LICENSE']}, classifiers=( 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'Natural Language :: English', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python', 'Programming Language :: Python :: 2.7', #'Programming Language :: Python :: 3', #'Programming Language :: Python :: 3.4', #'Programming Language :: Python :: 3.5', ), )
from setuptools import setup setup( name='icapservice', version='0.2.1', description='ICAP service library for Python', author='Giles Brown', author_email='giles_brown@hotmail.com', url='https://github.com/gilesbrown/icapservice', license='MIT', packages=['icapservice'], zip_safe=False, install_requires=['six', 'brotlipy'], include_package_data=True, package_data={'': ['LICENSE']}, classifiers=( 'Development Status :: 3 - Alpha', 'Intended Audience :: Developers', 'Natural Language :: English', 'License :: OSI Approved :: MIT License', 'Programming Language :: Python', 'Programming Language :: Python :: 2.7', #'Programming Language :: Python :: 3', #'Programming Language :: Python :: 3.4', #'Programming Language :: Python :: 3.5', ), )
Patch 0.2.1 to remove print
Patch 0.2.1 to remove print
Python
mit
gilesbrown/python-icapservice,gilesbrown/python-icapservice
--- +++ @@ -3,7 +3,7 @@ setup( name='icapservice', - version='0.2.0', + version='0.2.1', description='ICAP service library for Python', author='Giles Brown', author_email='giles_brown@hotmail.com',
86103cbdc457c699f3a76eba914a8708c65bbbbc
setup.py
setup.py
from setuptools import setup with open('README.md') as file: # Try my best to have at least the intro in Markdown/reST. long_description = file.read().partition('<!-- END long_description -->')[0] setup(name='caniusepython3', version='1.0', description='Determine what projects are blocking you from porting to Python 3', long_description=long_description, author='Brett Cannon', author_email='brett@python.org', url='https://github.com/brettcannon/caniusepython3', py_modules=['caniusepython3'], setup_requires=['setuptools'], install_requires=['distlib', 'pip'], tests_require=['mock'], classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Console', 'Intended Audience :: Developers', 'License :: OSI Approved :: Apache Software License', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', ], entry_points={ 'console_scripts': [ 'caniusepython3=caniusepython3:main', ] }, zip_safe=True, )
from setuptools import setup with open('README.md') as file: # Try my best to have at least the intro in Markdown/reST. long_description = file.read().partition('<!-- END long_description -->')[0] setup(name='caniusepython3', version='1.0', description='Determine what projects are blocking you from porting to Python 3', long_description=long_description, author='Brett Cannon', author_email='brett@python.org', url='https://github.com/brettcannon/caniusepython3', py_modules=['caniusepython3'], setup_requires=['setuptools'], install_requires=['distlib', 'pip'], tests_require=['mock'], classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Console', 'Intended Audience :: Developers', 'License :: OSI Approved :: Apache Software License', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.2', 'Programming Language :: Python :: 3.3', ], entry_points={ 'console_scripts': [ 'caniusepython3=caniusepython3:main', ] }, zip_safe=True, )
Set classifier for Python 3.2
Set classifier for Python 3.2 For #6
Python
apache-2.0
ctismer/caniusepython3,dhamaniasad/caniusepython3,nett55/caniusepypy,brettcannon/caniusepython3,svisser/caniusepython3,public/caniusepypy
--- +++ @@ -21,6 +21,7 @@ 'Intended Audience :: Developers', 'License :: OSI Approved :: Apache Software License', 'Programming Language :: Python :: 3', + 'Programming Language :: Python :: 3.2', 'Programming Language :: Python :: 3.3', ], entry_points={
b984060f9e3455df56953580dd3ee4e0717f916b
setup.py
setup.py
#!/usr/bin/env python from setuptools import setup setup( name='rinse', version='0.1.2', description='Python3 SOAP client built with lxml and requests.', long_description=open('README.rst').read(), author='Tyson Clugg', author_email='tyson@clugg.net', url='http://github.com/tysonclugg/rinse', license='MIT', packages=['rinse'], test_suite='rinse.tests', install_requires=[ 'defusedxml', 'lxml', 'requests', ], classifiers=[ "Programming Language :: Python :: 3", "Development Status :: 3 - Alpha", "License :: OSI Approved :: MIT License", ], )
#!/usr/bin/env python from setuptools import setup setup( name='rinse', version='0.1.2', description='Python3 SOAP client built with lxml and requests.', long_description=open('README.rst').read(), author='Tyson Clugg', author_email='tyson@clugg.net', url='http://github.com/tysonclugg/rinse', license='MIT', packages=['rinse'], test_suite='rinse.tests', install_requires=[ 'defusedxml', 'lxml', 'requests', ], classifiers=[ "Programming Language :: Python :: 2", "Programming Language :: Python :: 3", "Development Status :: 3 - Alpha", "License :: OSI Approved :: MIT License", ], )
Add "Python 2" classifier since it works (according to Travis CI).
Add "Python 2" classifier since it works (according to Travis CI).
Python
mit
MarkusH/rinse,simudream/rinse,simudream/rinse,funkybob/rinse,tysonclugg/rinse,thedrow/rinse,tysonclugg/rinse,MarkusH/rinse
--- +++ @@ -18,6 +18,7 @@ 'requests', ], classifiers=[ + "Programming Language :: Python :: 2", "Programming Language :: Python :: 3", "Development Status :: 3 - Alpha", "License :: OSI Approved :: MIT License",
ee8355e8c3d06c6add56ce6962d5ccb9432c98c5
setup.py
setup.py
from setuptools import setup def readme(): with open('README.rst') as f: return f.read() setup(name='housecanary', version='0.5', description='Client Wrapper for the HouseCanary API', long_description=readme(), url='http://github.com/housecanary/hc-api-python', author='HouseCanary', author_email='techops@housecanary.com', license='MIT', packages=['housecanary'], install_requires=['requests','docopt', 'openpyxl'], zip_safe=False, test_suite='nose.collector', tests_require=['nose', 'mock'], scripts=['bin/hc_api_export'])
from setuptools import setup def readme(): with open('README.rst') as f: return f.read() setup(name='housecanary', version='0.5.1', description='Client Wrapper for the HouseCanary API', long_description=readme(), url='http://github.com/housecanary/hc-api-python', author='HouseCanary', author_email='techops@housecanary.com', license='MIT', packages=['housecanary', 'housecanary.excel'], install_requires=['requests','docopt', 'openpyxl'], zip_safe=False, test_suite='nose.collector', tests_require=['nose', 'mock'], scripts=['bin/hc_api_export'])
Add missing package name and bump version
Add missing package name and bump version
Python
mit
housecanary/hc-api-python
--- +++ @@ -5,14 +5,14 @@ return f.read() setup(name='housecanary', - version='0.5', + version='0.5.1', description='Client Wrapper for the HouseCanary API', long_description=readme(), url='http://github.com/housecanary/hc-api-python', author='HouseCanary', author_email='techops@housecanary.com', license='MIT', - packages=['housecanary'], + packages=['housecanary', 'housecanary.excel'], install_requires=['requests','docopt', 'openpyxl'], zip_safe=False, test_suite='nose.collector',
98c80428b35e2a79b4481c5eb9180613266e9698
setup.py
setup.py
from setuptools import find_packages, setup version = '6.0.0' install_requires = ( 'djangorestframework>=2.4.3,<3', 'incuna_mail>=2.0.0,<3', ) extras_require = { 'avatar': [ 'django-imagekit>=3.2', ], 'utils': [ 'raven>=5.1.1', ], } setup( name='django-user-management', packages=find_packages(), include_package_data=True, version=version, description='User management model mixins and api views.', long_description='', keywords='django rest framework user management api', author='Incuna', author_email='admin@incuna.com', url='https://github.com/incuna/django-user-management/', install_requires=install_requires, extras_require=extras_require, zip_safe=False, license='BSD', classifiers=[ 'Development Status :: 5 - Production/Stable', 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Topic :: Software Development', 'Topic :: Utilities', ], )
from setuptools import find_packages, setup version = '6.0.0' install_requires = ( 'djangorestframework>=2.4.4,<3', 'incuna_mail>=2.0.0,<3', ) extras_require = { 'avatar': [ 'django-imagekit>=3.2', ], 'utils': [ 'raven>=5.1.1', ], } setup( name='django-user-management', packages=find_packages(), include_package_data=True, version=version, description='User management model mixins and api views.', long_description='', keywords='django rest framework user management api', author='Incuna', author_email='admin@incuna.com', url='https://github.com/incuna/django-user-management/', install_requires=install_requires, extras_require=extras_require, zip_safe=False, license='BSD', classifiers=[ 'Development Status :: 5 - Production/Stable', 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Topic :: Software Development', 'Topic :: Utilities', ], )
Update `djangorestframework` from 2.4.3 to 2.4.4
Update `djangorestframework` from 2.4.3 to 2.4.4
Python
bsd-2-clause
incuna/django-user-management,incuna/django-user-management
--- +++ @@ -5,7 +5,7 @@ install_requires = ( - 'djangorestframework>=2.4.3,<3', + 'djangorestframework>=2.4.4,<3', 'incuna_mail>=2.0.0,<3', )
350f3bb3431d451f6bf6f2fac2e696b9122d65a6
setup.py
setup.py
#!/usr/bin/env python import os import sys from setuptools import setup readme = open('README.rst').read() doclink = """ Documentation ------------- The full documentation is at http://gryaml.rtfd.org.""" history = open('HISTORY.rst').read().replace('.. :changelog:', '') setup( name='gryaml', use_scm_version=True, description='Represent Neo4j graph data as YAML.', long_description=readme + '\n\n' + doclink + '\n\n' + history, author='Wil Cooley', author_email='wcooley@nakedape.cc', url='https://github.com/wcooley/python-gryaml', packages=[ 'gryaml', ], package_dir={'gryaml': 'gryaml'}, include_package_data=True, install_requires=[ 'py2neo>=2.0,<3', 'pyyaml', ], setup_requires=['setuptools_scm'], license='MIT', zip_safe=False, keywords='gryaml', classifiers=[ 'Development Status :: 2 - Pre-Alpha', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Natural Language :: English', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: Implementation :: PyPy', ], )
#!/usr/bin/env python """Setuptools setup.""" from setuptools import setup readme = open('README.rst').read() doclink = """ Documentation ------------- The full documentation is at http://gryaml.rtfd.org.""" history = open('HISTORY.rst').read().replace('.. :changelog:', '') setup( name='gryaml', use_scm_version=True, description='Represent Neo4j graph data as YAML.', long_description=readme + '\n\n' + doclink + '\n\n' + history, author='Wil Cooley', author_email='wcooley@nakedape.cc', url='https://github.com/wcooley/python-gryaml', packages=[ 'gryaml', ], package_dir={'gryaml': 'gryaml'}, include_package_data=True, install_requires=[ 'boltons', 'py2neo>=2.0,<3', 'pyyaml', ], setup_requires=['setuptools_scm'], license='MIT', zip_safe=False, keywords='gryaml', classifiers=[ 'Development Status :: 2 - Pre-Alpha', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Natural Language :: English', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.6', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: Implementation :: PyPy', ], )
Add missing 'boltons' package & clean up
Add missing 'boltons' package & clean up
Python
mit
wcooley/python-gryaml
--- +++ @@ -1,7 +1,5 @@ #!/usr/bin/env python - -import os -import sys +"""Setuptools setup.""" from setuptools import setup @@ -27,6 +25,7 @@ package_dir={'gryaml': 'gryaml'}, include_package_data=True, install_requires=[ + 'boltons', 'py2neo>=2.0,<3', 'pyyaml', ],
672d6cb517198bc37c4126c997ba984901a14b55
setup.py
setup.py
import os, io from setuptools import setup, find_packages long_description = ( io.open('README.rst', encoding='utf-8').read() + '\n' + io.open('CHANGES.txt', encoding='utf-8').read()) setup(name='more.jinja2', version='0.3.dev0', description="Jinja2 template integration for Morepath", long_description=long_description, author="Martijn Faassen", author_email="faassen@startifact.com", keywords='morepath jinja2', license="BSD", url="http://pypi.python.org/pypi/more.jinja2", namespace_packages=['more'], packages=find_packages(), include_package_data=True, zip_safe=False, install_requires=[ 'setuptools', 'morepath >= 0.10', 'Jinja2 >= 2.7.3' ], extras_require = dict( test=['pytest >= 2.6.0', 'pytest-cov', 'WebTest'], ), )
import io from setuptools import setup, find_packages long_description = '\n'.join(( io.open('README.rst', encoding='utf-8').read(), io.open('CHANGES.txt', encoding='utf-8').read() )) setup(name='more.jinja2', version='0.3.dev0', description="Jinja2 template integration for Morepath", long_description=long_description, author="Martijn Faassen", author_email="faassen@startifact.com", keywords='morepath jinja2', license="BSD", url="http://pypi.python.org/pypi/more.jinja2", namespace_packages=['more'], packages=find_packages(), include_package_data=True, zip_safe=False, install_requires=[ 'setuptools', 'morepath >= 0.10', 'Jinja2 >= 2.7.3' ], extras_require=dict( test=['pytest >= 2.6.0', 'pytest-cov', 'WebTest'], ), )
Use io.open with encoding='utf-8' and flake8 compliance
Use io.open with encoding='utf-8' and flake8 compliance
Python
bsd-3-clause
morepath/more.jinja2
--- +++ @@ -1,10 +1,10 @@ -import os, io +import io from setuptools import setup, find_packages -long_description = ( - io.open('README.rst', encoding='utf-8').read() - + '\n' + - io.open('CHANGES.txt', encoding='utf-8').read()) +long_description = '\n'.join(( + io.open('README.rst', encoding='utf-8').read(), + io.open('CHANGES.txt', encoding='utf-8').read() +)) setup(name='more.jinja2', version='0.3.dev0', @@ -24,7 +24,7 @@ 'morepath >= 0.10', 'Jinja2 >= 2.7.3' ], - extras_require = dict( + extras_require=dict( test=['pytest >= 2.6.0', 'pytest-cov', 'WebTest'],
7d475a44f2584396890360d1545abfa585dfdda8
setup.py
setup.py
from setuptools import setup, find_packages setup(name='django-forge', version=__import__('forge').__version__, author='Justin Bronn', author_email='jbronn@gmail.com', description='A Django implementation of the Puppet Forge web API.', url='https://github.com/jbronn/django-forge', download_url='http://pypi.python.org/pypi/django-forge/', install_requires=[ 'Django>=1.4', 'requests>=2', 'semantic_version>=2.1.2', ], packages=find_packages(), package_data={'apache': ['forge/apache'], 'templates': ['forge/templates']}, include_package_data=True, zip_safe=False, classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'Intended Audience :: System Administrators', 'License :: OSI Approved :: Apache Software License', ], )
from setuptools import setup, find_packages setup(name='django-forge', version=__import__('forge').__version__, author='Justin Bronn', author_email='jbronn@gmail.com', description='A Django implementation of the Puppet Forge API.', url='https://github.com/jbronn/django-forge', download_url='http://pypi.python.org/pypi/django-forge/', install_requires=[ 'Django>=1.4', 'requests>=2', 'semantic_version>=2.1.2', ], packages=find_packages(), include_package_data=True, zip_safe=False, classifiers=[ 'Development Status :: 4 - Beta', 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'Intended Audience :: System Administrators', 'License :: OSI Approved :: Apache Software License', ], )
Simplify description and MANIFEST.in suits me fine.
Simplify description and MANIFEST.in suits me fine.
Python
apache-2.0
jbronn/django-forge,jbronn/django-forge,ocadotechnology/django-forge,ocadotechnology/django-forge
--- +++ @@ -5,7 +5,7 @@ version=__import__('forge').__version__, author='Justin Bronn', author_email='jbronn@gmail.com', - description='A Django implementation of the Puppet Forge web API.', + description='A Django implementation of the Puppet Forge API.', url='https://github.com/jbronn/django-forge', download_url='http://pypi.python.org/pypi/django-forge/', install_requires=[ @@ -14,8 +14,6 @@ 'semantic_version>=2.1.2', ], packages=find_packages(), - package_data={'apache': ['forge/apache'], - 'templates': ['forge/templates']}, include_package_data=True, zip_safe=False, classifiers=[
2e850a22d0fcf8441d47928f5d758e3cb6b6bbaa
setup.py
setup.py
#!/usr/bin/env python from setuptools import find_packages, setup setup( name='Flask-uWSGI-WebSocket', version='0.6.1', url='https://github.com/zeekay/flask_uwsgi_websocket', license='MIT', author='Zach Kelling', author_email='zk@monoid.io', description='High-performance WebSockets for your Flask apps powered by uWSGI.', long_description=open('README.rst').read(), py_modules=['flask_uwsgi_websocket'], zip_safe=False, include_package_data=True, packages=find_packages(), platforms='any', install_requires=[ 'Flask', 'uwsgi', ], classifiers=[ 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Internet :: WWW/HTTP :: Dynamic Content', 'Topic :: Software Development :: Libraries :: Python Modules' ], keywords='uwsgi flask websockets' )
#!/usr/bin/env python from setuptools import find_packages, setup setup( name='Flask-uWSGI-WebSocket', version='0.6.1', url='https://github.com/zeekay/flask-uwsgi-websocket', license='MIT', author='Zach Kelling', author_email='zk@monoid.io', description='High-performance WebSockets for your Flask apps powered by uWSGI.', long_description=open('README.rst').read(), py_modules=['flask_uwsgi_websocket'], zip_safe=False, include_package_data=True, packages=find_packages(), platforms='any', install_requires=[ 'Flask', 'uwsgi', ], classifiers=[ 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Topic :: Internet :: WWW/HTTP :: Dynamic Content', 'Topic :: Software Development :: Libraries :: Python Modules' ], keywords='uwsgi flask websockets' )
Fix homepage url to point to the correct repo
Fix homepage url to point to the correct repo
Python
mit
zeekay/flask-uwsgi-websocket
--- +++ @@ -4,7 +4,7 @@ setup( name='Flask-uWSGI-WebSocket', version='0.6.1', - url='https://github.com/zeekay/flask_uwsgi_websocket', + url='https://github.com/zeekay/flask-uwsgi-websocket', license='MIT', author='Zach Kelling', author_email='zk@monoid.io',
fbb0708aebf437de8a5d2e8faf6334fc46d89b45
setup.py
setup.py
from setuptools import setup from rohrpost import __version__ def read(filepath): with open(filepath, "r", encoding="utf-8") as f: return f.read() setup( name="rohrpost", version=__version__, description="rohrpost WebSocket protocol for ASGI", long_description=read("README.rst"), url="https://github.com/axsemantics/rohrpost", author="Tobias Kunze", author_email="tobias.kunze@ax-semantics.com", license="MIT", python_requires=">=3.5", install_requires=["channels>=2.0"], classifiers=[ "Development Status :: 5 - Production/Stable", "Environment :: Web Environment", "Intended Audience :: Developers", "Operating System :: OS Independent", "License :: OSI Approved :: MIT License", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.5", "Programming Language :: Python :: 3.6", "Programming Language :: Python :: 3.7", "Topic :: Internet :: WWW/HTTP", ], packages=["rohrpost"], project_urls={ "Documentation": "https://rohrpost.readthedocs.io/en/stable/", "Source": "https://github.com/axsemantics/rohrpost", "Tracker": "https://github.com/axsemantics/rohrpost/issues", }, )
from setuptools import setup from rohrpost import __version__ def read(filepath): with open(filepath, "r", encoding="utf-8") as f: return f.read() setup( name="rohrpost", version=__version__, description="rohrpost WebSocket protocol for ASGI", long_description=read("README.rst"), url="https://github.com/axsemantics/rohrpost", author="Tobias Kunze", author_email="tobias.kunze@ax-semantics.com", license="MIT", python_requires=">=3.5", install_requires=["channels>=2.0"], classifiers=[ "Development Status :: 5 - Production/Stable", "Environment :: Web Environment", "Intended Audience :: Developers", "Operating System :: OS Independent", "License :: OSI Approved :: MIT License", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.5", "Programming Language :: Python :: 3.6", "Programming Language :: Python :: 3.7", "Programming Language :: Python :: 3 :: Only", "Topic :: Internet :: WWW/HTTP", ], packages=["rohrpost"], project_urls={ "Documentation": "https://rohrpost.readthedocs.io/en/stable/", "Source": "https://github.com/axsemantics/rohrpost", "Tracker": "https://github.com/axsemantics/rohrpost/issues", }, )
Add 'Python :: 3 :: Only' classifier
Add 'Python :: 3 :: Only' classifier
Python
mit
axsemantics/rohrpost,axsemantics/rohrpost
--- +++ @@ -29,6 +29,7 @@ "Programming Language :: Python :: 3.5", "Programming Language :: Python :: 3.6", "Programming Language :: Python :: 3.7", + "Programming Language :: Python :: 3 :: Only", "Topic :: Internet :: WWW/HTTP", ], packages=["rohrpost"],
fab75e9c6c6e4ebfffaeb5594f206022cadd5f31
setup.py
setup.py
#!/usr/bin/python # -*- coding: utf-8 -*- from setuptools import setup setup( name='pymisp', version='1.1.2', author='Raphaël Vinot', author_email='raphael.vinot@circl.lu', maintainer='Raphaël Vinot', url='https://github.com/MISP/PyMISP', description='Python API for MISP.', packages=['pymisp'], classifiers=[ 'License :: OSI Approved :: GNU General Public License v3 (GPLv3)', 'Development Status :: 5 - Production/Stable', 'Environment :: Console', 'Intended Audience :: Science/Research', 'Intended Audience :: Telecommunications Industry', 'Programming Language :: Python', 'Topic :: Security', 'Topic :: Internet', ], install_requires=['requests'], )
#!/usr/bin/python # -*- coding: utf-8 -*- from setuptools import setup setup( name='pymisp', version='1.2', author='Raphaël Vinot', author_email='raphael.vinot@circl.lu', maintainer='Raphaël Vinot', url='https://github.com/MISP/PyMISP', description='Python API for MISP.', packages=['pymisp'], classifiers=[ 'License :: OSI Approved :: GNU General Public License v3 (GPLv3)', 'Development Status :: 5 - Production/Stable', 'Environment :: Console', 'Intended Audience :: Science/Research', 'Intended Audience :: Telecommunications Industry', 'Programming Language :: Python', 'Topic :: Security', 'Topic :: Internet', ], install_requires=['requests'], )
Increase flexibility of upload sample
Increase flexibility of upload sample
Python
bsd-2-clause
pombredanne/PyMISP,grolinet/PyMISP,iglocska/PyMISP
--- +++ @@ -4,7 +4,7 @@ setup( name='pymisp', - version='1.1.2', + version='1.2', author='Raphaël Vinot', author_email='raphael.vinot@circl.lu', maintainer='Raphaël Vinot',
8c228a79450c49ee1d494ca1e3cf61ea7bcc8177
setup.py
setup.py
""" Copyright (c) 2010-2013, Anthony Garcia <anthony@lagg.me> Distributed under the ISC License (see LICENSE) """ from distutils.core import setup, Command from distutils.errors import DistutilsOptionError from unittest import TestLoader, TextTestRunner import os import steam class run_tests(Command): description = "Run the steamodd unit tests" user_options = [ ("key=", 'k', "Your API key") ] def initialize_options(self): self.key = None def finalize_options(self): if not self.key: raise DistutilsOptionError("API key is required") else: os.environ["STEAM_API_KEY"] = self.key def run(self): tests = TestLoader().discover("tests") TextTestRunner(verbosity = 2).run(tests) setup(name = "steamodd", version = steam.__version__, description = "High level Steam API implementation with low level reusable core", packages = ["steam"], author = steam.__author__, author_email = steam.__contact__, url = "https://github.com/Lagg/steamodd", classifiers = [ "License :: OSI Approved :: ISC License (ISCL)", "Intended Audience :: Developers", "Operating System :: OS Independent", "Programming Language :: Python" ], license = steam.__license__, cmdclass = {"run_tests": run_tests})
""" Copyright (c) 2010-2013, Anthony Garcia <anthony@lagg.me> Distributed under the ISC License (see LICENSE) """ from distutils.core import setup, Command from distutils.errors import DistutilsOptionError from unittest import TestLoader, TextTestRunner import steam class run_tests(Command): description = "Run the steamodd unit tests" user_options = [ ("key=", 'k', "Your API key") ] def initialize_options(self): self.key = None def finalize_options(self): if not self.key: raise DistutilsOptionError("API key is required") else: steam.api.key.set(self.key) def run(self): tests = TestLoader().discover("tests") TextTestRunner(verbosity = 2).run(tests) setup(name = "steamodd", version = steam.__version__, description = "High level Steam API implementation with low level reusable core", packages = ["steam"], author = steam.__author__, author_email = steam.__contact__, url = "https://github.com/Lagg/steamodd", classifiers = [ "License :: OSI Approved :: ISC License (ISCL)", "Intended Audience :: Developers", "Operating System :: OS Independent", "Programming Language :: Python" ], license = steam.__license__, cmdclass = {"run_tests": run_tests})
Set API key directly in test runner
Set API key directly in test runner
Python
isc
miedzinski/steamodd,Lagg/steamodd
--- +++ @@ -6,7 +6,6 @@ from distutils.core import setup, Command from distutils.errors import DistutilsOptionError from unittest import TestLoader, TextTestRunner -import os import steam class run_tests(Command): @@ -23,7 +22,7 @@ if not self.key: raise DistutilsOptionError("API key is required") else: - os.environ["STEAM_API_KEY"] = self.key + steam.api.key.set(self.key) def run(self): tests = TestLoader().discover("tests")
17956eb2b8089432ff2a0fcec5ce56884f904db1
setup.py
setup.py
# # Copyright 2013 Cisco Systems # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from setuptools import setup, find_packages setup( name='django-cloudslave', version='0.2.0', description='Create, use and destroy temporary slaves in the cloud', author='Soren Hansen', author_email='sorhanse@cisco.com', url='http://github.com/sorenh/python-django-cloudslave', packages=find_packages(), include_package_data=True, license='Apache 2.0', keywords='django openstack cloud', install_requires=[ 'django', 'python-novaclient' ], test_suite='tests.main', classifiers=[ 'Development Status :: 2 - Pre-Alpha', 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: Apache Software License', 'Operating System :: POSIX :: Linux', 'Programming Language :: Python', 'Topic :: Software Development', ] )
# # Copyright 2013 Cisco Systems # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. from setuptools import setup, find_packages setup( name='django-cloudslave', version='0.2.0', description='Create, use and destroy temporary slaves in the cloud', author='Soren Hansen', author_email='sorhanse@cisco.com', url='http://github.com/sorenh/python-django-cloudslave', packages=find_packages(), include_package_data=True, license='Apache 2.0', keywords='django openstack cloud', install_requires=[ 'django', 'python-novaclient', 'south' ], test_suite='tests.main', classifiers=[ 'Development Status :: 2 - Pre-Alpha', 'Environment :: Web Environment', 'Framework :: Django', 'Intended Audience :: Developers', 'License :: OSI Approved :: Apache Software License', 'Operating System :: POSIX :: Linux', 'Programming Language :: Python', 'Topic :: Software Development', ] )
Add south as a dependency.
Add south as a dependency.
Python
apache-2.0
sorenh/python-django-cloudslave
--- +++ @@ -28,7 +28,8 @@ keywords='django openstack cloud', install_requires=[ 'django', - 'python-novaclient' + 'python-novaclient', + 'south' ], test_suite='tests.main', classifiers=[
5f58d9f73b3b674d1d39ea7027a2e6de6dc8ff44
setup.py
setup.py
# -*- coding: utf-8 -*- from distutils.core import setup setup( name='nutshell', packages=['nutshell'], version='0.1.1', description='A minimal python library to access Nutshell CRM:s JSON-RPC API.', author=u'Emil Stenström', author_email='em@kth.se', url='https://github.com/EmilStenstrom/python-nutshell', download_url='https://github.com/EmilStenstrom/python-nutshell/tarball/0.1.1', keywords=['nutshell', 'nutshell-crm', 'json-rpc'], classifiers=[], )
# -*- coding: utf-8 -*- from distutils.core import setup setup( name='nutshell', packages=['nutshell'], version='0.1.1', description='A minimal python library to access Nutshell CRM:s JSON-RPC API.', author=u'Emil Stenström', author_email='em@kth.se', url='https://github.com/EmilStenstrom/python-nutshell', download_url='https://github.com/EmilStenstrom/python-nutshell/tarball/0.1.1', install_requires=["requests"], keywords=['nutshell', 'nutshell-crm', 'json-rpc'], classifiers=[], )
Add requests as installation dependency.
Add requests as installation dependency.
Python
mit
EmilStenstrom/python-nutshell
--- +++ @@ -10,6 +10,7 @@ author_email='em@kth.se', url='https://github.com/EmilStenstrom/python-nutshell', download_url='https://github.com/EmilStenstrom/python-nutshell/tarball/0.1.1', + install_requires=["requests"], keywords=['nutshell', 'nutshell-crm', 'json-rpc'], classifiers=[], )
c04e740db80792076c5a7299da8e552dfa3603bf
setup.py
setup.py
import os from setuptools import setup, find_packages def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() setup( name = 'django-helpline-faq', version = '1.1', description = 'A simple FAQ application for Django sites.', long_description = read('README.rst'), license = "BSD", author ='Kevin Fricovsky', author_email = 'kfricovsky@gmail.com', url = 'http://django-fack.rtfd.org/', packages = find_packages(exclude=['example']), zip_safe = False, classifiers = [ 'Development Status :: 3 - Alpha', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Framework :: Django', ], install_requires = ['Django >= 1.3'], test_suite = "faq._testrunner.runtests", tests_require = ["mock"], )
import os from setuptools import setup, find_packages def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() setup( name = 'django-helpline-faq', version = '1.1', description = 'A simple FAQ application for Django sites.', long_description = read('README.rst'), license = "BSD", author ='Kevin Fricovsky', author_email = 'kfricovsky@gmail.com', url = 'http://django-fack.rtfd.org/', packages = find_packages(exclude=['example']), include_package_data=True, zip_safe = False, classifiers = [ 'Development Status :: 3 - Alpha', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Framework :: Django', ], install_requires = ['Django >= 1.3'], test_suite = "faq._testrunner.runtests", tests_require = ["mock"], )
Include Package Data was missing.
Include Package Data was missing.
Python
bsd-3-clause
Kirembu/django-helpline-faq,Kirembu/django-helpline-faq
--- +++ @@ -16,6 +16,7 @@ url = 'http://django-fack.rtfd.org/', packages = find_packages(exclude=['example']), + include_package_data=True, zip_safe = False, classifiers = [
67a0f6c0aa8015f5dea7dcc8c7bc6cae809016f5
setup.py
setup.py
import os from setuptools import setup def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() setup(name='windpowerlib', version='0.1.2dev', description='Creating time series of wind power plants.', url='http://github.com/wind-python/windpowerlib', author='oemof developer group', author_email='windpowerlib@rl-institut.de', license=None, packages=['windpowerlib'], package_data={ 'windpowerlib': [os.path.join('data', '*.csv')]}, long_description=read('README.rst'), zip_safe=False, install_requires=['pandas >= 0.19.1', 'requests'], extras_require={ 'dev': ['pytest', 'jupyter', 'sphinx_rtd_theme', 'nbformat']})
import os from setuptools import setup def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() setup(name='windpowerlib', version='0.1.2dev', description='Creating time series of wind power plants.', url='http://github.com/wind-python/windpowerlib', author='oemof developer group', author_email='windpowerlib@rl-institut.de', license=None, packages=['windpowerlib'], package_data={ 'windpowerlib': [os.path.join('data', '*.csv')]}, long_description=read('README.rst'), zip_safe=False, install_requires=['pandas >= 0.19.1, < 0.25.0', 'requests'], extras_require={ 'dev': ['pytest', 'jupyter', 'sphinx_rtd_theme', 'nbformat']})
Add upper limit of pandas
Add upper limit of pandas
Python
mit
wind-python/windpowerlib
--- +++ @@ -18,7 +18,7 @@ 'windpowerlib': [os.path.join('data', '*.csv')]}, long_description=read('README.rst'), zip_safe=False, - install_requires=['pandas >= 0.19.1', + install_requires=['pandas >= 0.19.1, < 0.25.0', 'requests'], extras_require={ 'dev': ['pytest', 'jupyter', 'sphinx_rtd_theme', 'nbformat']})
199c421742c054129bc07ecfdf8b255482c4ad28
setup.py
setup.py
from setuptools import setup, find_packages import sys, os version = '0.1.0' description = "CKAN extension for creating/distributing budget data packages" with open('README.rst') as readme: long_description = readme.read() setup( name='ckanext-budgets', version=version, description=description, long_description=long_description, classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Other Audience', 'License :: OSI Approved :: GNU Affero General Public License v3', 'Programming Language :: Python :: 2.7', 'Topic :: Internet :: WWW/HTTP :: Dynamic Content', ], keywords='ckan', author='Tryggvi Bjorgvinsson', author_email='tryggvi.bjorgvinsson@okfn.org', url='https://github.com/tryggvib/ckanext-budgets', license='AGPLv3', packages=find_packages(exclude=['ez_setup', 'examples', 'tests']), namespace_packages=['ckanext', 'ckanext.budgets'], include_package_data=True, zip_safe=False, install_requires=[ # -*- Extra requirements: -*- 'unicodecsv', 'requests', 'six', 'py-dateutil', ], entry_points=''' [ckan.plugins] budgets=ckanext.budgets.plugin:BudgetDataPackagePlugin ''', )
from setuptools import setup, find_packages import sys, os version = '0.1.1' description = "CKAN extension for creating/distributing budget data packages" with open('README.rst') as readme: long_description = readme.read() setup( name='ckanext-budgets', version=version, description=description, long_description=long_description, classifiers=[ 'Development Status :: 4 - Beta', 'Intended Audience :: Other Audience', 'License :: OSI Approved :: GNU Affero General Public License v3', 'Programming Language :: Python :: 2.7', 'Topic :: Internet :: WWW/HTTP :: Dynamic Content', ], keywords='ckan', author='Tryggvi Bjorgvinsson', author_email='tryggvi.bjorgvinsson@okfn.org', url='https://github.com/tryggvib/ckanext-budgets', license='AGPLv3', packages=find_packages(exclude=['ez_setup', 'examples', 'tests']), namespace_packages=['ckanext', 'ckanext.budgets'], include_package_data=True, zip_safe=False, install_requires=[ # -*- Extra requirements: -*- 'unicodecsv', 'requests', 'six', 'py-dateutil', 'budgetdatapackage' ], entry_points=''' [ckan.plugins] budgets=ckanext.budgets.plugin:BudgetDataPackagePlugin ''', )
Update dependencies and bump patch version
Update dependencies and bump patch version budgetdatapackage was missing from the dependencies and has now been added.
Python
agpl-3.0
openspending/ckanext-budgets,openspending/ckanext-budgets
--- +++ @@ -1,7 +1,7 @@ from setuptools import setup, find_packages import sys, os -version = '0.1.0' +version = '0.1.1' description = "CKAN extension for creating/distributing budget data packages" with open('README.rst') as readme: @@ -34,6 +34,7 @@ 'requests', 'six', 'py-dateutil', + 'budgetdatapackage' ], entry_points=''' [ckan.plugins]
72d01a13761afbdcdfeb4fabb9095fa786403b18
setup.py
setup.py
from setuptools import find_packages, setup setup( name='ngx-task', version='0.1', description='Testimonial for candidates to show up their code-foo', author='Dmitry Shulyak', author_email='dmitri.shulyak@gmail.com', url='https://github.com/shudmi/ngx-task', classifiers=[ 'License :: Apache License 2.0', 'Programming Language :: Python', 'Programming Language :: Python 3', 'Programming Language :: Python 3.4', ], packages=find_packages(exclude=['tests', 'tests.*']), install_requires=[], entry_points=""" [console_scripts] ngx_generate=ngx_task.cli.generate_data ngx_process=ngx_task.cli.process_data """ )
from setuptools import find_packages, setup setup( name='ngx-task', version='0.2', description='Testimonial for candidates to show up their code-foo', author='Dmitry Shulyak', author_email='dmitri.shulyak@gmail.com', url='https://github.com/shudmi/ngx-task', classifiers=[ 'License :: Apache License 2.0', 'Programming Language :: Python', 'Programming Language :: Python 3', 'Programming Language :: Python 3.4', ], packages=find_packages(exclude=['tests', 'tests.*']), install_requires=[], tests_require=[ "pytest==3.0.7", ], entry_points=""" [console_scripts] ngx_generate=ngx_task.cli:generate_data ngx_process=ngx_task.cli:process_data """ )
Add tests requirements, fix console scripts definitions
Add tests requirements, fix console scripts definitions
Python
apache-2.0
shudmi/ngx-task
--- +++ @@ -2,7 +2,7 @@ setup( name='ngx-task', - version='0.1', + version='0.2', description='Testimonial for candidates to show up their code-foo', author='Dmitry Shulyak', author_email='dmitri.shulyak@gmail.com', @@ -15,9 +15,12 @@ ], packages=find_packages(exclude=['tests', 'tests.*']), install_requires=[], + tests_require=[ + "pytest==3.0.7", + ], entry_points=""" [console_scripts] - ngx_generate=ngx_task.cli.generate_data - ngx_process=ngx_task.cli.process_data + ngx_generate=ngx_task.cli:generate_data + ngx_process=ngx_task.cli:process_data """ )
bebe2be26d21289bb43936d3895c4b29126d508c
setup.py
setup.py
from setuptools import setup # "import" __version__ for line in open('nbsphinx.py'): if line.startswith('__version__'): exec(line) break setup( name='nbsphinx', version=__version__, py_modules=['nbsphinx'], install_requires=[ 'docutils', 'jinja2', 'nbconvert', 'traitlets', 'nbformat', 'sphinx>=1.3.2,!=1.5.0', ], author='Matthias Geier', author_email='Matthias.Geier@gmail.com', description='Jupyter Notebook Tools for Sphinx', long_description=open('README.rst').read(), license='MIT', keywords='Sphinx Jupyter notebook'.split(), url='http://nbsphinx.rtfd.io/', platforms='any', classifiers=[ 'Framework :: Sphinx', 'Framework :: Sphinx :: Extension', 'Framework :: Jupyter', 'Intended Audience :: Education', 'Intended Audience :: Science/Research', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 3', 'Topic :: Documentation :: Sphinx', ], zip_safe=True, )
from setuptools import setup # "import" __version__ for line in open('nbsphinx.py'): if line.startswith('__version__'): exec(line) break setup( name='nbsphinx', version=__version__, py_modules=['nbsphinx'], install_requires=[ 'docutils', 'jinja2', 'nbconvert', 'traitlets', 'nbformat', 'sphinx>=1.3.2,!=1.5.0', ], author='Matthias Geier', author_email='Matthias.Geier@gmail.com', description='Jupyter Notebook Tools for Sphinx', long_description=open('README.rst').read(), license='MIT', keywords='Sphinx Jupyter notebook'.split(), url='http://nbsphinx.readthedocs.io/', platforms='any', classifiers=[ 'Framework :: Sphinx', 'Framework :: Sphinx :: Extension', 'Framework :: Jupyter', 'Intended Audience :: Education', 'Intended Audience :: Science/Research', 'License :: OSI Approved :: MIT License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 3', 'Topic :: Documentation :: Sphinx', ], zip_safe=True, )
Change rtfd -> readthedocs in package description
DOC: Change rtfd -> readthedocs in package description
Python
mit
spatialaudio/nbsphinx,spatialaudio/nbsphinx,spatialaudio/nbsphinx
--- +++ @@ -24,7 +24,7 @@ long_description=open('README.rst').read(), license='MIT', keywords='Sphinx Jupyter notebook'.split(), - url='http://nbsphinx.rtfd.io/', + url='http://nbsphinx.readthedocs.io/', platforms='any', classifiers=[ 'Framework :: Sphinx',
9d19fb7ada5caaa2dc74736cd12635bed3d8516a
setup.py
setup.py
import os from setuptools import setup, find_packages setup(name='morepath', version = '0.1dev', description="A micro web-framework with superpowers", author="Martijn Faassen", author_email="faassen@startifact.com", license="BSD", packages=find_packages(), include_package_data=True, zip_safe=False, install_requires=[ 'setuptools', 'venusian', 'reg', 'werkzeug', ], extras_require = dict( test=['pytest >= 2.0', 'pytest-cov'], ), )
import os from setuptools import setup, find_packages setup(name='morepath', version = '0.1dev', description="A micro web-framework with superpowers", author="Martijn Faassen", author_email="faassen@startifact.com", license="BSD", packages=find_packages(), include_package_data=True, zip_safe=False, install_requires=[ 'setuptools', 'venusian >= 1.0a8', 'reg', 'werkzeug >= 0.9.4', ], extras_require = dict( test=['pytest >= 2.0', 'pytest-cov'], ), )
Put in some version requirements.
Put in some version requirements.
Python
bsd-3-clause
taschini/morepath,faassen/morepath,morepath/morepath
--- +++ @@ -12,9 +12,9 @@ zip_safe=False, install_requires=[ 'setuptools', - 'venusian', + 'venusian >= 1.0a8', 'reg', - 'werkzeug', + 'werkzeug >= 0.9.4', ], extras_require = dict( test=['pytest >= 2.0',
cbbcbb5707a90929da8d47f6b3322cebec983279
setup.py
setup.py
from setuptools import setup from distutils.core import Command import os import sys class TestCommand(Command): description = "Run tests" user_options = [] def initialize_options(self): pass def finalize_options(self): pass def run(self): import subprocess errno = subprocess.call(['nosetests', '--debug=DEBUG', '-s']) raise SystemExit(errno) setup( name='mafan', version='0.2.7', author='Herman Schaaf', author_email='herman@ironzebra.com', packages=['mafan', 'mafan.hanzidentifier'], scripts=['bin/convert.py'], url='https://github.com/hermanschaaf/mafan', license='LICENSE.txt', description='A toolbox for working with the Chinese language in Python', long_description=open('docs/README.md').read(), cmdclass={ 'test': TestCommand, }, install_requires=[ "jieba == 0.29", "argparse == 1.1", "chardet == 2.1.1", "wsgiref == 0.1.2", ], )
from setuptools import setup from distutils.core import Command import os import sys class TestCommand(Command): description = "Run tests" user_options = [] def initialize_options(self): pass def finalize_options(self): pass def run(self): import subprocess errno = subprocess.call(['nosetests', '--debug=DEBUG', '-s']) raise SystemExit(errno) setup( name='mafan', version='0.2.10', author='Herman Schaaf', author_email='herman@ironzebra.com', packages=[ 'mafan', 'mafan.hanzidentifier', 'mafan.third_party', 'mafan.third_party.jianfan' ], scripts=['bin/convert.py'], url='https://github.com/hermanschaaf/mafan', license='LICENSE.txt', description='A toolbox for working with the Chinese language in Python', long_description=open('docs/README.md').read(), cmdclass={ 'test': TestCommand, }, install_requires=[ "jieba == 0.29", "argparse == 1.1", "chardet == 2.1.1", "wsgiref == 0.1.2", ], )
Add jianfan to python package installation
Add jianfan to python package installation
Python
mit
hermanschaaf/mafan,cychiang/mafan
--- +++ @@ -21,10 +21,15 @@ setup( name='mafan', - version='0.2.7', + version='0.2.10', author='Herman Schaaf', author_email='herman@ironzebra.com', - packages=['mafan', 'mafan.hanzidentifier'], + packages=[ + 'mafan', + 'mafan.hanzidentifier', + 'mafan.third_party', + 'mafan.third_party.jianfan' + ], scripts=['bin/convert.py'], url='https://github.com/hermanschaaf/mafan', license='LICENSE.txt',
ba2e263e40e1324f8fd6c3ee012a8d9ada46bdd1
setup.py
setup.py
#!/usr/local/bin/python3 from distutils.core import setup, Extension setup( name = 'lazy', version = '1.0', description = 'Lazy', ext_modules = [ Extension( name = 'b._collections', sources = [ 'src/collections.c', ], ), Extension( name = 'b._types', depends = [ 'include/memoizer.h', ], include_dirs = [ 'include', ], sources = [ 'src/memoizer.c', 'src/types.c', ], ), ], )
#!/usr/local/bin/python3 from distutils.core import setup, Extension # Workaround -Werror=statement-after-declaration # http://bugs.python.org/issue18211 import os os.environ['CFLAGS'] = '-Wno-unused-result' setup( name = 'lazy', version = '1.0', description = 'Lazy', ext_modules = [ Extension( name = 'b._collections', sources = [ 'src/collections.c', ], ), Extension( name = 'b._types', depends = [ 'include/memoizer.h', ], include_dirs = [ 'include', ], sources = [ 'src/memoizer.c', 'src/types.c', ], ), ], )
Disable strict C90 flag that appears to be accidentally being used by distutils
Disable strict C90 flag that appears to be accidentally being used by distutils
Python
apache-2.0
blake-sheridan/py,blake-sheridan/py
--- +++ @@ -1,6 +1,11 @@ #!/usr/local/bin/python3 from distutils.core import setup, Extension + +# Workaround -Werror=statement-after-declaration +# http://bugs.python.org/issue18211 +import os +os.environ['CFLAGS'] = '-Wno-unused-result' setup( name = 'lazy', @@ -17,7 +22,7 @@ name = 'b._types', depends = [ 'include/memoizer.h', - ], + ], include_dirs = [ 'include', ],
ce0f4a30cad570557ad67122333041806d411adc
tasks.py
tasks.py
from invoke import Collection from invocations import docs from invocations.checks import blacken from invocations.packaging import release from invocations.pytest import test, coverage ns = Collection(test, coverage, release, blacken, docs) ns.configure({"packaging": {"sign": True}})
from invoke import Collection from invocations import docs from invocations.checks import blacken from invocations.packaging import release from invocations.pytest import test, coverage ns = Collection(test, coverage, release, blacken, docs) ns.configure( {"packaging": {"sign": True, "changelog_file": "docs/changelog.rst"}} )
Set changelog_file for invocations release task, which now dry-runs ok
Set changelog_file for invocations release task, which now dry-runs ok
Python
bsd-2-clause
bitprophet/lexicon
--- +++ @@ -6,4 +6,6 @@ ns = Collection(test, coverage, release, blacken, docs) -ns.configure({"packaging": {"sign": True}}) +ns.configure( + {"packaging": {"sign": True, "changelog_file": "docs/changelog.rst"}} +)
35fab0222543a2f32ef395bf6b622bad29533ceb
tests.py
tests.py
import unittest from gtlaunch import Launcher class MockOptions(object): def __init__(self): self.verbose = False self.config = '' self.project = '' class LauncherTestCase(unittest.TestCase): def setUp(self): self.options = MockOptions() def test_lazy_init(self): launcher = Launcher(self.options, lazy=True) self.assertIsNone(launcher.project) def test_no_cwd(self): project = { 'tabs': [], } launcher = Launcher(self.options, lazy=True) args = launcher.build_args(project) self.assertNotIn('--working-directory', args) def test_cwd(self): project = { 'cwd': '/home/test', 'tabs': [], } launcher = Launcher(self.options, lazy=True) args = launcher.build_args(project) idx = args.index('--working-directory') self.assertEqual(args[idx + 1], project['cwd']) def test_args_maximize(self): project = { 'cwd': '~', 'tabs': [], } launcher = Launcher(self.options, lazy=True) args = launcher.build_args(project) self.assertIn('--maximize', args) if __name__ == '__main__': unittest.main()
import unittest from gtlaunch import Launcher class MockOptions(object): def __init__(self): self.verbose = False self.config = '' self.project = '' class LauncherTestCase(unittest.TestCase): def setUp(self): self.options = MockOptions() self.launcher = Launcher(self.options, lazy=True) def test_lazy_init(self): self.assertIsNone(self.launcher.project) def test_no_cwd(self): project = { 'tabs': [], } args = self.launcher.build_args(project) self.assertNotIn('--working-directory', args) def test_cwd(self): project = { 'cwd': '/home/test', 'tabs': [], } args = self.launcher.build_args(project) idx = args.index('--working-directory') self.assertEqual(args[idx + 1], project['cwd']) def test_args_maximize(self): project = { 'cwd': '~', 'tabs': [], } args = self.launcher.build_args(project) self.assertIn('--maximize', args) if __name__ == '__main__': unittest.main()
Create lazy launcher in setUp.
Create lazy launcher in setUp.
Python
mit
GoldenLine/gtlaunch
--- +++ @@ -13,17 +13,16 @@ class LauncherTestCase(unittest.TestCase): def setUp(self): self.options = MockOptions() + self.launcher = Launcher(self.options, lazy=True) def test_lazy_init(self): - launcher = Launcher(self.options, lazy=True) - self.assertIsNone(launcher.project) + self.assertIsNone(self.launcher.project) def test_no_cwd(self): project = { 'tabs': [], } - launcher = Launcher(self.options, lazy=True) - args = launcher.build_args(project) + args = self.launcher.build_args(project) self.assertNotIn('--working-directory', args) def test_cwd(self): @@ -31,8 +30,7 @@ 'cwd': '/home/test', 'tabs': [], } - launcher = Launcher(self.options, lazy=True) - args = launcher.build_args(project) + args = self.launcher.build_args(project) idx = args.index('--working-directory') self.assertEqual(args[idx + 1], project['cwd']) @@ -41,8 +39,7 @@ 'cwd': '~', 'tabs': [], } - launcher = Launcher(self.options, lazy=True) - args = launcher.build_args(project) + args = self.launcher.build_args(project) self.assertIn('--maximize', args)
f7852806c3198d58162b66e18bfd9998ef33b63c
lexos/receivers/stats_receiver.py
lexos/receivers/stats_receiver.py
from lexos.receivers.base_receiver import BaseReceiver class StatsReceiver(BaseReceiver): def __init__(self): """So far there is no frontend option for statistics analysis""" super().__init__() def options_from_front_end(self): """So far there is no frontend option for statistics analysis""" pass
from lexos.receivers.base_receiver import BaseReceiver class StatsReceiver(BaseReceiver): def __init__(self): """So far there is no frontend option for statistics analysis""" super().__init__() def options_from_front_end(self): """So far there is no frontend option for statistics analysis""" raise NotImplementedError
Modify receiver to prevent using in future
Modify receiver to prevent using in future
Python
mit
WheatonCS/Lexos,WheatonCS/Lexos,WheatonCS/Lexos
--- +++ @@ -8,4 +8,4 @@ def options_from_front_end(self): """So far there is no frontend option for statistics analysis""" - pass + raise NotImplementedError
addee67fbf46a795c9de4669c9951c84b6590d98
cartoframes/context/base_context.py
cartoframes/context/base_context.py
from abc import ABCMeta, abstractmethod class BaseContext(): __metaclass__ = ABCMeta @abstractmethod def download(self): pass @abstractmethod def upload(self): pass @abstractmethod def execute_query(self): pass @abstractmethod def execute_long_running_query(self): pass
from abc import ABCMeta, abstractmethod class BaseContext(): __metaclass__ = ABCMeta @abstractmethod def download(self, query, retry_times=0): pass @abstractmethod def upload(self, query, data): pass @abstractmethod def execute_query(self, query, parse_json=True, do_post=True, format=None, **request_args): pass @abstractmethod def execute_long_running_query(self, query): pass
Add params in BaseContext abtract methods
Add params in BaseContext abtract methods
Python
bsd-3-clause
CartoDB/cartoframes,CartoDB/cartoframes
--- +++ @@ -5,17 +5,17 @@ __metaclass__ = ABCMeta @abstractmethod - def download(self): + def download(self, query, retry_times=0): pass @abstractmethod - def upload(self): + def upload(self, query, data): pass @abstractmethod - def execute_query(self): + def execute_query(self, query, parse_json=True, do_post=True, format=None, **request_args): pass @abstractmethod - def execute_long_running_query(self): + def execute_long_running_query(self, query): pass
b084e02dd2cf7b492c69090b6acd548066c7c34f
pos_picking_state_fix/models/pos_picking.py
pos_picking_state_fix/models/pos_picking.py
# -*- coding: utf-8 -*- # See README file for full copyright and licensing details. from openerp import models, api class PosPicking(models.Model): _inherit = 'pos.order' @api.multi def create_picking(self): try: super(PosPicking, self).create_picking() except: # Cancel move lines if self.picking_id.state != 'done': for move in self.picking_id.move_lines: move.do_unreserve() return True
# -*- coding: utf-8 -*- # See README file for full copyright and licensing details. import time from openerp import models, api from openerp.tools import DEFAULT_SERVER_DATETIME_FORMAT class PosPicking(models.Model): _inherit = 'pos.order' @api.multi def create_picking(self): try: super(PosPicking, self).create_picking() except: if self.picking_id.state != 'done': for move in self.picking_id.move_lines: if move.quant_ids: # We pass this move to done because the quants were already moved move.write({'state': 'done', 'date': time.strftime(DEFAULT_SERVER_DATETIME_FORMAT)}) else: # If there are no moved quants we pass the move to Waiting Availability move.do_unreserve() return True
Check if quants are moved and pass moves to done to avoid duplication
[FIX] Check if quants are moved and pass moves to done to avoid duplication
Python
agpl-3.0
rgbconsulting/rgb-addons,rgbconsulting/rgb-pos,rgbconsulting/rgb-pos,rgbconsulting/rgb-addons
--- +++ @@ -1,7 +1,9 @@ # -*- coding: utf-8 -*- # See README file for full copyright and licensing details. +import time from openerp import models, api +from openerp.tools import DEFAULT_SERVER_DATETIME_FORMAT class PosPicking(models.Model): @@ -12,8 +14,12 @@ try: super(PosPicking, self).create_picking() except: - # Cancel move lines if self.picking_id.state != 'done': for move in self.picking_id.move_lines: - move.do_unreserve() + if move.quant_ids: + # We pass this move to done because the quants were already moved + move.write({'state': 'done', 'date': time.strftime(DEFAULT_SERVER_DATETIME_FORMAT)}) + else: + # If there are no moved quants we pass the move to Waiting Availability + move.do_unreserve() return True
5b011488b5fcfd17f2029e833b757d24d437908e
document_page_project/__manifest__.py
document_page_project/__manifest__.py
# Copyright 2019 ForgeFlow S.L. (https://www.forgeflow.com) - Lois Rilo # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). { "name": "Document Page Project", "summary": "This module links document pages to projects", "version": "13.0.1.0.1", "development_status": "Production/Stable", "category": "Project", "author": "ForgeFlow, Odoo Community Association (OCA)", "website": "https://github.com/OCA/knowledge", "license": "AGPL-3", "depends": ["project", "document_page"], "data": ["views/document_page_views.xml", "views/project_project_views.xml"], "installable": True, }
# Copyright 2019 ForgeFlow S.L. (https://www.forgeflow.com) - Lois Rilo # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). { "name": "Document Page Project", "summary": "This module links document pages to projects", "version": "13.0.1.0.1", "development_status": "Beta", "category": "Project", "author": "ForgeFlow, Odoo Community Association (OCA)", "website": "https://github.com/OCA/knowledge", "license": "AGPL-3", "depends": ["project", "document_page"], "data": ["views/document_page_views.xml", "views/project_project_views.xml"], "installable": True, }
Revert to Beta as document_page is Beta
[REV] document_page_project: Revert to Beta as document_page is Beta
Python
agpl-3.0
OCA/knowledge,OCA/knowledge,OCA/knowledge
--- +++ @@ -5,7 +5,7 @@ "name": "Document Page Project", "summary": "This module links document pages to projects", "version": "13.0.1.0.1", - "development_status": "Production/Stable", + "development_status": "Beta", "category": "Project", "author": "ForgeFlow, Odoo Community Association (OCA)", "website": "https://github.com/OCA/knowledge",
f40bf1441121c138877e27bd23bcef73cf5c2cef
cisco_olt_http/tests/test_operations.py
cisco_olt_http/tests/test_operations.py
import os import pytest import requests from cisco_olt_http import operations from cisco_olt_http.client import Client @pytest.fixture def data_dir(): return os.path.abspath( os.path.join(os.path.dirname(__file__), 'data')) def test_get_data(): client = Client('http://base-url') show_equipment_op = operations.ShowEquipmentOp(client) op_data = show_equipment_op.get_data() assert op_data class TestOperationResult: def test_ok_response(self, data_dir, mocker): response = mocker.Mock(autospec=requests.Response) with open(os.path.join(data_dir, 'ok_response.xml')) as of: response.content = of.read() operation_result = operations.OperationResult(response) assert not operation_result.error assert operation_result.error_str == 'OK'
import os import pytest import requests from cisco_olt_http import operations from cisco_olt_http.client import Client @pytest.fixture def data_dir(): return os.path.abspath( os.path.join(os.path.dirname(__file__), 'data')) @pytest.fixture def ok_response(data_dir, mocker): response = mocker.Mock(autospec=requests.Response) with open(os.path.join(data_dir, 'ok_response.xml')) as of: response.content = of.read() return response def test_get_data(): client = Client('http://base-url') show_equipment_op = operations.ShowEquipmentOp(client) op_data = show_equipment_op.get_data() assert op_data class TestOperationResult: def test_ok_response(self, ok_response): operation_result = operations.OperationResult(ok_response) assert not operation_result.error assert operation_result.error_str == 'OK'
Move ok response creation to pytest fixture
Move ok response creation to pytest fixture
Python
mit
Vnet-as/cisco-olt-http-client,beezz/cisco-olt-http-client
--- +++ @@ -12,6 +12,14 @@ os.path.join(os.path.dirname(__file__), 'data')) +@pytest.fixture +def ok_response(data_dir, mocker): + response = mocker.Mock(autospec=requests.Response) + with open(os.path.join(data_dir, 'ok_response.xml')) as of: + response.content = of.read() + return response + + def test_get_data(): client = Client('http://base-url') show_equipment_op = operations.ShowEquipmentOp(client) @@ -21,14 +29,7 @@ class TestOperationResult: - def test_ok_response(self, data_dir, mocker): - - response = mocker.Mock(autospec=requests.Response) - - with open(os.path.join(data_dir, 'ok_response.xml')) as of: - response.content = of.read() - - operation_result = operations.OperationResult(response) - + def test_ok_response(self, ok_response): + operation_result = operations.OperationResult(ok_response) assert not operation_result.error assert operation_result.error_str == 'OK'
19af4b5c8c849750dd0885ea4fcfb651545b7985
migrations/002_add_month_start.py
migrations/002_add_month_start.py
""" Add _week_start_at field to all documents in all collections """ from backdrop.core.bucket import utc from backdrop.core.records import Record import logging log = logging.getLogger(__name__) def up(db): for name in db.collection_names(): log.info("Migrating collection: {0}".format(name)) collection = db[name] query = { "_timestamp": {"$exists": True}, "_month_start_at": {"$exists": False} } for document in collection.find(query): document['_timestamp'] = utc(document['_timestamp']) if '_week_start_at' in document: document.pop('_week_start_at') record = Record(document) collection.save(record.to_mongo())
""" Add _week_start_at field to all documents in all collections """ from backdrop.core.bucket import utc from backdrop.core.records import Record import logging log = logging.getLogger(__name__) def up(db): for name in db.collection_names(): log.info("Migrating collection: {0}".format(name)) collection = db[name] query = { "_timestamp": {"$exists": True}, "_month_start_at": {"$exists": False} } for document in collection.find(query): document['_timestamp'] = utc(document['_timestamp']) if '_week_start_at' in document: document.pop('_week_start_at') if '_updated_at' in document: document.pop('_updated_at') record = Record(document) collection.save(record.to_mongo())
Remove disallowed fields before resaving on migrations.
Remove disallowed fields before resaving on migrations. - TODO: fix this properly.
Python
mit
alphagov/backdrop,alphagov/backdrop,alphagov/backdrop
--- +++ @@ -20,6 +20,8 @@ document['_timestamp'] = utc(document['_timestamp']) if '_week_start_at' in document: document.pop('_week_start_at') + if '_updated_at' in document: + document.pop('_updated_at') record = Record(document) collection.save(record.to_mongo())
de5c0c9107156a073670d68fcb04e575e08f9b80
sympy/__init__.py
sympy/__init__.py
__version__ = "0.5.0" from sympy.core import * from series import * from simplify import * from solvers import * from matrices import * from geometry import * from polynomials import * from utilities import * #from specfun import * from integrals import * try: from plotting import Plot except ImportError, e: print str(e)
__version__ = "0.5.0" from sympy.core import * from series import * from simplify import * from solvers import * from matrices import * from geometry import * from polynomials import * from utilities import * #from specfun import * from integrals import * try: from plotting import Plot except ImportError, e: class Plot(object): def __init__(*args, **kwargs): raise e
Hide ctypes import error until Plot() is called.
Hide ctypes import error until Plot() is called.
Python
bsd-3-clause
kmacinnis/sympy,Curious72/sympy,meghana1995/sympy,MechCoder/sympy,saurabhjn76/sympy,VaibhavAgarwalVA/sympy,Designist/sympy,lidavidm/sympy,skidzo/sympy,beni55/sympy,Davidjohnwilson/sympy,jaimahajan1997/sympy,kmacinnis/sympy,MridulS/sympy,mcdaniel67/sympy,jbbskinny/sympy,pandeyadarsh/sympy,jaimahajan1997/sympy,mattpap/sympy-polys,lindsayad/sympy,souravsingh/sympy,ryanGT/sympy,Sumith1896/sympy,tovrstra/sympy,moble/sympy,emon10005/sympy,kaushik94/sympy,mafiya69/sympy,emon10005/sympy,Vishluck/sympy,Arafatk/sympy,MridulS/sympy,debugger22/sympy,madan96/sympy,Shaswat27/sympy,Titan-C/sympy,shikil/sympy,rahuldan/sympy,vipulroxx/sympy,toolforger/sympy,shipci/sympy,KevinGoodsell/sympy,cswiercz/sympy,abhiii5459/sympy,Gadal/sympy,jbaayen/sympy,ChristinaZografou/sympy,iamutkarshtiwari/sympy,rahuldan/sympy,kmacinnis/sympy,sahilshekhawat/sympy,asm666/sympy,chaffra/sympy,kevalds51/sympy,maniteja123/sympy,sunny94/temp,vipulroxx/sympy,drufat/sympy,shikil/sympy,saurabhjn76/sympy,mafiya69/sympy,atreyv/sympy,Curious72/sympy,hrashk/sympy,Mitchkoens/sympy,dqnykamp/sympy,ahhda/sympy,liangjiaxing/sympy,madan96/sympy,lindsayad/sympy,iamutkarshtiwari/sympy,VaibhavAgarwalVA/sympy,bukzor/sympy,wyom/sympy,flacjacket/sympy,sahmed95/sympy,Titan-C/sympy,bukzor/sympy,jamesblunt/sympy,kaushik94/sympy,cswiercz/sympy,sahilshekhawat/sympy,skirpichev/omg,dqnykamp/sympy,wyom/sympy,AunShiLord/sympy,cccfran/sympy,mafiya69/sympy,AkademieOlympia/sympy,Sumith1896/sympy,jbbskinny/sympy,kumarkrishna/sympy,atreyv/sympy,ga7g08/sympy,postvakje/sympy,farhaanbukhsh/sympy,pbrady/sympy,moble/sympy,ahhda/sympy,minrk/sympy,garvitr/sympy,skidzo/sympy,MridulS/sympy,meghana1995/sympy,ahhda/sympy,yashsharan/sympy,drufat/sympy,shipci/sympy,lindsayad/sympy,aktech/sympy,kaushik94/sympy,pernici/sympy,abloomston/sympy,atsao72/sympy,hrashk/sympy,minrk/sympy,sahmed95/sympy,sampadsaha5/sympy,wanglongqi/sympy,chaffra/sympy,hargup/sympy,AkademieOlympia/sympy,hargup/sympy,moble/sympy,yashsharan/sympy,garvitr/sympy,aktech/sympy,kevalds51/sympy,liangjiaxing/sympy,emon10005/sympy,atreyv/sympy,shipci/sympy,iamutkarshtiwari/sympy,hazelnusse/sympy-old,asm666/sympy,Davidjohnwilson/sympy,fperez/sympy,oliverlee/sympy,postvakje/sympy,yukoba/sympy,amitjamadagni/sympy,Vishluck/sympy,AunShiLord/sympy,kaichogami/sympy,AunShiLord/sympy,sunny94/temp,madan96/sympy,srjoglekar246/sympy,ChristinaZografou/sympy,Arafatk/sympy,cccfran/sympy,VaibhavAgarwalVA/sympy,abloomston/sympy,atsao72/sympy,ga7g08/sympy,Mitchkoens/sympy,Curious72/sympy,Designist/sympy,ga7g08/sympy,Shaswat27/sympy,ChristinaZografou/sympy,grevutiu-gabriel/sympy,mcdaniel67/sympy,hazelnusse/sympy-old,grevutiu-gabriel/sympy,kumarkrishna/sympy,toolforger/sympy,abhiii5459/sympy,yukoba/sympy,beni55/sympy,Gadal/sympy,jamesblunt/sympy,hargup/sympy,Gadal/sympy,jaimahajan1997/sympy,aktech/sympy,diofant/diofant,Mitchkoens/sympy,kaichogami/sympy,bukzor/sympy,souravsingh/sympy,sahmed95/sympy,toolforger/sympy,cswiercz/sympy,abloomston/sympy,MechCoder/sympy,Shaswat27/sympy,pbrady/sympy,wanglongqi/sympy,sampadsaha5/sympy,pandeyadarsh/sympy,drufat/sympy,yukoba/sympy,kaichogami/sympy,MechCoder/sympy,wanglongqi/sympy,Vishluck/sympy,abhiii5459/sympy,vipulroxx/sympy,AkademieOlympia/sympy,Arafatk/sympy,mcdaniel67/sympy,kumarkrishna/sympy,lidavidm/sympy,jerli/sympy,sampadsaha5/sympy,sahilshekhawat/sympy,debugger22/sympy,souravsingh/sympy,pandeyadarsh/sympy,grevutiu-gabriel/sympy,wyom/sympy,shikil/sympy,maniteja123/sympy,skidzo/sympy,jamesblunt/sympy,amitjamadagni/sympy,kevalds51/sympy,rahuldan/sympy,beni55/sympy,atsao72/sympy,oliverlee/sympy,jerli/sympy,Davidjohnwilson/sympy,saurabhjn76/sympy,postvakje/sympy,liangjiaxing/sympy,chaffra/sympy,dqnykamp/sympy,garvitr/sympy,maniteja123/sympy,yashsharan/sympy,oliverlee/sympy,Designist/sympy,asm666/sympy,farhaanbukhsh/sympy,jbbskinny/sympy,sunny94/temp,Sumith1896/sympy,farhaanbukhsh/sympy,cccfran/sympy,hrashk/sympy,Titan-C/sympy,debugger22/sympy,pbrady/sympy,lidavidm/sympy,meghana1995/sympy,jerli/sympy
--- +++ @@ -12,7 +12,10 @@ from utilities import * #from specfun import * from integrals import * + try: from plotting import Plot except ImportError, e: - print str(e) + class Plot(object): + def __init__(*args, **kwargs): + raise e
b82dbd63aedf8a6a6af494b6d6be697a9f4230d5
tests/test_utils.py
tests/test_utils.py
import pickle from six.moves import range from fuel.utils import do_not_pickle_attributes @do_not_pickle_attributes("non_pickable", "bulky_attr") class TestClass(object): def __init__(self): self.load() def load(self): self.bulky_attr = list(range(100)) self.non_pickable = lambda x: x def test_do_not_pickle_attributes(): cl = TestClass() dump = pickle.dumps(cl) loaded = pickle.loads(dump) assert loaded.bulky_attr == list(range(100)) assert loaded.non_pickable is not None
import pickle from six.moves import range from fuel.utils import do_not_pickle_attributes, expand_axis_label @do_not_pickle_attributes("non_pickable", "bulky_attr") class TestClass(object): def __init__(self): self.load() def load(self): self.bulky_attr = list(range(100)) self.non_pickable = lambda x: x def test_do_not_pickle_attributes(): cl = TestClass() dump = pickle.dumps(cl) loaded = pickle.loads(dump) assert loaded.bulky_attr == list(range(100)) assert loaded.non_pickable is not None def test_expand_axis_label(): assert expand_axis_label('b') == 'batch' assert expand_axis_label('c') == 'channel' assert expand_axis_label('t') == 'time' assert expand_axis_label('0') == 'axis_0' assert expand_axis_label('1') == 'axis_1' assert expand_axis_label('0b') == '0b' assert expand_axis_label('') == ''
Add unit test for expand_axis_label
Add unit test for expand_axis_label
Python
mit
dwf/fuel,ejls/fuel,udibr/fuel,rizar/fuel,capybaralet/fuel,rizar/fuel,EderSantana/fuel,EderSantana/fuel,orhanf/fuel,aalmah/fuel,mila-udem/fuel,mjwillson/fuel,glewis17/fuel,orhanf/fuel,dhruvparamhans/fuel,hantek/fuel,lamblin/fuel,jbornschein/fuel,dribnet/fuel,markusnagel/fuel,udibr/fuel,harmdevries89/fuel,dribnet/fuel,glewis17/fuel,janchorowski/fuel,harmdevries89/fuel,chrishokamp/fuel,jbornschein/fuel,vdumoulin/fuel,codeaudit/fuel,aalmah/fuel,markusnagel/fuel,dmitriy-serdyuk/fuel,rodrigob/fuel,dwf/fuel,dmitriy-serdyuk/fuel,bouthilx/fuel,bouthilx/fuel,capybaralet/fuel,janchorowski/fuel,laurent-dinh/fuel,dhruvparamhans/fuel,mjwillson/fuel,chrishokamp/fuel,mila-udem/fuel,lamblin/fuel,ejls/fuel,vdumoulin/fuel,laurent-dinh/fuel,codeaudit/fuel,hantek/fuel,rodrigob/fuel
--- +++ @@ -1,7 +1,7 @@ import pickle from six.moves import range -from fuel.utils import do_not_pickle_attributes +from fuel.utils import do_not_pickle_attributes, expand_axis_label @do_not_pickle_attributes("non_pickable", "bulky_attr") @@ -22,3 +22,13 @@ loaded = pickle.loads(dump) assert loaded.bulky_attr == list(range(100)) assert loaded.non_pickable is not None + + +def test_expand_axis_label(): + assert expand_axis_label('b') == 'batch' + assert expand_axis_label('c') == 'channel' + assert expand_axis_label('t') == 'time' + assert expand_axis_label('0') == 'axis_0' + assert expand_axis_label('1') == 'axis_1' + assert expand_axis_label('0b') == '0b' + assert expand_axis_label('') == ''
3e6f835a88183182b6ebba25c61666735a69fc81
tests/vaultshell.py
tests/vaultshell.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import unittest class VaultShellTests(unittest.TestCase): def test_basic(self): print "test basic. Pass"
#!/usr/bin/env python # -*- coding: utf-8 -*- import unittest import vault_shell.vault_commandhelper as VaultHelper class VaultShellTests(unittest.TestCase): def test_basic(self): print "test basic. Pass" vaulthelper = VaultHelper.VaultCommandHelper() self.failUnless(vaulthelper is not None) def test_execute_vault_commands(self): vaulthelper = VaultHelper.VaultCommandHelper() output = vaulthelper.execute_vault_commands(['vault']) self.failUnless(output is not None) def test_get_commandkey_from_cmdlist(self): vaulthelper = VaultHelper.VaultCommandHelper() cmdkey = vaulthelper.get_commandkey_from_cmdlist(["token-create"]) self.assertEqual(cmdkey, "vault_token-create", msg="cmdkey did not match")
Add more tests for the vault commandhelper
Add more tests for the vault commandhelper
Python
apache-2.0
bdastur/vault-shell
--- +++ @@ -2,7 +2,22 @@ # -*- coding: utf-8 -*- import unittest +import vault_shell.vault_commandhelper as VaultHelper class VaultShellTests(unittest.TestCase): def test_basic(self): print "test basic. Pass" + vaulthelper = VaultHelper.VaultCommandHelper() + self.failUnless(vaulthelper is not None) + + def test_execute_vault_commands(self): + vaulthelper = VaultHelper.VaultCommandHelper() + output = vaulthelper.execute_vault_commands(['vault']) + self.failUnless(output is not None) + + def test_get_commandkey_from_cmdlist(self): + vaulthelper = VaultHelper.VaultCommandHelper() + cmdkey = vaulthelper.get_commandkey_from_cmdlist(["token-create"]) + self.assertEqual(cmdkey, + "vault_token-create", + msg="cmdkey did not match")
7b50c9290a8c8d3481d9147ebb66d3b7868ad7fc
bouncer-plumbing/mlab-to-bouncer/makeconfig.py
bouncer-plumbing/mlab-to-bouncer/makeconfig.py
#!/usr/bin/env python import sys import yaml def read_parts_from_stdin(): data = sys.stdin.read() parts_string = data.split("----") parts_parsed = [] for part in parts_string: part_parsed = yaml.safe_load(part) parts_parsed.append(part_parsed) return parts_parsed def assemble_bouncer_config(parts): merged_parts = { } for part in parts: merged_parts.update(part) bouncer_config = { 'collector': merged_parts } return yaml.dump(bouncer_config) def write_bouncer_config(bouncer_config, path): print bouncer_config parts = read_parts_from_stdin() bouncer_config = assemble_bouncer_config(parts) write_bouncer_config(bouncer_config, '/home/mlab/data/bouncer.yaml')
#!/usr/bin/env python import sys import yaml def read_parts_from_stdin(): data = sys.stdin.read() parts_string = data.split("----") parts_parsed = [] for part in parts_string: part_parsed = yaml.safe_load(part) parts_parsed.append(part_parsed) return parts_parsed def assemble_bouncer_config(parts): merged_parts = { } for part in parts: merged_parts.update(part) bouncer_config = { 'collector': merged_parts } return yaml.dump(bouncer_config) def write_bouncer_config(path, bouncer_config_contents): try: f = open(path, 'w') f.write(bouncer_config_contents) f.close() except IOError: print "Couldn't write to bouncer config file." exit(1) bouncer_config_path = '/home/mlab/data/bouncer.yaml' if len(sys.argv) >= 2: bouncer_config_path = sys.argv[1] # FIXME: Read from the mlab-ns simulator. parts = read_parts_from_stdin() bouncer_config = assemble_bouncer_config(parts) write_bouncer_config(bouncer_config_path, bouncer_config)
Write to bouncer config file
Write to bouncer config file
Python
apache-2.0
m-lab/ooni-support,hellais/ooni-support,m-lab/ooni-support,hellais/ooni-support
--- +++ @@ -19,10 +19,21 @@ bouncer_config = { 'collector': merged_parts } return yaml.dump(bouncer_config) -def write_bouncer_config(bouncer_config, path): - print bouncer_config +def write_bouncer_config(path, bouncer_config_contents): + try: + f = open(path, 'w') + f.write(bouncer_config_contents) + f.close() + except IOError: + print "Couldn't write to bouncer config file." + exit(1) +bouncer_config_path = '/home/mlab/data/bouncer.yaml' +if len(sys.argv) >= 2: + bouncer_config_path = sys.argv[1] + +# FIXME: Read from the mlab-ns simulator. parts = read_parts_from_stdin() bouncer_config = assemble_bouncer_config(parts) -write_bouncer_config(bouncer_config, '/home/mlab/data/bouncer.yaml') +write_bouncer_config(bouncer_config_path, bouncer_config)
8170ad6cdfd2346bc24a3d743663b4866416ca83
Engine.py
Engine.py
#Imports import pygame from pygame.locals import * from OpenGL.GL import * from OpenGL.GLU import * from shapes import Shape, Cube #Create a game class class Game(object): #Constructor def __init__(self, title, width, height, bgcolour): #Initialise pygame pygame.init() #Set the size of the window self.size = self.width, self.height = width, height #Set the default perspective and clipping distances self.fov = 45.0 self.aspectratio = width / height self.minrender = 0.1 self.maxrender = 80 #Set the pygame mode to use double buffering and open gl pygame.set_mode(self.size, DOUBLEBUF|OPENGL) #Set the perspective self.setperspective() #Create an empty list of shapes to render self.shapes = [] #Create a function to update the perspective def setperspective(self): #Set the perspective gluPerspective(self.fov, self.aspectratio, self.minrender, self.maxrender)
#Imports import pygame from pygame.locals import * from OpenGL.GL import * from OpenGL.GLU import * from shapes import Shape, Cube #Create a game class class Game(object): #Constructor def __init__(self, title, width, height, bgcolour): #Initialise pygame pygame.init() #Set the size of the window self.size = self.width, self.height = width, height #Set the default perspective and clipping distances self.fov = 45.0 self.aspectratio = width / height self.minrender = 0.1 self.maxrender = 80 #Set the pygame mode to use double buffering and open gl pygame.set_mode(self.size, DOUBLEBUF|OPENGL) #Set the perspective self.setperspective() #Create an empty list of shapes to render self.shapes = [] #Create a function to update the perspective def setperspective(self): #Set the perspective gluPerspective(self.fov, self.aspectratio, self.minrender, self.maxrender) #Create a function to add a shape def addshape(self, s): self.shapes.append(s) #Create a function to render the shapes def render(self): #For each of the shapes, check the type and render it for s in shapes: #If the shape is a cube, call the rendercube method if s.type == Shape.CUBE: rendercube(s)
Add functions to add shapes and iterate over each shape to render.
Add functions to add shapes and iterate over each shape to render.
Python
mit
thebillington/pyPhys3D
--- +++ @@ -39,4 +39,16 @@ #Set the perspective gluPerspective(self.fov, self.aspectratio, self.minrender, self.maxrender) + + #Create a function to add a shape + def addshape(self, s): + self.shapes.append(s) + + #Create a function to render the shapes + def render(self): + #For each of the shapes, check the type and render it + for s in shapes: + #If the shape is a cube, call the rendercube method + if s.type == Shape.CUBE: + rendercube(s)
53e1ff21bb219495f1b99f84dbb31624fdd35231
lpthw/ex33.py
lpthw/ex33.py
#i = 0 #numbers = [] #while i < 6: # print "At the top i is %d" % i # numbers.append(i) # # i += 1 # print "Numbers now: ", numbers # print "At the bottom i is %d" % i # # #print "The numbers: " # #for num in numbers: # print num #Study Drills print "What's the limit of the list?" a = raw_input("> ") def list_numbers(a): """This function might add numbers to a list?""" i = 0 numbers = [] while i < a: print "At the top i is %d" % i numbers.append(i) i += 1 print "Numbers now: ", numbers print "At the bottom i is %d" % i print "The numbers: " for num in numbers: print num return list_numbers(a)
#i = 0 #numbers = [] #while i < 6: # print "At the top i is %d" % i # numbers.append(i) # # i += 1 # print "Numbers now: ", numbers # print "At the bottom i is %d" % i # # #print "The numbers: " # #for num in numbers: # print num #Study Drills print "What's the limit of the list?" a = int(raw_input("> ")) def list_numbers(a): """This function might add numbers to a list?""" i = 0 numbers = [] while i < a: print "At the top i is %d" % i numbers.append(i) i += 1 print "Numbers now: ", numbers print "At the bottom i is %d" % i print "The numbers: " for num in numbers: print num return list_numbers(a)
Fix that crazy error that would cause enless looping...
Fix that crazy error that would cause enless looping...
Python
mit
jaredmanning/learning,jaredmanning/learning
--- +++ @@ -17,7 +17,7 @@ #Study Drills print "What's the limit of the list?" -a = raw_input("> ") +a = int(raw_input("> ")) def list_numbers(a): """This function might add numbers to a list?"""
92adc02daae13f6ef24ae1ec2eafac77ce528a74
setup/timvideos/streaming/list_aws_hosts.py
setup/timvideos/streaming/list_aws_hosts.py
# list_aws_hosts.py # list all active ec2 hosts from boto import ec2 import pw creds = pw.stream['aws'] ec2conn = ec2.connection.EC2Connection(creds['id'], creds['key'] ) reservations = ec2conn.get_all_instances() instances = [i for r in reservations for i in r.instances] for i in instances: if not i.dns_name: continue print i.tags['Name'], i.id, i.dns_name
#!/usr/bin/env python # -*- coding: utf-8 -*- # list_aws_hosts.py # list all active ec2 hosts """ Start / stop by name. Start mission "list_aws_hosts.py start mission" Stop mission "list_aws_hosts.py stop mission" Status mission "list_aws_hosts.py status mission" mission i-b59966c7 **OFF** stopped """ from boto import ec2 import pw creds = pw.stream['aws'] def aws_start(instance, name): if name == instance.tags['Name']: instance.start() def aws_stop(instance, name): if name == instance.tags['Name']: instance.stop() def aws_status(instance, name=None): if name and not name == instance.tags['Name']: return if not instance.dns_name: print instance.tags['Name'], instance.id, '**OFF**', instance.state else: print instance.tags['Name'], instance.id, instance.dns_name, instance.state def do_command(command, name): ec2conn = ec2.connection.EC2Connection(creds['id'], creds['key']) reservations = ec2conn.get_all_instances() instances = [i for r in reservations for i in r.instances] for i in instances: command(i, name) def do_status(): ec2conn = ec2.connection.EC2Connection(creds['id'], creds['key']) reservations = ec2conn.get_all_instances() instances = [i for r in reservations for i in r.instances] for i in instances: aws_status(i) if __name__ == '__main__': import sys if len(sys.argv) == 3: command, name = sys.argv[1:] if command == 'start': do_command(aws_start, name) elif command == 'stop': do_command(aws_stop, name) else: do_command(aws_status, name) else: do_status()
Update script to start, stop and status by name.
Update script to start, stop and status by name.
Python
mit
EricSchles/veyepar,CarlFK/veyepar,yoe/veyepar,yoe/veyepar,xfxf/veyepar,EricSchles/veyepar,yoe/veyepar,xfxf/veyepar,CarlFK/veyepar,xfxf/veyepar,CarlFK/veyepar,EricSchles/veyepar,CarlFK/veyepar,xfxf/veyepar,xfxf/veyepar,CarlFK/veyepar,yoe/veyepar,yoe/veyepar,EricSchles/veyepar,EricSchles/veyepar
--- +++ @@ -1,15 +1,61 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- # list_aws_hosts.py # list all active ec2 hosts + +""" +Start / stop by name. +Start mission "list_aws_hosts.py start mission" +Stop mission "list_aws_hosts.py stop mission" +Status mission "list_aws_hosts.py status mission" + mission i-b59966c7 **OFF** stopped +""" from boto import ec2 import pw creds = pw.stream['aws'] -ec2conn = ec2.connection.EC2Connection(creds['id'], creds['key'] ) -reservations = ec2conn.get_all_instances() -instances = [i for r in reservations for i in r.instances] -for i in instances: - if not i.dns_name: - continue - print i.tags['Name'], i.id, i.dns_name +def aws_start(instance, name): + if name == instance.tags['Name']: + instance.start() + +def aws_stop(instance, name): + if name == instance.tags['Name']: + instance.stop() + +def aws_status(instance, name=None): + if name and not name == instance.tags['Name']: + return + + if not instance.dns_name: + print instance.tags['Name'], instance.id, '**OFF**', instance.state + else: + print instance.tags['Name'], instance.id, instance.dns_name, instance.state + +def do_command(command, name): + ec2conn = ec2.connection.EC2Connection(creds['id'], creds['key']) + reservations = ec2conn.get_all_instances() + instances = [i for r in reservations for i in r.instances] + for i in instances: + command(i, name) + +def do_status(): + ec2conn = ec2.connection.EC2Connection(creds['id'], creds['key']) + reservations = ec2conn.get_all_instances() + instances = [i for r in reservations for i in r.instances] + for i in instances: + aws_status(i) + +if __name__ == '__main__': + import sys + if len(sys.argv) == 3: + command, name = sys.argv[1:] + if command == 'start': + do_command(aws_start, name) + elif command == 'stop': + do_command(aws_stop, name) + else: + do_command(aws_status, name) + else: + do_status()
6da69eb8f13dc56cc19d06a09d74005395de8989
fedmsg_meta_umb/tps.py
fedmsg_meta_umb/tps.py
# Copyright (C) 2017 Red Hat, Inc. # # fedmsg_meta_umb is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # fedmsg_meta_umb is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with fedmsg; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA # # Authors: Gowrishankar Rajaiyan <grajaiya@redhat.com> from fedmsg.meta.base import BaseProcessor class TPSProcessor(BaseProcessor): topic_prefix_re = r'/topic/VirtualTopic\.eng' __name__ = 'tps' def title(self, msg, **config): return msg['topic'].split('.', 2)[-1] def packages(self, msg, **config): return set([msg['headers']['component'].rsplit('-', 2)[0]])
# Copyright (C) 2017 Red Hat, Inc. # # fedmsg_meta_umb is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # fedmsg_meta_umb is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with fedmsg; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA # # Authors: Gowrishankar Rajaiyan <grajaiya@redhat.com> from fedmsg.meta.base import BaseProcessor class TPSProcessor(BaseProcessor): topic_prefix_re = r'/topic/VirtualTopic\.eng' __name__ = 'tps' __description__ = 'package sanity testing of brew builds' __obj__ = 'Test Package Sanity' __docs__ = 'https://mojo.redhat.com/docs/DOC-0000000' __link__ = 'https://sometpslink.engineering.redhat.com' def title(self, msg, **config): return msg['topic'].split('.', 2)[-1] def packages(self, msg, **config): return set([msg['headers']['component'].rsplit('-', 2)[0]])
Add missing attributes in TPSProcessor.
Add missing attributes in TPSProcessor. Signed-off-by: shanks <4508bc7244505cbe28c7ec6ff0c99c8246ca3de6@redhat.com>
Python
lgpl-2.1
release-engineering/fedmsg_meta_umb
--- +++ @@ -23,6 +23,10 @@ topic_prefix_re = r'/topic/VirtualTopic\.eng' __name__ = 'tps' + __description__ = 'package sanity testing of brew builds' + __obj__ = 'Test Package Sanity' + __docs__ = 'https://mojo.redhat.com/docs/DOC-0000000' + __link__ = 'https://sometpslink.engineering.redhat.com' def title(self, msg, **config): return msg['topic'].split('.', 2)[-1]
153ed6a519d6836adb02b934cff44974a7132b6d
flake8/parseDocTest.py
flake8/parseDocTest.py
def parseFailDetails(failDetails): """ Parse the line number of the doctest failure""" import re failDetails = failDetails.split(',') lineNo = -1 if len(failDetails) == 3: match = re.search("line.*?(\d+)", failDetails[1]) if match is None: return lineNo lineNo = int(match.group(1)) return lineNo def parseDocTestResult(docTestResStr): """ Extract the line number and filename of the doctest failure""" lines = docTestResStr.split("\n") for lineNo, line in enumerate(lines): failure = line.find("Failed example:") if failure != -1: failDetails = lines[lineNo - 1] yield parseFailDetails(failDetails)
def parseFailDetails(failDetails): """ Parse the line number of the doctest failure >>> parseFailDetails("blah") -1 """ import re failDetails = failDetails.split(',') lineNo = -1 if len(failDetails) == 3: match = re.search("line.*?(\d+)", failDetails[1]) if match is None: return lineNo lineNo = int(match.group(1)) return lineNo def parseDocTestResult(docTestResStr): """ Extract the line number and filename of the doctest failure""" lines = docTestResStr.split("\n") for lineNo, line in enumerate(lines): failure = line.find("Failed example:") if failure != -1: failDetails = lines[lineNo - 1] yield parseFailDetails(failDetails) if __name__ == "__main__": from doctest import testmod testmod()
Fix doc test failure parsing
Fix doc test failure parsing
Python
mit
softwaredoug/flake8_doctest
--- +++ @@ -1,5 +1,8 @@ def parseFailDetails(failDetails): - """ Parse the line number of the doctest failure""" + """ Parse the line number of the doctest failure + >>> parseFailDetails("blah") + -1 + """ import re failDetails = failDetails.split(',') lineNo = -1 @@ -19,3 +22,7 @@ if failure != -1: failDetails = lines[lineNo - 1] yield parseFailDetails(failDetails) + +if __name__ == "__main__": + from doctest import testmod + testmod()
808d089b2b93671ef3d4331007fc1c3da2dea0b5
example/urls.py
example/urls.py
from django.conf.urls import patterns # Uncomment the next two lines to enable the admin: # from django.contrib import admin # admin.autodiscover() urlpatterns = patterns('', # Example: # (r'^example/', include('example.foo.urls')), # Uncomment the admin/doc line below and add 'django.contrib.admindocs' # to INSTALLED_APPS to enable admin documentation: # (r'^admin/doc/', include('django.contrib.admindocs.urls')), # Uncomment the next line to enable the admin: # (r'^admin/(.*)', admin.site.root), ('^$', 'rpc4django.views.serve_rpc_request'), ('^RPC2$', 'rpc4django.views.serve_rpc_request'), )
from django.conf.urls import patterns from rpc4django.views import serve_rpc_request # Uncomment the next two lines to enable the admin: # from django.contrib import admin # admin.autodiscover() urlpatterns = patterns('', # Example: # (r'^example/', include('example.foo.urls')), # Uncomment the admin/doc line below and add 'django.contrib.admindocs' # to INSTALLED_APPS to enable admin documentation: # (r'^admin/doc/', include('django.contrib.admindocs.urls')), # Uncomment the next line to enable the admin: # (r'^admin/(.*)', admin.site.root), ('^$', 'rpc4django.views.serve_rpc_request'), ('^RPC2$', serve_rpc_request), )
Use django 1.10 patterns style
Use django 1.10 patterns style
Python
bsd-3-clause
davidfischer/rpc4django,davidfischer/rpc4django,davidfischer/rpc4django
--- +++ @@ -1,4 +1,5 @@ from django.conf.urls import patterns +from rpc4django.views import serve_rpc_request # Uncomment the next two lines to enable the admin: # from django.contrib import admin @@ -15,5 +16,5 @@ # Uncomment the next line to enable the admin: # (r'^admin/(.*)', admin.site.root), ('^$', 'rpc4django.views.serve_rpc_request'), - ('^RPC2$', 'rpc4django.views.serve_rpc_request'), + ('^RPC2$', serve_rpc_request), )
8e225f890fd90112a125648cbd49507340cd3224
events/search_indexes.py
events/search_indexes.py
from haystack import indexes from .models import Event, Place, PublicationStatus from django.utils.html import strip_tags class EventIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.CharField(document=True, use_template=True) autosuggest = indexes.EdgeNgramField(model_attr='name') start_time = indexes.DateField(model_attr='start_time') end_time = indexes.DateField(model_attr='end_time') def get_updated_field(self): return 'last_modified_time' def get_model(self): return Event def prepare(self, obj): #obj.lang_keywords = obj.keywords.filter(language=get_language()) if obj.description: obj.description = strip_tags(obj.description) return super(EventIndex, self).prepare(obj) def index_queryset(self, using=None): return self.get_model().objects.filter(publication_status=PublicationStatus.PUBLIC) class PlaceIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.CharField(document=True, use_template=True) autosuggest = indexes.EdgeNgramField(model_attr='name') def get_updated_field(self): return 'last_modified_time' def get_model(self): return Place
from haystack import indexes from .models import Event, Place, PublicationStatus from django.utils.html import strip_tags class EventIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.CharField(document=True, use_template=True) autosuggest = indexes.EdgeNgramField(model_attr='name') start_time = indexes.DateTimeField(model_attr='start_time') end_time = indexes.DateTimeField(model_attr='end_time') def get_updated_field(self): return 'last_modified_time' def get_model(self): return Event def prepare(self, obj): #obj.lang_keywords = obj.keywords.filter(language=get_language()) if obj.description: obj.description = strip_tags(obj.description) return super(EventIndex, self).prepare(obj) def index_queryset(self, using=None): return self.get_model().objects.filter(publication_status=PublicationStatus.PUBLIC) class PlaceIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.CharField(document=True, use_template=True) autosuggest = indexes.EdgeNgramField(model_attr='name') def get_updated_field(self): return 'last_modified_time' def get_model(self): return Place
Fix type of EventIndex fields
Fix type of EventIndex fields
Python
mit
tuomas777/linkedevents,aapris/linkedevents,aapris/linkedevents,City-of-Helsinki/linkedevents,City-of-Helsinki/linkedevents,tuomas777/linkedevents,aapris/linkedevents,tuomas777/linkedevents,City-of-Helsinki/linkedevents
--- +++ @@ -6,8 +6,8 @@ class EventIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.CharField(document=True, use_template=True) autosuggest = indexes.EdgeNgramField(model_attr='name') - start_time = indexes.DateField(model_attr='start_time') - end_time = indexes.DateField(model_attr='end_time') + start_time = indexes.DateTimeField(model_attr='start_time') + end_time = indexes.DateTimeField(model_attr='end_time') def get_updated_field(self): return 'last_modified_time'
40905893c296e2c812539079925adfd25e39d44f
wger/wsgi.py
wger/wsgi.py
""" WSGI config for workout_manager project. This module contains the WSGI application used by Django's development server and any production WSGI deployments. It should expose a module-level variable named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover this application via the ``WSGI_APPLICATION`` setting. Usually you will have the standard Django WSGI application here, but it also might make sense to replace the whole Django WSGI application with a custom one that later delegates to the Django one. For example, you could introduce WSGI middleware here, or combine a Django application with an application of another framework. """ import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "workout_manager.settings") # This application object is used by any WSGI server configured to use this # file. This includes Django's development server, if the WSGI_APPLICATION # setting points here. from django.core.wsgi import get_wsgi_application application = get_wsgi_application() # Apply WSGI middleware here. # from helloworld.wsgi import HelloWorldApplication # application = HelloWorldApplication(application)
""" WSGI config for workout_manager project. This module contains the WSGI application used by Django's development server and any production WSGI deployments. It should expose a module-level variable named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover this application via the ``WSGI_APPLICATION`` setting. Usually you will have the standard Django WSGI application here, but it also might make sense to replace the whole Django WSGI application with a custom one that later delegates to the Django one. For example, you could introduce WSGI middleware here, or combine a Django application with an application of another framework. """ import os os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings") # This application object is used by any WSGI server configured to use this # file. This includes Django's development server, if the WSGI_APPLICATION # setting points here. from django.core.wsgi import get_wsgi_application application = get_wsgi_application() # Apply WSGI middleware here. # from helloworld.wsgi import HelloWorldApplication # application = HelloWorldApplication(application)
Change location of default settings in WSGI
Change location of default settings in WSGI
Python
agpl-3.0
petervanderdoes/wger,rolandgeider/wger,DeveloperMal/wger,rolandgeider/wger,wger-project/wger,kjagoo/wger_stark,DeveloperMal/wger,wger-project/wger,petervanderdoes/wger,rolandgeider/wger,wger-project/wger,kjagoo/wger_stark,DeveloperMal/wger,DeveloperMal/wger,kjagoo/wger_stark,wger-project/wger,petervanderdoes/wger,rolandgeider/wger,kjagoo/wger_stark,petervanderdoes/wger
--- +++ @@ -15,7 +15,7 @@ """ import os -os.environ.setdefault("DJANGO_SETTINGS_MODULE", "workout_manager.settings") +os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings") # This application object is used by any WSGI server configured to use this # file. This includes Django's development server, if the WSGI_APPLICATION
98fad1af84abe13eb64baad58c8a2faf3cd6cccb
tt_dailyemailblast/tasks.py
tt_dailyemailblast/tasks.py
from celery.task import task from . import models from . import send_backends @task def send_daily_email_blasts(blast_pk): blast = models.DailyEmailBlast.objects.get(pk=blast_pk) send_backends.sync_daily_email_blasts(blast) @task def send_recipients_list(recipients_list_pk, blast_pk): blast = models.DailyEmailBlast.objects.get(pk=blast_pk) recipients_list = models.RecipientList.objects.get(pk=recipients_list_pk) send_backends.sync_recipients_list(recipients_list, blast) @task def send_recipients(recipient_pk, recipients_list_pk, blast_pk): blast = models.DailyEmailBlast.objects.get(pk=blast_pk) recipients_list = models.RecipientList.objects.get(pk=recipients_list_pk) recipient = models.Recipient.objects.get(pk=recipient_pk) send_backends.sync_recipient(recipient, recipients_list, blast)
from celery.task import task from . import models from .send_backends import sync @task def send_daily_email_blasts(blast_pk): blast = models.DailyEmailBlast.objects.get(pk=blast_pk) sync.sync_daily_email_blasts(blast) @task def send_recipients_list(recipients_list_pk, blast_pk): blast = models.DailyEmailBlast.objects.get(pk=blast_pk) recipients_list = models.RecipientList.objects.get(pk=recipients_list_pk) sync.sync_recipients_list(recipients_list, blast) @task def send_recipients(recipient_pk, recipients_list_pk, blast_pk): blast = models.DailyEmailBlast.objects.get(pk=blast_pk) recipients_list = models.RecipientList.objects.get(pk=recipients_list_pk) recipient = models.Recipient.objects.get(pk=recipient_pk) sync.sync_recipient(recipient, recipients_list, blast)
Fix every single async task was broken
Fix every single async task was broken
Python
apache-2.0
texastribune/tt_dailyemailblast,texastribune/tt_dailyemailblast
--- +++ @@ -1,20 +1,20 @@ from celery.task import task from . import models -from . import send_backends +from .send_backends import sync @task def send_daily_email_blasts(blast_pk): blast = models.DailyEmailBlast.objects.get(pk=blast_pk) - send_backends.sync_daily_email_blasts(blast) + sync.sync_daily_email_blasts(blast) @task def send_recipients_list(recipients_list_pk, blast_pk): blast = models.DailyEmailBlast.objects.get(pk=blast_pk) recipients_list = models.RecipientList.objects.get(pk=recipients_list_pk) - send_backends.sync_recipients_list(recipients_list, blast) + sync.sync_recipients_list(recipients_list, blast) @task @@ -22,4 +22,4 @@ blast = models.DailyEmailBlast.objects.get(pk=blast_pk) recipients_list = models.RecipientList.objects.get(pk=recipients_list_pk) recipient = models.Recipient.objects.get(pk=recipient_pk) - send_backends.sync_recipient(recipient, recipients_list, blast) + sync.sync_recipient(recipient, recipients_list, blast)
d33a624fa6aedb93ae43ba1d2c0f6a76d90ff4a6
foldermd5sums.py
foldermd5sums.py
#!/usr/bin/env python """Script to read data files in a directory, compute their md5sums, and output them to a JSON file.""" import json import os import sys import hashlib def get_md5sums(directory): md5sums = [] for filename in os.listdir(directory): md5 = hashlib.md5() with open(os.path.join(directory, filename), 'rb') as fp: for chunk in iter(lambda: fp.read(128 * md5.block_size), b''): md5.update(chunk) md5hash = md5.hexdigest() md5sums.append((filename, md5hash)) return md5sums if __name__ == '__main__': if len(sys.argv) < 3: print('Usage: ' + sys.argv[0] + ' input_directory output.json') sys.exit(1) directory = sys.argv[1] if not os.path.exists(directory): print('Directory does not exist!') sys.exit(1) output_json = sys.argv[2] md5sums = get_md5sums(directory) with open(output_json, 'w') as fp: json.dump(md5sums, fp, indent=0)
#!/usr/bin/env python """Script to read data files in a directory, compute their md5sums, and output them to a JSON file.""" import json import os import sys import hashlib def get_relative_filepaths(base_directory): """ Return a list of file paths without the base_directory prefix""" file_list = [] for root, subFolders, files in os.walk('Data'): relative_path="/".join(root.split('/')[1:]) for file in files: file_list.append(os.path.join(relative_path,file)) return file_list def get_md5sums(base_directory): md5sums = [] for filename in get_relative_filepaths(base_directory): md5 = hashlib.md5() full_filepath = os.path.join(base_directory, filename) with open(full_filepath, 'rb') as fp: for chunk in iter(lambda: fp.read(128 * md5.block_size), b''): md5.update(chunk) md5hash = md5.hexdigest() md5sums.append((filename, md5hash)) return md5sums if __name__ == '__main__': if len(sys.argv) < 3: print('Usage: ' + sys.argv[0] + ' input_directory output.json') sys.exit(1) directory = sys.argv[1] if not os.path.exists(directory): print('Directory does not exist!') sys.exit(1) output_json = sys.argv[2] md5sums = get_md5sums(directory) with open(output_json, 'w') as fp: json.dump(md5sums, fp, indent=0)
Allow directory of files to be indexed
ENH: Allow directory of files to be indexed In the Data directory, there may be sub-directories of files that need to be kept separate, but all of them need to be indexed.
Python
apache-2.0
zivy/SimpleITK-Notebooks,InsightSoftwareConsortium/SimpleITK-Notebooks,InsightSoftwareConsortium/SimpleITK-Notebooks,zivy/SimpleITK-Notebooks,InsightSoftwareConsortium/SimpleITK-Notebooks,thewtex/SimpleITK-Notebooks,zivy/SimpleITK-Notebooks,thewtex/SimpleITK-Notebooks,thewtex/SimpleITK-Notebooks
--- +++ @@ -8,16 +8,26 @@ import sys import hashlib -def get_md5sums(directory): +def get_relative_filepaths(base_directory): + """ Return a list of file paths without the base_directory prefix""" + file_list = [] + for root, subFolders, files in os.walk('Data'): + relative_path="/".join(root.split('/')[1:]) + for file in files: + file_list.append(os.path.join(relative_path,file)) + return file_list + + +def get_md5sums(base_directory): md5sums = [] - for filename in os.listdir(directory): + for filename in get_relative_filepaths(base_directory): md5 = hashlib.md5() - with open(os.path.join(directory, filename), 'rb') as fp: + full_filepath = os.path.join(base_directory, filename) + with open(full_filepath, 'rb') as fp: for chunk in iter(lambda: fp.read(128 * md5.block_size), b''): md5.update(chunk) md5hash = md5.hexdigest() md5sums.append((filename, md5hash)) - return md5sums if __name__ == '__main__':
cbefb84542d9dfddd0f2fdf8bd0cb2fc89d5b824
jupytext/__init__.py
jupytext/__init__.py
"""Read and write Jupyter notebooks as text files""" from .jupytext import readf, writef, writes, reads from .formats import NOTEBOOK_EXTENSIONS, guess_format, get_format_implementation from .version import __version__ try: from .contentsmanager import TextFileContentsManager except ImportError as err: class TextFileContentsManager: """A class that raises the previous ImportError""" err = err def __init__(self): raise self.err __all__ = ['readf', 'writef', 'writes', 'reads', 'NOTEBOOK_EXTENSIONS', 'guess_format', 'get_format_implementation', 'TextFileContentsManager', '__version__']
"""Read and write Jupyter notebooks as text files""" from .jupytext import readf, writef, writes, reads from .formats import NOTEBOOK_EXTENSIONS, guess_format, get_format_implementation from .version import __version__ try: from .contentsmanager import TextFileContentsManager except ImportError as err: class TextFileContentsManager: """A class that raises the previous ImportError""" err = err def __init__(self): raise self.err def _jupyter_nbextension_paths(): """Allows commands like jupyter nbextension install --py jupytext jupyter nbextension enable --py jupytext jupyter labextension install jupyterlab-jupytext""" return [dict( section="notebook", # the path is relative to the `jupytext` directory src="nbextension", # directory in the `nbextension/` namespace dest="jupytext", # _also_ in the `nbextension/` namespace require="jupytext/index")] __all__ = ['readf', 'writef', 'writes', 'reads', 'NOTEBOOK_EXTENSIONS', 'guess_format', 'get_format_implementation', 'TextFileContentsManager', '__version__']
Allow "jupyter nbextension install/enable --py jupytext"
Allow "jupyter nbextension install/enable --py jupytext"
Python
mit
mwouts/jupytext,mwouts/jupytext,mwouts/jupytext,mwouts/jupytext,mwouts/jupytext,mwouts/jupytext,mwouts/jupytext,mwouts/jupytext,mwouts/jupytext,mwouts/jupytext
--- +++ @@ -14,6 +14,21 @@ def __init__(self): raise self.err +def _jupyter_nbextension_paths(): + """Allows commands like + jupyter nbextension install --py jupytext + jupyter nbextension enable --py jupytext + jupyter labextension install jupyterlab-jupytext""" + return [dict( + section="notebook", + # the path is relative to the `jupytext` directory + src="nbextension", + # directory in the `nbextension/` namespace + dest="jupytext", + # _also_ in the `nbextension/` namespace + require="jupytext/index")] + + __all__ = ['readf', 'writef', 'writes', 'reads', 'NOTEBOOK_EXTENSIONS', 'guess_format', 'get_format_implementation', 'TextFileContentsManager', '__version__']
20d21b851d02bbcf8c6a0f065b9f05f5e0bfc662
geodj/youtube.py
geodj/youtube.py
from gdata.youtube.service import YouTubeService, YouTubeVideoQuery from django.utils.encoding import smart_str import re class YoutubeMusic: def __init__(self): self.service = YouTubeService() def search(self, artist): query = YouTubeVideoQuery() query.vq = artist query.orderby = 'relevance' query.racy = 'exclude' query.categories.append("/Music") feed = self.service.YouTubeQuery(query) results = [] for entry in feed.entry: if not self.is_valid_entry(artist, entry): continue results.append({ 'url': entry.media.player.url, 'title': smart_str(entry.media.title.text), 'duration': int(entry.media.duration.seconds), }) return {'artist': artist, 'results': results} def is_valid_entry(self, artist, entry): duration = int(entry.media.duration.seconds) title = smart_str(entry.media.title.text).lower() if entry.rating is not None and float(entry.rating.average) < 3.5: return False if duration < (2 * 60) or duration > (9 * 60): return False if artist.lower() not in title: return False if re.search("\b(concert|cover)\b", title): return False return True
from gdata.youtube.service import YouTubeService, YouTubeVideoQuery from django.utils.encoding import smart_str import re class YoutubeMusic: def __init__(self): self.service = YouTubeService() def search(self, artist): query = YouTubeVideoQuery() query.vq = artist query.orderby = 'relevance' query.racy = 'exclude' query.format = '5' query.categories.append("/Music") feed = self.service.YouTubeQuery(query) results = [] for entry in feed.entry: if not self.is_valid_entry(artist, entry): continue results.append({ 'url': entry.media.player.url, 'title': smart_str(entry.media.title.text), 'duration': int(entry.media.duration.seconds), }) return {'artist': artist, 'results': results} def is_valid_entry(self, artist, entry): duration = int(entry.media.duration.seconds) title = smart_str(entry.media.title.text).lower() if entry.rating is not None and float(entry.rating.average) < 3.5: return False if duration < (2 * 60) or duration > (9 * 60): return False if artist.lower() not in title: return False if re.search("\b(concert|cover)\b", title): return False return True
Use format=5 in YT search to prevent "embedding disabled"
Use format=5 in YT search to prevent "embedding disabled"
Python
mit
6/GeoDJ,6/GeoDJ
--- +++ @@ -11,6 +11,7 @@ query.vq = artist query.orderby = 'relevance' query.racy = 'exclude' + query.format = '5' query.categories.append("/Music") feed = self.service.YouTubeQuery(query) results = []
1d6bb5e7ce706c8f54599f98744f3a5d62ce104e
src/config.py
src/config.py
import os import ConfigParser as configparser class Config(object): def __init__(self): self.config = configparser.RawConfigParser() self.configfile = os.path.expanduser('~/.mmetering-clirc') if not os.path.isfile(self.configfile): # setup a new config file self.init_file() def init_file(self): self.config.add_section('mmetering') with open(self.configfile, 'a+') as configfile: self.config.write(configfile) def read(self): self.config.read(self.configfile) def write(self): with open(self.configfile, 'wb') as configfile: self.config.write(configfile) def get_base_dir(self): self.read() try: return self.config.get('mmetering', 'base_dir') except configparser.NoOptionError: print 'No base_dir specified in %s' % self.configfile print 'Use mmetering-cli setup' def set_base_dir(self, path): base_dir = os.path.expanduser(path) self.read() self.config.set('mmetering', 'base_dir', base_dir) self.write()
import os import ConfigParser as configparser class Config(object): def __init__(self): self.config = configparser.RawConfigParser() self.configfile = os.path.expanduser('~/.mmetering-clirc') if not os.path.isfile(self.configfile): # setup a new config file self.init_file() def init_file(self): self.config.add_section('mmetering') with open(self.configfile, 'a+') as configfile: self.config.write(configfile) def read(self): self.config.read(self.configfile) def write(self): with open(self.configfile, 'wb') as configfile: self.config.write(configfile) def set(self, section, name, value): val = os.path.expanduser(value) self.read() self.config.set(section, name, val) self.write() def get(self, section, name): self.read() try: return self.config.get(section, name) except configparser.NoOptionError: print 'No %s specified in %s' % (name, self.configfile) print 'Try \'mmetering-cli setup\''
Replace get_base_dir and set_base_dir with more abstract methods get and set
Replace get_base_dir and set_base_dir with more abstract methods get and set
Python
mit
mmetering/mmetering-cli
--- +++ @@ -23,19 +23,18 @@ with open(self.configfile, 'wb') as configfile: self.config.write(configfile) - def get_base_dir(self): + def set(self, section, name, value): + val = os.path.expanduser(value) + + self.read() + self.config.set(section, name, val) + self.write() + + def get(self, section, name): self.read() try: - return self.config.get('mmetering', 'base_dir') + return self.config.get(section, name) except configparser.NoOptionError: - print 'No base_dir specified in %s' % self.configfile - print 'Use mmetering-cli setup' + print 'No %s specified in %s' % (name, self.configfile) + print 'Try \'mmetering-cli setup\'' - def set_base_dir(self, path): - base_dir = os.path.expanduser(path) - - self.read() - self.config.set('mmetering', 'base_dir', base_dir) - - self.write() -
e966ddd804eee2f1b053de6f0bbf943d80dccc59
django_elastipymemcache/client.py
django_elastipymemcache/client.py
from pymemcache.client.hash import HashClient class Client(HashClient): def get_many(self, keys, gets=False, *args, **kwargs): # pymemcache's HashClient may returns {'key': False} end = super(Client, self).get_many(keys, gets, args, kwargs) return {key: end[key] for key in end if end[key]} get_multi = get_many
from pymemcache.client.hash import HashClient class Client(HashClient): def get_many(self, keys, gets=False, *args, **kwargs): # pymemcache's HashClient may returns {'key': False} end = super(Client, self).get_many(keys, gets, args, kwargs) return {key: end.get(key) for key in end if end.get(key)} get_multi = get_many
Fix get value more safe
Fix get value more safe
Python
mit
uncovertruth/django-elastipymemcache
--- +++ @@ -6,6 +6,6 @@ # pymemcache's HashClient may returns {'key': False} end = super(Client, self).get_many(keys, gets, args, kwargs) - return {key: end[key] for key in end if end[key]} + return {key: end.get(key) for key in end if end.get(key)} get_multi = get_many
60daa277d5c3f1d9ab07ff5beccdaa323996068b
feincmstools/templatetags/feincmstools_tags.py
feincmstools/templatetags/feincmstools_tags.py
import os from django import template register = template.Library() @register.filter def is_parent_of(page1, page2): """ Determines whether a given page is the parent of another page Example: {% if page|is_parent_of:feincms_page %} ... {% endif %} """ if page1 is None: return False return (page1.tree_id == page2.tree_id and page1.lft < page2.lft and page1.rght > page2.rght) @register.filter def is_equal_or_parent_of(page1, page2): return (page1.tree_id == page2.tree_id and page1.lft <= page2.lft and page1.rght >= page2.rght) @register.filter def is_sibling_of(page1, page2): """ Determines whether a given page is a sibling of another page {% if page|is_sibling_of:feincms_page %} ... {% endif %} """ if page1 is None or page2 is None: return False return (page1.parent_id == page2.parent_id) @register.filter def get_extension(filename): """ Return the extension from a file name """ return os.path.splitext(filename)[1][1:]
import os from django import template from feincms.templatetags.feincms_tags import feincms_render_content register = template.Library() @register.filter def is_parent_of(page1, page2): """ Determines whether a given page is the parent of another page Example: {% if page|is_parent_of:feincms_page %} ... {% endif %} """ if page1 is None: return False return (page1.tree_id == page2.tree_id and page1.lft < page2.lft and page1.rght > page2.rght) @register.filter def is_equal_or_parent_of(page1, page2): return (page1.tree_id == page2.tree_id and page1.lft <= page2.lft and page1.rght >= page2.rght) @register.filter def is_sibling_of(page1, page2): """ Determines whether a given page is a sibling of another page {% if page|is_sibling_of:feincms_page %} ... {% endif %} """ if page1 is None or page2 is None: return False return (page1.parent_id == page2.parent_id) @register.filter def get_extension(filename): """ Return the extension from a file name """ return os.path.splitext(filename)[1][1:] @register.assignment_tag(takes_context=True) def feincms_render_content_as(context, content, request=None): return feincms_render_content(context, content, request)
Add assignment tag util for rendering chunks to tpl context
Add assignment tag util for rendering chunks to tpl context
Python
bsd-3-clause
ixc/glamkit-feincmstools,ixc/glamkit-feincmstools
--- +++ @@ -1,6 +1,9 @@ import os from django import template + +from feincms.templatetags.feincms_tags import feincms_render_content + register = template.Library() @register.filter @@ -43,3 +46,8 @@ def get_extension(filename): """ Return the extension from a file name """ return os.path.splitext(filename)[1][1:] + + +@register.assignment_tag(takes_context=True) +def feincms_render_content_as(context, content, request=None): + return feincms_render_content(context, content, request)
1e5102d8bafb3b4d2cb07822129397aa56f30bbe
devicecloud/examples/example_helpers.py
devicecloud/examples/example_helpers.py
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. # # Copyright (c) 2015 Digi International, Inc. from getpass import getpass import os from devicecloud import DeviceCloud def get_authenticated_dc(): while True: base_url = os.environ.get('DC_BASE_URL', 'https://login.etherios.com') username = os.environ.get('DC_USERNAME', None) if not username: username = input("username: ") password = os.environ.get('DC_PASSWORD', None) if not password: password = getpass("password: ") dc = DeviceCloud(username, password, base_url=base_url) if dc.has_valid_credentials(): print("Credentials accepted!") return dc else: print("Invalid username or password provided, try again")
# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. # # Copyright (c) 2015 Digi International, Inc. from getpass import getpass import os from six.moves import input from devicecloud import DeviceCloud def get_authenticated_dc(): while True: base_url = os.environ.get('DC_BASE_URL', 'https://login.etherios.com') username = os.environ.get('DC_USERNAME', None) if not username: username = input("username: ") password = os.environ.get('DC_PASSWORD', None) if not password: password = getpass("password: ") dc = DeviceCloud(username, password, base_url=base_url) if dc.has_valid_credentials(): print("Credentials accepted!") return dc else: print("Invalid username or password provided, try again")
Handle using the input function in python 2 for getting username for examples
Handle using the input function in python 2 for getting username for examples Previously this used the builtin input function to get the username. In python 3 this is fine, but if python 2 this is equivalent to eval(raw_input(prompt)) and thus tried to evaluate the username as a variable and typically failed.
Python
mpl-2.0
michaelcho/python-devicecloud,michaelcho/python-devicecloud,digidotcom/python-devicecloud,brucetsao/python-devicecloud,ctrlaltdel/python-devicecloud,digidotcom/python-devicecloud,brucetsao/python-devicecloud,ctrlaltdel/python-devicecloud
--- +++ @@ -5,6 +5,7 @@ # Copyright (c) 2015 Digi International, Inc. from getpass import getpass import os +from six.moves import input from devicecloud import DeviceCloud
4a41b33286cf881f0b3aa09c29a4aaa3568b5259
website/stats/plots/mimp.py
website/stats/plots/mimp.py
from analyses.mimp import glycosylation_sub_types, run_mimp from helpers.plots import stacked_bar_plot from ..store import counter @counter @stacked_bar_plot def gains_and_losses_for_glycosylation_subtypes(): results = {} effects = 'loss', 'gain' for source_name in ['mc3', 'clinvar']: for site_type_name in glycosylation_sub_types: result = run_mimp(source_name, site_type_name, enzyme_type='catch-all') if result.empty: continue effect_counts = result.effect.value_counts() results[source_name] = effects, [effect_counts.get(effect, 0) for effect in effects] return results
from analyses.mimp import glycosylation_sub_types, run_mimp from helpers.plots import stacked_bar_plot from ..store import counter @counter @stacked_bar_plot def gains_and_losses_for_glycosylation_subtypes(): results = {} effects = 'loss', 'gain' for source_name in ['mc3', 'clinvar']: for site_type_name in glycosylation_sub_types: result = run_mimp(source_name, site_type_name, enzyme_type='catch-all') if result.empty: continue effect_counts = result.effect.value_counts() results[source_name] = effects, [ int(effect_counts.get(effect, 0)) for effect in effects ] return results
Convert numpy int to native int for JSON serialization
Convert numpy int to native int for JSON serialization
Python
lgpl-2.1
reimandlab/Visualisation-Framework-for-Genome-Mutations,reimandlab/ActiveDriverDB,reimandlab/ActiveDriverDB,reimandlab/ActiveDriverDB,reimandlab/Visualisation-Framework-for-Genome-Mutations,reimandlab/Visualisation-Framework-for-Genome-Mutations,reimandlab/Visualistion-Framework-for-Genome-Mutations,reimandlab/Visualistion-Framework-for-Genome-Mutations,reimandlab/Visualistion-Framework-for-Genome-Mutations,reimandlab/Visualisation-Framework-for-Genome-Mutations,reimandlab/Visualisation-Framework-for-Genome-Mutations,reimandlab/ActiveDriverDB,reimandlab/Visualistion-Framework-for-Genome-Mutations
--- +++ @@ -15,5 +15,8 @@ if result.empty: continue effect_counts = result.effect.value_counts() - results[source_name] = effects, [effect_counts.get(effect, 0) for effect in effects] + results[source_name] = effects, [ + int(effect_counts.get(effect, 0)) + for effect in effects + ] return results
d7232d855d406a26b2485b5c1fcd587e90fddf39
tests/test_aio.py
tests/test_aio.py
import pytest from ratelimiter import RateLimiter @pytest.mark.asyncio async def test_alock(): rl = RateLimiter(max_calls=10, period=0.01) assert rl._alock is None async with rl: pass alock = rl._alock assert alock async with rl: pass assert rl._alock is alock
import pytest from ratelimiter import RateLimiter @pytest.mark.asyncio async def test_alock(event_loop): rl = RateLimiter(max_calls=10, period=0.01) assert rl._alock is None async with rl: pass alock = rl._alock assert alock async with rl: pass assert rl._alock is alock
Fix Runtime warnings on async tests
Fix Runtime warnings on async tests
Python
apache-2.0
RazerM/ratelimiter
--- +++ @@ -3,7 +3,7 @@ from ratelimiter import RateLimiter @pytest.mark.asyncio -async def test_alock(): +async def test_alock(event_loop): rl = RateLimiter(max_calls=10, period=0.01) assert rl._alock is None
d47d56525f85c5fa8b1f6b817a85479b9eb07582
sqlalchemy_utils/functions/__init__.py
sqlalchemy_utils/functions/__init__.py
from .defer_except import defer_except from .mock import create_mock_engine, mock_engine from .render import render_expression, render_statement from .sort_query import sort_query, QuerySorterException from .database import ( database_exists, create_database, drop_database, escape_like, is_auto_assigned_date_column, is_indexed_foreign_key, non_indexed_foreign_keys, ) from .orm import ( declarative_base, getdotattr, has_changes, identity, naturally_equivalent, primary_keys, table_name, ) __all__ = ( create_database, create_mock_engine, database_exists, declarative_base, defer_except, drop_database, escape_like, getdotattr, has_changes, identity, is_auto_assigned_date_column, is_indexed_foreign_key, mock_engine, naturally_equivalent, non_indexed_foreign_keys, primary_keys, QuerySorterException, render_expression, render_statement, sort_query, table_name, )
from .defer_except import defer_except from .mock import create_mock_engine, mock_engine from .render import render_expression, render_statement from .sort_query import sort_query, QuerySorterException from .database import ( database_exists, create_database, drop_database, escape_like, is_auto_assigned_date_column, is_indexed_foreign_key, non_indexed_foreign_keys, ) from .orm import ( declarative_base, getdotattr, has_changes, identity, naturally_equivalent, query_entities, primary_keys, table_name, ) __all__ = ( create_database, create_mock_engine, database_exists, declarative_base, defer_except, drop_database, escape_like, getdotattr, has_changes, identity, is_auto_assigned_date_column, is_indexed_foreign_key, mock_engine, naturally_equivalent, non_indexed_foreign_keys, primary_keys, QuerySorterException, render_expression, render_statement, sort_query, table_name, )
Add query_entities to functions module import
Add query_entities to functions module import
Python
bsd-3-clause
joshfriend/sqlalchemy-utils,joshfriend/sqlalchemy-utils,cheungpat/sqlalchemy-utils,marrybird/sqlalchemy-utils,rmoorman/sqlalchemy-utils,spoqa/sqlalchemy-utils,tonyseek/sqlalchemy-utils,tonyseek/sqlalchemy-utils,JackWink/sqlalchemy-utils,konstantinoskostis/sqlalchemy-utils
--- +++ @@ -17,6 +17,7 @@ has_changes, identity, naturally_equivalent, + query_entities, primary_keys, table_name, )
244a8ef2d3976970f8647e5fdd3979932cebe6d7
webserver/celery.py
webserver/celery.py
from __future__ import absolute_import import os from celery import Celery from django.conf import settings # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'webserver.settings') app = Celery('webserver') # Using a string here means the worker will not have to # pickle the object when using Windows. app.config_from_object('django.conf:settings') app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) @app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self.request))
from __future__ import absolute_import import os from celery import Celery from django.conf import settings # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'webserver.settings') app = Celery('webserver') # Using a string here means the worker will not have to # pickle the object when using Windows. app.config_from_object('django.conf:settings') app.autodiscover_tasks(lambda: settings.INSTALLED_APPS)
Remove debug task from Celery
Remove debug task from Celery
Python
mit
fengthedroid/heroes-of-the-storm-replay-parser,fengthedroid/heroes-of-the-storm-replay-parser,Oize/heroes-of-the-storm-replay-parser,Oize/heroes-of-the-storm-replay-parser,karlgluck/heroes-of-the-storm-replay-parser,Oize/heroes-of-the-storm-replay-parser
--- +++ @@ -14,7 +14,3 @@ app.config_from_object('django.conf:settings') app.autodiscover_tasks(lambda: settings.INSTALLED_APPS) - -@app.task(bind=True) -def debug_task(self): - print('Request: {0!r}'.format(self.request))
13ec50a7e2187edb03174ed4a9dbf8767f4c6ad4
version.py
version.py
major = 0 minor=0 patch=0 branch="dev" timestamp=1376412824.91
major = 0 minor=0 patch=8 branch="master" timestamp=1376412892.53
Tag commit for v0.0.8-master generated by gitmake.py
Tag commit for v0.0.8-master generated by gitmake.py
Python
mit
ryansturmer/gitmake
--- +++ @@ -1,5 +1,5 @@ major = 0 minor=0 -patch=0 -branch="dev" -timestamp=1376412824.91 +patch=8 +branch="master" +timestamp=1376412892.53
c18884b10f345a8a094a3c4bf589888027d43bd5
examples/django_app/example_app/urls.py
examples/django_app/example_app/urls.py
from django.conf.urls import include, url from django.contrib import admin from example_app.views import ChatterBotAppView, ChatterBotApiView urlpatterns = [ url(r'^$', ChatterBotAppView.as_view(), name='main'), url(r'^admin/', include(admin.site.urls), name='admin'), url(r'^api/chatterbot/', ChatterBotApiView.as_view(), name='chatterbot'), ]
from django.conf.urls import url from django.contrib import admin from example_app.views import ChatterBotAppView, ChatterBotApiView urlpatterns = [ url(r'^$', ChatterBotAppView.as_view(), name='main'), url(r'^admin/', admin.site.urls, name='admin'), url(r'^api/chatterbot/', ChatterBotApiView.as_view(), name='chatterbot'), ]
Remove url inlude for Django 2.0
Remove url inlude for Django 2.0
Python
bsd-3-clause
gunthercox/ChatterBot,vkosuri/ChatterBot
--- +++ @@ -1,10 +1,10 @@ -from django.conf.urls import include, url +from django.conf.urls import url from django.contrib import admin from example_app.views import ChatterBotAppView, ChatterBotApiView urlpatterns = [ url(r'^$', ChatterBotAppView.as_view(), name='main'), - url(r'^admin/', include(admin.site.urls), name='admin'), + url(r'^admin/', admin.site.urls, name='admin'), url(r'^api/chatterbot/', ChatterBotApiView.as_view(), name='chatterbot'), ]
3243f199fb46d2d6f95ae9afd18b1570f9b5f529
astatsscraper/parsing.py
astatsscraper/parsing.py
def parse_app_page(response): # Should always be able to grab a title title = response.xpath('//div[@class = "panel panel-default panel-gameinfo"]/div[@class = "panel-heading"]/text()').extract()[0].strip() # Parse times into floats time_to_hundo = response.xpath('//table[@class = "Default1000"]/tr/td[span = "Hours to 100%"]/text()[last()]').extract()[0].strip() time_to_hundo = time_to_hundo.replace(',', '.') time_to_hundo = float(time_to_hundo) # Points may or may not be present, default to 0 if absent points = response.xpath('//table[@class = "Default1000"]/tr/td[span = "Points"]/text()[last()]').extract() if not points: points = 0 else: points = int(points[0].strip()) yield { 'title': title, 'time to 100%': time_to_hundo, 'points': points, } def parse_search_result_for_apps(response): for href in response.xpath('//table//table//a/@href'): relative_url = href.extract() if relative_url.startswith('Steam_Game_Info.php?AppID='): yield relative_url[:len('Steam_Game_Info.php?AppID=')]
def parse_app_page(response): # Should always be able to grab a title title = response.xpath('//div[@class = "panel panel-default panel-gameinfo"]/div[@class = "panel-heading"]/text()').extract()[0].strip() # Parse times into floats time_to_hundo = response.xpath('//table[@class = "Default1000"]/tr/td[span = "Hours to 100%"]/text()[last()]').extract()[0].strip() time_to_hundo = time_to_hundo.replace(',', '.') time_to_hundo = float(time_to_hundo) # Points may or may not be present, default to 0 if absent points = response.xpath('//table[@class = "Default1000"]/tr/td[span = "Points"]/text()[last()]').extract() if not points: points = 0 else: points = int(points[0].strip()) yield { 'title': title, 'time to 100%': time_to_hundo, 'points': points, } def parse_search_result_for_apps(response): for href in response.xpath('//table//table//a/@href'): relative_url = href.extract() if relative_url.startswith('Steam_Game_Info.php?AppID='): yield { 'app_id' : relative_url[len('Steam_Game_Info.php?AppID='):] }
Fix up bad last commit
Fix up bad last commit
Python
mit
SingingTree/AStatsScraper,SingingTree/AStatsScraper
--- +++ @@ -18,8 +18,11 @@ 'points': points, } + def parse_search_result_for_apps(response): for href in response.xpath('//table//table//a/@href'): relative_url = href.extract() if relative_url.startswith('Steam_Game_Info.php?AppID='): - yield relative_url[:len('Steam_Game_Info.php?AppID=')] + yield { + 'app_id' : relative_url[len('Steam_Game_Info.php?AppID='):] + }
cd41fdbdb53008c9701213d4f223bb8df0514ecb
byceps/util/datetime/timezone.py
byceps/util/datetime/timezone.py
""" byceps.util.datetime.timezone ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Timezone helpers :Copyright: 2006-2021 Jochen Kupperschmidt :License: Revised BSD (see `LICENSE` file for details) """ from datetime import datetime from flask import current_app import pendulum def local_tz_to_utc(dt: datetime): """Convert date/time object from configured default local time to UTC.""" tz_str = get_timezone_string() return (pendulum.instance(dt) .set(tz=tz_str) .in_tz(pendulum.UTC) # Keep SQLAlchemy from converting it to another zone. .replace(tzinfo=None)) def utc_to_local_tz(dt: datetime) -> datetime: """Convert naive date/time object from UTC to configured time zone.""" tz_str = get_timezone_string() return pendulum.instance(dt).in_tz(tz_str) def get_timezone_string() -> str: """Return the configured default timezone as a string.""" return current_app.config['TIMEZONE']
""" byceps.util.datetime.timezone ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Timezone helpers :Copyright: 2006-2021 Jochen Kupperschmidt :License: Revised BSD (see `LICENSE` file for details) """ from flask import current_app def get_timezone_string() -> str: """Return the configured default timezone as a string.""" return current_app.config['TIMEZONE']
Remove unused custom functions `local_tz_to_utc`, `utc_to_local_tz`
Remove unused custom functions `local_tz_to_utc`, `utc_to_local_tz`
Python
bsd-3-clause
homeworkprod/byceps,homeworkprod/byceps,homeworkprod/byceps
--- +++ @@ -8,28 +8,7 @@ :License: Revised BSD (see `LICENSE` file for details) """ -from datetime import datetime - from flask import current_app -import pendulum - - - -def local_tz_to_utc(dt: datetime): - """Convert date/time object from configured default local time to UTC.""" - tz_str = get_timezone_string() - - return (pendulum.instance(dt) - .set(tz=tz_str) - .in_tz(pendulum.UTC) - # Keep SQLAlchemy from converting it to another zone. - .replace(tzinfo=None)) - - -def utc_to_local_tz(dt: datetime) -> datetime: - """Convert naive date/time object from UTC to configured time zone.""" - tz_str = get_timezone_string() - return pendulum.instance(dt).in_tz(tz_str) def get_timezone_string() -> str:
61fdbe0dba79dc19cda5320a0ad1352facf12d3d
twine/__init__.py
twine/__init__.py
# Copyright 2018 Donald Stufft and individual contributors # # 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. __all__ = ( "__title__", "__summary__", "__uri__", "__version__", "__author__", "__email__", "__license__", "__copyright__", ) __copyright__ = "Copyright 2019 Donald Stufft and individual contributors" try: import importlib.metadata as importlib_metadata except ImportError: import importlib_metadata metadata = importlib_metadata.metadata('twine') __title__ = metadata['name'] __summary__ = metadata['summary'] __uri__ = metadata['home-page'] __version__ = metadata['version'] __author__ = metadata['author'] __email__ = metadata['author-email'] __license__ = metadata['license']
# Copyright 2018 Donald Stufft and individual contributors # # 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. __all__ = ( "__title__", "__summary__", "__uri__", "__version__", "__author__", "__email__", "__license__", "__copyright__", ) __copyright__ = "Copyright 2019 Donald Stufft and individual contributors" try: # https://github.com/python/mypy/issues/1393 from importlib.metadata import metadata # type: ignore except ImportError: # https://github.com/python/mypy/issues/1153 from importlib_metadata import metadata # type: ignore twine_metadata = metadata('twine') __title__ = twine_metadata['name'] __summary__ = twine_metadata['summary'] __uri__ = twine_metadata['home-page'] __version__ = twine_metadata['version'] __author__ = twine_metadata['author'] __email__ = twine_metadata['author-email'] __license__ = twine_metadata['license']
Rework imports and ignore known mypy issues
Rework imports and ignore known mypy issues
Python
apache-2.0
pypa/twine
--- +++ @@ -18,19 +18,22 @@ __copyright__ = "Copyright 2019 Donald Stufft and individual contributors" + try: - import importlib.metadata as importlib_metadata + # https://github.com/python/mypy/issues/1393 + from importlib.metadata import metadata # type: ignore except ImportError: - import importlib_metadata + # https://github.com/python/mypy/issues/1153 + from importlib_metadata import metadata # type: ignore -metadata = importlib_metadata.metadata('twine') +twine_metadata = metadata('twine') -__title__ = metadata['name'] -__summary__ = metadata['summary'] -__uri__ = metadata['home-page'] -__version__ = metadata['version'] -__author__ = metadata['author'] -__email__ = metadata['author-email'] -__license__ = metadata['license'] +__title__ = twine_metadata['name'] +__summary__ = twine_metadata['summary'] +__uri__ = twine_metadata['home-page'] +__version__ = twine_metadata['version'] +__author__ = twine_metadata['author'] +__email__ = twine_metadata['author-email'] +__license__ = twine_metadata['license']
1bc4507234d87b1ed246501165fa1d8138bf5ca6
cheddar/exceptions.py
cheddar/exceptions.py
""" Shared exception. """ class BadRequestError(Exception): pass class ConflictError(Exception): pass class NotFoundError(Exception): def __init__(self, status_code=None): self.status_code = status_code
""" Shared exception. """ class BadRequestError(Exception): pass class ConflictError(Exception): pass class NotFoundError(Exception): def __init__(self, status_code=None): super(NotFoundError, self).__init__() self.status_code = status_code
Fix for pypy compatibility: must super's __init__
Fix for pypy compatibility: must super's __init__
Python
apache-2.0
jessemyers/cheddar,jessemyers/cheddar
--- +++ @@ -14,5 +14,6 @@ class NotFoundError(Exception): def __init__(self, status_code=None): + super(NotFoundError, self).__init__() self.status_code = status_code
ac9cd5ff007ee131e97f70c49c763f79f06ebf5a
green/test/test_integration.py
green/test/test_integration.py
import multiprocessing import os from pathlib import PurePath import subprocess import sys import tempfile from textwrap import dedent import unittest try: from unittest.mock import MagicMock except: from mock import MagicMock from green import cmdline class TestFinalizer(unittest.TestCase): def setUp(self): self.tmpdir = tempfile.mkdtemp() def test_finalizer(self): """ Test that the finalizer works on Python 3.8+ """ sub_tmpdir = tempfile.mkdtemp(dir=self.tmpdir) for i in range(multiprocessing.cpu_count() * 2): fh = open(os.path.join(sub_tmpdir, f"test_finalizer{i}.py"), "w") fh.write( dedent( f""" import unittest class Pass{i}(unittest.TestCase): def test_pass{i}(self): pass def msg(): print("finalizer worked") """ ) ) fh.close() args = [ sys.executable, "-m", "green.cmdline", "--finalizer=test_finalizer0.msg", "--maxtasksperchild=1", ] pythonpath = str(PurePath(__file__).parent.parent.parent) output = subprocess.run( args, cwd=sub_tmpdir, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, env={"PYTHONPATH": pythonpath}, timeout=10, ).stdout.decode("utf-8") self.assertIn("finalizer worked", output)
import copy import multiprocessing import os from pathlib import PurePath import subprocess import sys import tempfile from textwrap import dedent import unittest try: from unittest.mock import MagicMock except: from mock import MagicMock from green import cmdline class TestFinalizer(unittest.TestCase): def setUp(self): self.tmpdir = tempfile.mkdtemp() def test_finalizer(self): """ Test that the finalizer works on Python 3.8+ """ sub_tmpdir = tempfile.mkdtemp(dir=self.tmpdir) for i in range(multiprocessing.cpu_count() * 2): fh = open(os.path.join(sub_tmpdir, f"test_finalizer{i}.py"), "w") fh.write( dedent( f""" import unittest class Pass{i}(unittest.TestCase): def test_pass{i}(self): pass def msg(): print("finalizer worked") """ ) ) fh.close() args = [ sys.executable, "-m", "green.cmdline", "--finalizer=test_finalizer0.msg", "--maxtasksperchild=1", ] pythonpath = str(PurePath(__file__).parent.parent.parent) env = copy.deepcopy(os.environ) env["PYTHONPATH"] = pythonpath output = subprocess.run( args, cwd=sub_tmpdir, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, env=env, timeout=10, ).stdout.decode("utf-8") self.assertIn("finalizer worked", output)
Include the entire existing environment for integration tests subprocesses
Include the entire existing environment for integration tests subprocesses
Python
mit
CleanCut/green,CleanCut/green
--- +++ @@ -1,3 +1,4 @@ +import copy import multiprocessing import os from pathlib import PurePath @@ -48,12 +49,15 @@ ] pythonpath = str(PurePath(__file__).parent.parent.parent) + env = copy.deepcopy(os.environ) + env["PYTHONPATH"] = pythonpath + output = subprocess.run( args, cwd=sub_tmpdir, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, - env={"PYTHONPATH": pythonpath}, + env=env, timeout=10, ).stdout.decode("utf-8") self.assertIn("finalizer worked", output)
290a1f7a2c6860ec57bdb74b9c97207e93e611f0
visualize_data.py
visualize_data.py
from __future__ import division import argparse import cv2 import h5py import util def main(): parser = argparse.ArgumentParser() parser.add_argument('hdf5_fname', type=str) parser.add_argument('--vis_scale', '-r', type=int, default=10, metavar='R', help='rescale image by R for visualization') args = parser.parse_args() with h5py.File(args.hdf5_fname, 'r') as hdf5_file: for image_curr, vel, image_diff in zip(hdf5_file['image_curr'], hdf5_file['vel'], hdf5_file['image_diff']): image_next = image_curr + image_diff vis_image, done = util.visualize_images_callback(image_curr, image_next, vis_scale=args.vis_scale, delay=0) if done: break cv2.destroyAllWindows() if __name__ == "__main__": main()
from __future__ import division import argparse import cv2 import h5py import util def main(): parser = argparse.ArgumentParser() parser.add_argument('hdf5_fname', type=str) parser.add_argument('--vis_scale', '-r', type=int, default=10, metavar='R', help='rescale image by R for visualization') parser.add_argument('--reverse', action='store_true') args = parser.parse_args() with h5py.File(args.hdf5_fname, 'r') as hdf5_file: dsets = (hdf5_file['image_curr'], hdf5_file['vel'], hdf5_file['image_diff']) if args.reverse: dsets = tuple(dset[()][::-1] for dset in dsets) for image_curr, vel, image_diff in zip(*dsets): image_next = image_curr + image_diff vis_image, done = util.visualize_images_callback(image_curr, image_next, vis_scale=args.vis_scale, delay=0) if done: break cv2.destroyAllWindows() if __name__ == "__main__": main()
Add option to visualize data in reverse
Add option to visualize data in reverse
Python
mit
alexlee-gk/visual_dynamics
--- +++ @@ -9,11 +9,15 @@ parser = argparse.ArgumentParser() parser.add_argument('hdf5_fname', type=str) parser.add_argument('--vis_scale', '-r', type=int, default=10, metavar='R', help='rescale image by R for visualization') + parser.add_argument('--reverse', action='store_true') args = parser.parse_args() with h5py.File(args.hdf5_fname, 'r') as hdf5_file: - for image_curr, vel, image_diff in zip(hdf5_file['image_curr'], hdf5_file['vel'], hdf5_file['image_diff']): + dsets = (hdf5_file['image_curr'], hdf5_file['vel'], hdf5_file['image_diff']) + if args.reverse: + dsets = tuple(dset[()][::-1] for dset in dsets) + for image_curr, vel, image_diff in zip(*dsets): image_next = image_curr + image_diff vis_image, done = util.visualize_images_callback(image_curr, image_next, vis_scale=args.vis_scale, delay=0) if done:
bf6d6cdaf946af7ce8d1aa6831e7da9b47fef54f
user_deletion/managers.py
user_deletion/managers.py
from dateutil.relativedelta import relativedelta from django.utils import timezone class UserDeletionManagerMixin: def users_to_notify(self): """Finds all users who have been inactive and not yet notified.""" from django.apps import apps user_deletion_config = apps.get_app_config('user_deletion') threshold = timezone.now() - relativedelta( months=user_deletion_config.MONTH_NOTIFICATION, ) return self.filter(last_login__lte=threshold, notified=False) def users_to_delete(self): """Finds all users who have been inactive and were notified.""" from django.apps import apps user_deletion_config = apps.get_app_config('user_deletion') threshold = timezone.now() - relativedelta( months=user_deletion_config.MONTH_DELETION, ) return self.filter(last_login__lte=threshold, notified=True)
from dateutil.relativedelta import relativedelta from django.apps import apps from django.utils import timezone class UserDeletionManagerMixin: def users_to_notify(self): """Finds all users who have been inactive and not yet notified.""" user_deletion_config = apps.get_app_config('user_deletion') threshold = timezone.now() - relativedelta( months=user_deletion_config.MONTH_NOTIFICATION, ) return self.filter(last_login__lte=threshold, notified=False) def users_to_delete(self): """Finds all users who have been inactive and were notified.""" user_deletion_config = apps.get_app_config('user_deletion') threshold = timezone.now() - relativedelta( months=user_deletion_config.MONTH_DELETION, ) return self.filter(last_login__lte=threshold, notified=True)
Put import back on top
Put import back on top
Python
bsd-2-clause
incuna/django-user-deletion
--- +++ @@ -1,12 +1,11 @@ from dateutil.relativedelta import relativedelta +from django.apps import apps from django.utils import timezone class UserDeletionManagerMixin: def users_to_notify(self): """Finds all users who have been inactive and not yet notified.""" - from django.apps import apps - user_deletion_config = apps.get_app_config('user_deletion') threshold = timezone.now() - relativedelta( @@ -16,8 +15,6 @@ def users_to_delete(self): """Finds all users who have been inactive and were notified.""" - from django.apps import apps - user_deletion_config = apps.get_app_config('user_deletion') threshold = timezone.now() - relativedelta(
6a767780253ef981e78b00bb9937e9aaa0f9d1b8
motobot/core_plugins/network_handlers.py
motobot/core_plugins/network_handlers.py
from motobot import hook from time import sleep @hook('PING') def handle_ping(bot, context, message): """ Handle the server's pings. """ bot.send('PONG :' + message.params[-1]) @hook('439') def handle_wait(bot, context, message): """ Handles too fast for server message and waits 1 second. """ bot.identified = False sleep(1) @hook('NOTICE') def handle_identification(bot, context, message): """ Use the notice message to identify and register to the server. """ if not bot.identified: bot.send('USER MotoBot localhost localhost MotoBot') bot.send('NICK ' + bot.nick) bot.identified = True @hook('002') def handle_nickserv_identification(bot, context, message): """ At server welcome message 004 identify to nickserv and join channels. """ if bot.nickserv_password is not None: bot.send('PRIVMSG nickserv :identify ' + bot.nickserv_password) @hook('ERROR') def handle_error(bot, context, message): """ Handle an error message from the server. """ bot.connected = bot.identified = False
from motobot import hook from time import sleep @hook('PING') def handle_ping(bot, context, message): """ Handle the server's pings. """ bot.send('PONG :' + message.params[-1]) @hook('439') def handle_wait(bot, context, message): """ Handles too fast for server message and waits 1 second. """ bot.identified = False sleep(1) @hook('NOTICE') def handle_identification(bot, context, message): """ Use the notice message to identify and register to the server. """ if not bot.identified: bot.send('USER MotoBot localhost localhost MotoBot') bot.send('NICK ' + bot.nick) bot.identified = True @hook('002') def handle_nickserv_identification(bot, context, message): """ At server welcome message 004 identify to nickserv and join channels. """ if bot.nickserv_password is not None: bot.send('PRIVMSG nickserv :identify ' + bot.nickserv_password) sleep(1) @hook('ERROR') def handle_error(bot, context, message): """ Handle an error message from the server. """ bot.connected = bot.identified = False
Add sleep after nickserv identify
Add sleep after nickserv identify
Python
mit
Motoko11/MotoBot
--- +++ @@ -29,6 +29,7 @@ """ At server welcome message 004 identify to nickserv and join channels. """ if bot.nickserv_password is not None: bot.send('PRIVMSG nickserv :identify ' + bot.nickserv_password) + sleep(1) @hook('ERROR')
c2d3c2c471dfb504626509a34256eb2d9898cfa2
rest_framework_nested/viewsets.py
rest_framework_nested/viewsets.py
class NestedViewSetMixin(object): def get_queryset(self): """ Filter the `QuerySet` based on its parents as defined in the `serializer_class.parent_lookup_kwargs`. """ queryset = super(NestedViewSetMixin, self).get_queryset() if hasattr(self.serializer_class, 'parent_lookup_kwargs'): orm_filters = {} for query_param, field_name in self.serializer_class.parent_lookup_kwargs.items(): orm_filters[field_name] = self.kwargs[query_param] return queryset.filter(**orm_filters) return queryset
class NestedViewSetMixin(object): def get_queryset(self): """ Filter the `QuerySet` based on its parents as defined in the `serializer_class.parent_lookup_kwargs`. """ queryset = super(NestedViewSetMixin, self).get_queryset() serializer_class = self.get_serializer_class() if hasattr(serializer_class, 'parent_lookup_kwargs'): orm_filters = {} for query_param, field_name in serializer_class.parent_lookup_kwargs.items(): orm_filters[field_name] = self.kwargs[query_param] return queryset.filter(**orm_filters) return queryset
Fix to use get_serializer_class method instead of serializer_class
Fix to use get_serializer_class method instead of serializer_class
Python
apache-2.0
alanjds/drf-nested-routers
--- +++ @@ -5,9 +5,10 @@ `serializer_class.parent_lookup_kwargs`. """ queryset = super(NestedViewSetMixin, self).get_queryset() - if hasattr(self.serializer_class, 'parent_lookup_kwargs'): + serializer_class = self.get_serializer_class() + if hasattr(serializer_class, 'parent_lookup_kwargs'): orm_filters = {} - for query_param, field_name in self.serializer_class.parent_lookup_kwargs.items(): + for query_param, field_name in serializer_class.parent_lookup_kwargs.items(): orm_filters[field_name] = self.kwargs[query_param] return queryset.filter(**orm_filters) return queryset
3b7328dd7d9d235bf32b3cfb836b49e50b70be77
oz/plugins/redis_sessions/__init__.py
oz/plugins/redis_sessions/__init__.py
from __future__ import absolute_import, division, print_function, with_statement, unicode_literals import os import binascii import hashlib import oz.app from .middleware import * from .options import * from .tests import * def random_hex(length): """Generates a random hex string""" return binascii.hexlify(os.urandom(length))[length:] def password_hash(password, password_salt=None): """Hashes a specified password""" password_salt = password_salt or oz.app.settings["session_salt"] return u"sha256!%s" % hashlib.sha256(unicode(password_salt) + unicode(password)).hexdigest()
from __future__ import absolute_import, division, print_function, with_statement, unicode_literals import os import binascii import hashlib import oz.app from .middleware import * from .options import * from .tests import * def random_hex(length): """Generates a random hex string""" return binascii.hexlify(os.urandom(length))[length:] def password_hash(password, password_salt=None): """Hashes a specified password""" password_salt = password_salt or oz.app.settings["session_salt"] salted_password = "".join([unicode(password_salt), password]) return "sha256!%s" % unicode(hashlib.sha256(salted_password.encode("utf-8")).hexdigest())
Allow for non-ascii characters in password_hash
Allow for non-ascii characters in password_hash
Python
bsd-3-clause
dailymuse/oz,dailymuse/oz,dailymuse/oz
--- +++ @@ -16,4 +16,5 @@ def password_hash(password, password_salt=None): """Hashes a specified password""" password_salt = password_salt or oz.app.settings["session_salt"] - return u"sha256!%s" % hashlib.sha256(unicode(password_salt) + unicode(password)).hexdigest() + salted_password = "".join([unicode(password_salt), password]) + return "sha256!%s" % unicode(hashlib.sha256(salted_password.encode("utf-8")).hexdigest())
442f21bfde16f72d4480fa7fd9dea2eac741a857
src/analyses/views.py
src/analyses/views.py
from django.contrib import messages from django.contrib.auth import get_user_model from django.contrib.auth.mixins import LoginRequiredMixin from django.utils.translation import ugettext_lazy as _ from django.views.generic import CreateView, TemplateView from .forms import AbstractAnalysisCreateForm from .pipelines import AVAILABLE_PIPELINES User = get_user_model() class SelectNewAnalysisTypeView(LoginRequiredMixin, TemplateView): template_name = "analyses/new_analysis_by_type.html" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['available_pipelines'] = AVAILABLE_PIPELINES return context class AbstractAnalysisFormView(LoginRequiredMixin, CreateView): form_class = AbstractAnalysisCreateForm template_name = None analysis_type = 'AbstractAnalysis' analysis_description = '' analysis_create_url = None def get_form_kwargs(self): """Pass request object for form creation""" kwargs = super().get_form_kwargs() kwargs['request'] = self.request return kwargs def form_valid(self, form): response = super().form_valid(form) messages.add_message( self.request, messages.INFO, _('You just created a %(analysis_type)s analysis!') % { 'analysis_type': self.analysis_type } ) return response
from django.contrib import messages from django.contrib.auth import get_user_model from django.contrib.auth.mixins import LoginRequiredMixin from django.utils.translation import ugettext_lazy as _ from django.views.generic import CreateView, TemplateView from .forms import AbstractAnalysisCreateForm from .pipelines import AVAILABLE_PIPELINES User = get_user_model() class SelectNewAnalysisTypeView(LoginRequiredMixin, TemplateView): template_name = "analyses/new_analysis_by_type.html" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['available_pipelines'] = AVAILABLE_PIPELINES return context class AbstractAnalysisFormView(LoginRequiredMixin, CreateView): form_class = AbstractAnalysisCreateForm template_name = None analysis_type = 'AbstractAnalysis' analysis_description = '' analysis_create_url = None def get_form_kwargs(self): """Pass request object for form creation""" kwargs = super().get_form_kwargs() kwargs['request'] = self.request return kwargs def form_valid(self, form): response = super().form_valid(form) messages.add_message( self.request, messages.INFO, _( 'You just created a %(analysis_type)s analysis! ' 'View its detail <a href="%(analysis_detail_url)s">here</a>.' ) % { 'analysis_type': self.analysis_type, 'analysis_detail_url': self.object.get_absolute_url(), }, extra_tags='safe', ) return response
Include analysis detail view URL in message
Include analysis detail view URL in message
Python
mit
ccwang002/biocloud-server-kai,ccwang002/biocloud-server-kai,ccwang002/biocloud-server-kai
--- +++ @@ -40,8 +40,13 @@ response = super().form_valid(form) messages.add_message( self.request, messages.INFO, - _('You just created a %(analysis_type)s analysis!') % { - 'analysis_type': self.analysis_type - } + _( + 'You just created a %(analysis_type)s analysis! ' + 'View its detail <a href="%(analysis_detail_url)s">here</a>.' + ) % { + 'analysis_type': self.analysis_type, + 'analysis_detail_url': self.object.get_absolute_url(), + }, + extra_tags='safe', ) return response
2bc95d90db15160f9c4869c03f9dadb6cd8d56fa
seleniumbase/config/proxy_list.py
seleniumbase/config/proxy_list.py
""" Proxy Server "Phone Book". Simplify running browser tests through a proxy server by adding your frequently-used proxies here. Now you can do something like this on the command line: "pytest SOME_TEST.py --proxy=proxy1" Format of PROXY_LIST server entries: * "ip_address:port" OR "username:password@ip_address:port" * "server:port" OR "username:password@server:port" (Do NOT include the http:// or https:// in your proxy string!) Example proxies in PROXY_LIST below are not guaranteed to be active or secure. If you don't already have a proxy server to connect to, you can try finding one from one of following sites: * https://www.us-proxy.org/ """ PROXY_LIST = { "example1": "159.122.164.163:8080", # (Example) - set your own proxy here "proxy1": None, "proxy2": None, "proxy3": None, "proxy4": None, "proxy5": None, }
""" Proxy Server "Phone Book". Simplify running browser tests through a proxy server by adding your frequently-used proxies here. Now you can do something like this on the command line: "pytest SOME_TEST.py --proxy=proxy1" Format of PROXY_LIST server entries: * "ip_address:port" OR "username:password@ip_address:port" * "server:port" OR "username:password@server:port" (Do NOT include the http:// or https:// in your proxy string!) Example proxies in PROXY_LIST below are not guaranteed to be active or secure. If you don't already have a proxy server to connect to, you can try finding one from one of following sites: * https://www.us-proxy.org/ """ PROXY_LIST = { "example1": "159.122.164.163:8080", # (Example) - set your own proxy here "example2": "158.69.138.8:1080", # (Example) - set your own proxy here "proxy1": None, "proxy2": None, "proxy3": None, "proxy4": None, "proxy5": None, }
Add another proxy server example string
Add another proxy server example string
Python
mit
seleniumbase/SeleniumBase,seleniumbase/SeleniumBase,mdmintz/SeleniumBase,seleniumbase/SeleniumBase,seleniumbase/SeleniumBase,mdmintz/SeleniumBase,mdmintz/SeleniumBase,mdmintz/SeleniumBase
--- +++ @@ -20,6 +20,7 @@ PROXY_LIST = { "example1": "159.122.164.163:8080", # (Example) - set your own proxy here + "example2": "158.69.138.8:1080", # (Example) - set your own proxy here "proxy1": None, "proxy2": None, "proxy3": None,
1a15a08abd7c7b5313402be4574ca6811044fd75
launch_control/models/hw_device.py
launch_control/models/hw_device.py
""" Module with the HardwareDevice model. """ from launch_control.utils.json import PlainOldData class HardwareDevice(PlainOldData): """ Model representing any HardwareDevice A device is just a "device_type" attribute with a bag of properties and a human readable description. Individual device types can be freely added. For simplicity some common types of devices are provided as class properties DEVICE_xxx. Instances will come from a variety of factory classes, each capable of enumerating devices that it understands. The upside of having a common class like this is that it's easier to store it in the database _and_ not have to agree on a common set of properties for, say, all CPUs. If you want you can create instances manually, like this: >>> cpu = HardwareDevice(HardwareDevice.DEVICE_CPU) >>> cpu.desc = "800MHz OMAP3 Processor" >>> cpu.attributes['machine'] = 'arm' >>> cpu.attributes['mhz'] = 800 >>> cpu.attributes['vendor'] = 'Texas Instruments' """ DEVICE_CPU = "device.cpu" DEVICE_MEM = "device.mem" DEVICE_USB = "device.usb" DEVICE_PCI = "device.pci" DEVICE_BOARD = "device.board" __slots__ = ('device_type', 'desc', 'attributes') def __init__(self, device_type, desc, attributes=None): self.device_type = device_type self.description = description self.attributes = attributes or {}
""" Module with the HardwareDevice model. """ from launch_control.utils.json import PlainOldData class HardwareDevice(PlainOldData): """ Model representing any HardwareDevice A device is just a "device_type" attribute with a bag of properties and a human readable description. Individual device types can be freely added. For simplicity some common types of devices are provided as class properties DEVICE_xxx. Instances will come from a variety of factory classes, each capable of enumerating devices that it understands. The upside of having a common class like this is that it's easier to store it in the database _and_ not have to agree on a common set of properties for, say, all CPUs. If you want you can create instances manually, like this: >>> cpu = HardwareDevice(HardwareDevice.DEVICE_CPU) >>> cpu.desc = "800MHz OMAP3 Processor" >>> cpu.attributes['machine'] = 'arm' >>> cpu.attributes['mhz'] = 800 >>> cpu.attributes['vendor'] = 'Texas Instruments' """ DEVICE_CPU = "device.cpu" DEVICE_MEM = "device.mem" DEVICE_USB = "device.usb" DEVICE_PCI = "device.pci" DEVICE_BOARD = "device.board" __slots__ = ('device_type', 'desc', 'attributes') def __init__(self, device_type, description, attributes=None): self.device_type = device_type self.description = description self.attributes = attributes or {}
Fix HardwareDevice constructor to provide 'description' argument
Fix HardwareDevice constructor to provide 'description' argument
Python
agpl-3.0
Linaro/lava-server,Linaro/lava-server,OSSystems/lava-server,Linaro/lava-server,Linaro/lava-server,OSSystems/lava-server,OSSystems/lava-server
--- +++ @@ -36,7 +36,7 @@ __slots__ = ('device_type', 'desc', 'attributes') - def __init__(self, device_type, desc, attributes=None): + def __init__(self, device_type, description, attributes=None): self.device_type = device_type self.description = description self.attributes = attributes or {}
8fff587b9fd7e2cd0ca4d45e869345cbfb248045
troposphere/workspaces.py
troposphere/workspaces.py
# Copyright (c) 2015, Mark Peek <mark@peek.org> # All rights reserved. # # See LICENSE file for full license. from . import AWSObject class Workspace(AWSObject): resource_type = "AWS::WorkSpaces::Workspace" props = { 'BundleId': (basestring, True), 'DirectoryId': (basestring, True), 'UserName': (basestring, True), }
# Copyright (c) 2015, Mark Peek <mark@peek.org> # All rights reserved. # # See LICENSE file for full license. from . import AWSObject from .validators import boolean class Workspace(AWSObject): resource_type = "AWS::WorkSpaces::Workspace" props = { 'BundleId': (basestring, True), 'DirectoryId': (basestring, True), 'UserName': (basestring, True), 'RootVolumeEncryptionEnabled': (boolean, False), 'UserVolumeEncryptionEnabled': (boolean, False), 'VolumeEncryptionKey': (basestring, False), }
Add encryption properties to Workspace
Add encryption properties to Workspace
Python
bsd-2-clause
7digital/troposphere,dmm92/troposphere,horacio3/troposphere,ikben/troposphere,alonsodomin/troposphere,pas256/troposphere,cloudtools/troposphere,dmm92/troposphere,ikben/troposphere,Yipit/troposphere,cloudtools/troposphere,johnctitus/troposphere,amosshapira/troposphere,johnctitus/troposphere,pas256/troposphere,alonsodomin/troposphere,7digital/troposphere,craigbruce/troposphere,horacio3/troposphere
--- +++ @@ -4,6 +4,7 @@ # See LICENSE file for full license. from . import AWSObject +from .validators import boolean class Workspace(AWSObject): @@ -13,4 +14,7 @@ 'BundleId': (basestring, True), 'DirectoryId': (basestring, True), 'UserName': (basestring, True), + 'RootVolumeEncryptionEnabled': (boolean, False), + 'UserVolumeEncryptionEnabled': (boolean, False), + 'VolumeEncryptionKey': (basestring, False), }
b4e106271f96b083644b27d313ad80c240fcb0a5
gapipy/resources/booking/booking.py
gapipy/resources/booking/booking.py
# Python 2 and 3 from __future__ import unicode_literals from gapipy.resources.checkin import Checkin from ..base import Resource from .transaction import Payment, Refund from .document import Invoice, Document from .override import Override from .service import Service class Booking(Resource): _resource_name = 'bookings' _is_parent_resource = True _as_is_fields = ['id', 'href', 'external_id', 'currency'] _price_fields = [ 'amount_owing', 'amount_paid', 'amount_pending', 'commission', 'tax_on_commission', ] _date_fields = [ 'date_closed', 'date_of_first_travel', 'date_of_last_travel', 'balance_due_date', ] _date_time_fields_utc = ['date_created', ] _resource_fields = [ ('agent', 'Agent'), ('agency', 'Agency'), ('associated_agency', 'Agency'), ] @property def _resource_collection_fields(self): return [ ('services', Service), ('invoices', Invoice), ('payments', Payment), ('refunds', Refund), ('documents', Document), ('overrides', Override), ('checkins', Checkin), ]
# Python 2 and 3 from __future__ import unicode_literals from gapipy.resources.checkin import Checkin from ..base import Resource from .agency_chain import AgencyChain from .document import Invoice, Document from .override import Override from .service import Service from .transaction import Payment, Refund class Booking(Resource): _resource_name = 'bookings' _is_parent_resource = True _as_is_fields = ['id', 'href', 'external_id', 'currency'] _price_fields = [ 'amount_owing', 'amount_paid', 'amount_pending', 'commission', 'tax_on_commission', ] _date_fields = [ 'date_closed', 'date_of_first_travel', 'date_of_last_travel', 'balance_due_date', ] _date_time_fields_utc = ['date_created', ] _resource_fields = [ ('agency', 'Agency'), ('agency_chain', AgencyChain), ('agent', 'Agent'), ('associated_agency', 'Agency'), ] @property def _resource_collection_fields(self): return [ ('services', Service), ('invoices', Invoice), ('payments', Payment), ('refunds', Refund), ('documents', Document), ('overrides', Override), ('checkins', Checkin), ]
Add agency chain to Booking
Add agency chain to Booking
Python
mit
gadventures/gapipy
--- +++ @@ -4,10 +4,11 @@ from gapipy.resources.checkin import Checkin from ..base import Resource -from .transaction import Payment, Refund +from .agency_chain import AgencyChain from .document import Invoice, Document from .override import Override from .service import Service +from .transaction import Payment, Refund class Booking(Resource): @@ -28,8 +29,9 @@ ] _date_time_fields_utc = ['date_created', ] _resource_fields = [ + ('agency', 'Agency'), + ('agency_chain', AgencyChain), ('agent', 'Agent'), - ('agency', 'Agency'), ('associated_agency', 'Agency'), ]
8ba94b216531f249a7097f10eb74f363af6151e2
xmlrpc2/client.py
xmlrpc2/client.py
from __future__ import absolute_import from __future__ import division from __future__ import unicode_literals import urllib.parse class BaseTransport(object): @property def scheme(self): raise NotImplementedError("Transports must have a scheme") class HTTPTransport(BaseTransport): scheme = "http" class Client(object): def __init__(self, uri, transports=None): if transports is None: transports = [HTTPTransport] # Initialize transports self.transports = {} for transport in transports: t = transport() self.transports[t.scheme] = t parsed = urllib.parse.urlparse(uri) if parsed.scheme not in self.transports: raise ValueError("Invalid uri scheme {scheme}. Must be one of {available}.".format(scheme=parsed.scheme, available=",".join(self.transports))) self.transport = self.transports[parsed.scheme] # Default to /RPC2 for path as it is a common endpoint if not parsed.path: parsed = parsed[:2] + ("/RPC2",) + parsed[3:] self.uri = urllib.parse.urlunparse(parsed)
from __future__ import absolute_import from __future__ import division from __future__ import unicode_literals import urllib.parse class BaseTransport(object): @property def scheme(self): raise NotImplementedError("Transports must have a scheme") class HTTPTransport(BaseTransport): scheme = "http" class Client(object): def __init__(self, uri, transports=None): if transports is None: transports = [HTTPTransport] # Initialize transports self._transports = {} for transport in transports: t = transport() self._transports[t.scheme] = t parsed = urllib.parse.urlparse(uri) if parsed.scheme not in self._transports: raise ValueError("Invalid uri scheme {scheme}. Must be one of {available}.".format(scheme=parsed.scheme, available=",".join(self._transports))) self._transport = self._transports[parsed.scheme] # Default to /RPC2 for path as it is a common endpoint if not parsed.path: parsed = parsed[:2] + ("/RPC2",) + parsed[3:] self._uri = urllib.parse.urlunparse(parsed)
Rename internal variables to start with a _
Rename internal variables to start with a _
Python
bsd-2-clause
dstufft/xmlrpc2
--- +++ @@ -24,20 +24,20 @@ transports = [HTTPTransport] # Initialize transports - self.transports = {} + self._transports = {} for transport in transports: t = transport() - self.transports[t.scheme] = t + self._transports[t.scheme] = t parsed = urllib.parse.urlparse(uri) - if parsed.scheme not in self.transports: - raise ValueError("Invalid uri scheme {scheme}. Must be one of {available}.".format(scheme=parsed.scheme, available=",".join(self.transports))) + if parsed.scheme not in self._transports: + raise ValueError("Invalid uri scheme {scheme}. Must be one of {available}.".format(scheme=parsed.scheme, available=",".join(self._transports))) - self.transport = self.transports[parsed.scheme] + self._transport = self._transports[parsed.scheme] # Default to /RPC2 for path as it is a common endpoint if not parsed.path: parsed = parsed[:2] + ("/RPC2",) + parsed[3:] - self.uri = urllib.parse.urlunparse(parsed) + self._uri = urllib.parse.urlunparse(parsed)
e64195a005be583f32754e49e870b198ee7bc396
corehq/pillows/mappings/case_search_mapping.py
corehq/pillows/mappings/case_search_mapping.py
from corehq.pillows.mappings.case_mapping import CASE_ES_TYPE from corehq.pillows.mappings.utils import mapping_from_json from corehq.util.elastic import es_index from pillowtop.es_utils import ElasticsearchIndexInfo CASE_SEARCH_INDEX = es_index("case_search_2016-03-15") CASE_SEARCH_ALIAS = "case_search" CASE_SEARCH_MAX_RESULTS = 10 CASE_SEARCH_MAPPING = mapping_from_json('case_search_mapping.json') CASE_SEARCH_INDEX_INFO = ElasticsearchIndexInfo( index=CASE_SEARCH_INDEX, alias=CASE_SEARCH_ALIAS, type=CASE_ES_TYPE, mapping=CASE_SEARCH_MAPPING, )
from corehq.pillows.mappings.case_mapping import CASE_ES_TYPE from corehq.pillows.mappings.utils import mapping_from_json from corehq.util.elastic import es_index from pillowtop.es_utils import ElasticsearchIndexInfo CASE_SEARCH_INDEX = es_index("case_search_2016-03-15") CASE_SEARCH_ALIAS = "case_search" CASE_SEARCH_MAX_RESULTS = 100 CASE_SEARCH_MAPPING = mapping_from_json('case_search_mapping.json') CASE_SEARCH_INDEX_INFO = ElasticsearchIndexInfo( index=CASE_SEARCH_INDEX, alias=CASE_SEARCH_ALIAS, type=CASE_ES_TYPE, mapping=CASE_SEARCH_MAPPING, )
Increase case search limit to 100 results
Increase case search limit to 100 results
Python
bsd-3-clause
dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq
--- +++ @@ -6,7 +6,7 @@ CASE_SEARCH_INDEX = es_index("case_search_2016-03-15") CASE_SEARCH_ALIAS = "case_search" -CASE_SEARCH_MAX_RESULTS = 10 +CASE_SEARCH_MAX_RESULTS = 100 CASE_SEARCH_MAPPING = mapping_from_json('case_search_mapping.json')
db20fc6b7a21efbd7de0f5b0d1aa754c19c1a21f
race/management/commands/update_leaderboard.py
race/management/commands/update_leaderboard.py
from django.core.management.base import BaseCommand from django.conf import settings from ...models import OverallDriverPrediction, OverallConstructorPrediction class Command(BaseCommand): can_import_settings = True def handle(self, *args, **kwargs): conn = settings.REDIS_CONN num_ranks = conn.zcard("ranks") conn.zremrangebyscore("ranks", 0, num_ranks) for driver_prediction in OverallDriverPrediction.objects.all(): conn.zadd("ranks", driver_prediction.user.username, driver_prediction.score) for constructor_prediction in OverallConstructorPrediction.objects.all(): score = conn.zscore("ranks", constructor_prediction.user.username) if not score: score = 0 conn.zadd("ranks", constructor_prediction.user.username, constructor_prediction.score + score)
from django.core.management.base import BaseCommand from django.conf import settings from ...models import OverallDriverPrediction, OverallConstructorPrediction class Command(BaseCommand): can_import_settings = True def handle(self, *args, **kwargs): conn = settings.REDIS_CONN num_ranks = conn.zcard("ranks") conn.zremrangebyscore("ranks", 0, num_ranks + 1) for driver_prediction in OverallDriverPrediction.objects.all(): conn.zadd("ranks", driver_prediction.user.username, driver_prediction.score) for constructor_prediction in OverallConstructorPrediction.objects.all(): score = conn.zscore("ranks", constructor_prediction.user.username) if not score: score = 0 conn.zadd("ranks", constructor_prediction.user.username, constructor_prediction.score + score)
Remove all scores before populating the sorted set.
Remove all scores before populating the sorted set.
Python
bsd-3-clause
theju/f1oracle,theju/f1oracle
--- +++ @@ -9,7 +9,7 @@ def handle(self, *args, **kwargs): conn = settings.REDIS_CONN num_ranks = conn.zcard("ranks") - conn.zremrangebyscore("ranks", 0, num_ranks) + conn.zremrangebyscore("ranks", 0, num_ranks + 1) for driver_prediction in OverallDriverPrediction.objects.all(): conn.zadd("ranks", driver_prediction.user.username,
0f0e0e91db679f18ad9dc7568047b76e447ac589
stock_inventory_chatter/__openerp__.py
stock_inventory_chatter/__openerp__.py
# -*- coding: utf-8 -*- # Copyright 2017 Eficent Business and IT Consulting Services S.L. # (http://www.eficent.com) # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). { 'name': 'Stock Inventory Chatter', 'version': '9.0.1.0.0', 'author': "Eficent, " "Odoo Community Association (OCA)", "website": "https://github.com/OCA/stock-logistics-warehouse", 'category': 'Warehouse', 'summary': "Log changes being done in Inventory Adjustments", 'depends': ['stock'], "data": [ 'data/stock_data.xml', 'views/stock_inventory_view.xml', ], 'license': 'AGPL-3', 'installable': True, 'application': False, }
# -*- coding: utf-8 -*- # Copyright 2017 Eficent Business and IT Consulting Services S.L. # Copyright 2018 initOS GmbH # (http://www.eficent.com) # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). { 'name': 'Stock Inventory Chatter', 'version': '8.0.1.0.0', 'author': "Eficent, " "initOS GmbH, " "Odoo Community Association (OCA)", "website": "https://github.com/OCA/stock-logistics-warehouse", 'category': 'Warehouse', 'summary': "Log changes being done in Inventory Adjustments", 'depends': ['stock'], "data": [ 'data/stock_data.xml', 'views/stock_inventory_view.xml', ], 'license': 'AGPL-3', 'installable': True, 'application': False, }
Change of the module version
Change of the module version
Python
agpl-3.0
kmee/stock-logistics-warehouse,acsone/stock-logistics-warehouse,open-synergy/stock-logistics-warehouse
--- +++ @@ -1,12 +1,14 @@ # -*- coding: utf-8 -*- # Copyright 2017 Eficent Business and IT Consulting Services S.L. +# Copyright 2018 initOS GmbH # (http://www.eficent.com) # License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl.html). { 'name': 'Stock Inventory Chatter', - 'version': '9.0.1.0.0', + 'version': '8.0.1.0.0', 'author': "Eficent, " + "initOS GmbH, " "Odoo Community Association (OCA)", "website": "https://github.com/OCA/stock-logistics-warehouse", 'category': 'Warehouse',
d3227e87b658b4ee634dd273a97d1a8fba4c96c9
lc461_hamming_distance.py
lc461_hamming_distance.py
"""Leetcode 461. Hamming Distance Medium URL: https://leetcode.com/problems/hamming-distance/description/ The Hamming distance between two integers is the number of positions at which the corresponding bits are different. Given two integers x and y, calculate the Hamming distance. Note: 0 ≤ x, y < 231. Example: Input: x = 1, y = 4 Output: 2 Explanation: 1 (0 0 0 1) 4 (0 1 0 0) ↑ ↑ The above arrows point to positions where the corresponding bits are different. """ class Solution(object): def hammingDistance(self, x, y): """ :type x: int :type y: int :rtype: int Time complexity: O(1). Space complexity: O(1). """ return bin(x ^ y).count('1') def main(): print Solution().hammingDistance(1, 4) if __name__ == '__main__': main()
"""Leetcode 461. Hamming Distance Medium URL: https://leetcode.com/problems/hamming-distance/description/ The Hamming distance between two integers is the number of positions at which the corresponding bits are different. Given two integers x and y, calculate the Hamming distance. Note: 0 ≤ x, y < 231. Example: Input: x = 1, y = 4 Output: 2 Explanation: 1 (0 0 0 1) 4 (0 1 0 0) ↑ ↑ The above arrows point to positions where the corresponding bits are different. """ class Solution(object): def hammingDistance(self, x, y): """ :type x: int :type y: int :rtype: int Time complexity: O(1). Space complexity: O(1). """ return bin(x ^ y).count('1') def main(): print Solution().hammingDistance(1, 4) if __name__ == '__main__': main()
Revise docstring and add space line
Revise docstring and add space line
Python
bsd-2-clause
bowen0701/algorithms_data_structures
--- +++ @@ -22,7 +22,8 @@ 4 (0 1 0 0) ↑ ↑ -The above arrows point to positions where the corresponding bits are different. +The above arrows point to positions where the corresponding bits +are different. """ class Solution(object): @@ -41,5 +42,6 @@ def main(): print Solution().hammingDistance(1, 4) + if __name__ == '__main__': main()