commit stringlengths 40 40 | old_file stringlengths 5 117 | new_file stringlengths 5 117 | old_contents stringlengths 0 1.93k | new_contents stringlengths 19 3.3k | subject stringlengths 17 320 | message stringlengths 18 3.28k | lang stringclasses 1
value | license stringclasses 13
values | repos stringlengths 7 42.4k | completion stringlengths 152 6.66k | prompt stringlengths 21 3.65k |
|---|---|---|---|---|---|---|---|---|---|---|---|
ccda4cd859b512d8694eba4261439bb52574f099 | cities/Sample_City.py | cities/Sample_City.py | from bs4 import BeautifulSoup
# The URL for the page where the parking lots are listed
data_url = "http://example.com"
# Name of the city, just in case it contains umlauts which this filename shouldn't
city_name = "Sample City"
# Name of this file (without '.py'), sorry for needing this, but it makes things easier
f... | from bs4 import BeautifulSoup
import json
# The URL for the page where the parking lots are listed
data_url = "http://example.com"
# Name of the city, just in case it contains umlauts which this filename shouldn't
city_name = "Sample City"
# Name of this file (without '.py'), sorry for needing this, but it makes thi... | Add geodata parsing to sample city file | Add geodata parsing to sample city file
| Python | mit | Mic92/ParkAPI,Mic92/ParkAPI,offenesdresden/ParkAPI,offenesdresden/ParkAPI | <REPLACE_OLD> BeautifulSoup
# <REPLACE_NEW> BeautifulSoup
import json
# <REPLACE_END> <REPLACE_OLD> schema.
<REPLACE_NEW> schema.
def get_geodata_for_lot(lot_name):
geofile = open("./cities/" + file_name + ".geojson")
geodata = geofile.read()
geofile.close()
geodata = json.loads(geodata)
for f... | Add geodata parsing to sample city file
from bs4 import BeautifulSoup
# The URL for the page where the parking lots are listed
data_url = "http://example.com"
# Name of the city, just in case it contains umlauts which this filename shouldn't
city_name = "Sample City"
# Name of this file (without '.py'), sorry for n... |
d55389580160c4585c131537c04c4045a38ea134 | fluxghost/http_server_base.py | fluxghost/http_server_base.py |
from select import select
import logging
import socket
logger = logging.getLogger("HTTPServer")
from fluxghost.http_handlers.websocket_handler import WebSocketHandler
from fluxghost.http_handlers.file_handler import FileHandler
class HttpServerBase(object):
def __init__(self, assets_path, address, backlog=10):... |
from select import select
import logging
import socket
logger = logging.getLogger("HTTPServer")
from fluxghost.http_handlers.websocket_handler import WebSocketHandler
from fluxghost.http_handlers.file_handler import FileHandler
class HttpServerBase(object):
def __init__(self, assets_path, address, backlog=10):... | Add auto select port function | Add auto select port function
| Python | agpl-3.0 | flux3dp/fluxghost,flux3dp/fluxghost,flux3dp/fluxghost,flux3dp/fluxghost | <REPLACE_OLD> s.listen(backlog)
<REPLACE_NEW> s.listen(backlog)
if address[1] == 0:
from sys import stdout
address = s.getsockname()
stdout.write("LISTEN ON %i\n" % address[1])
stdout.flush()
<REPLACE_END> <|endoftext|>
from select import select
import loggin... | Add auto select port function
from select import select
import logging
import socket
logger = logging.getLogger("HTTPServer")
from fluxghost.http_handlers.websocket_handler import WebSocketHandler
from fluxghost.http_handlers.file_handler import FileHandler
class HttpServerBase(object):
def __init__(self, ass... |
340cbe542b89515033b6da40cf6cd6f761cfba9f | src/constants.py | src/constants.py | #!/usr/bin/env python
TRAJECTORY = 'linear'
CONTROLLER = 'pid'
if TRAJECTORY == 'linear':
SIMULATION_TIME_IN_SECONDS = 80.0
elif TRAJECTORY == 'circular':
SIMULATION_TIME_IN_SECONDS = 120.0
elif TRAJECTORY == 'squared':
SIMULATION_TIME_IN_SECONDS = 160.0
DELTA_T = 0.1 # this is the sampling time
STEPS = i... | #!/usr/bin/env python
TRAJECTORY = 'linear'
CONTROLLER = 'pid'
if TRAJECTORY == 'linear':
SIMULATION_TIME_IN_SECONDS = 60.0
elif TRAJECTORY == 'circular':
SIMULATION_TIME_IN_SECONDS = 120.0
elif TRAJECTORY == 'squared':
SIMULATION_TIME_IN_SECONDS = 160.0
DELTA_T = 0.1 # this is the sampling time
STEPS = i... | Change simulation time of linear trajectory to 60 seconds | Change simulation time of linear trajectory to 60 seconds
| Python | mit | bit0001/trajectory_tracking,bit0001/trajectory_tracking | <REPLACE_OLD> 80.0
elif <REPLACE_NEW> 60.0
elif <REPLACE_END> <|endoftext|> #!/usr/bin/env python
TRAJECTORY = 'linear'
CONTROLLER = 'pid'
if TRAJECTORY == 'linear':
SIMULATION_TIME_IN_SECONDS = 60.0
elif TRAJECTORY == 'circular':
SIMULATION_TIME_IN_SECONDS = 120.0
elif TRAJECTORY == 'squared':
SIMULATION_... | Change simulation time of linear trajectory to 60 seconds
#!/usr/bin/env python
TRAJECTORY = 'linear'
CONTROLLER = 'pid'
if TRAJECTORY == 'linear':
SIMULATION_TIME_IN_SECONDS = 80.0
elif TRAJECTORY == 'circular':
SIMULATION_TIME_IN_SECONDS = 120.0
elif TRAJECTORY == 'squared':
SIMULATION_TIME_IN_SECONDS ... |
2af6e066509689ed14f40b122c600bed39dea543 | setup.py | setup.py | #!/usr/bin/env python3
from setuptools import setup, find_packages
setup(
name='ppp_datamodel',
version='0.4',
description='Data model for the Projet Pensées Profondes.',
url='https://github.com/ProjetPP/PPP-datamodel-Python',
author='Valentin Lorentz',
author_email='valentin.lorentz+ppp@ens-l... | #!/usr/bin/env python3
from setuptools import setup, find_packages
setup(
name='ppp_datamodel',
version='0.5',
description='Data model for the Projet Pensées Profondes.',
url='https://github.com/ProjetPP/PPP-datamodel-Python',
author='Valentin Lorentz',
author_email='valentin.lorentz+ppp@ens-l... | Bump version number to 0.5 | Bump version number to 0.5
| Python | agpl-3.0 | ProjetPP/PPP-datamodel-Python,ProjetPP/PPP-datamodel-Python | <REPLACE_OLD> version='0.4',
<REPLACE_NEW> version='0.5',
<REPLACE_END> <|endoftext|> #!/usr/bin/env python3
from setuptools import setup, find_packages
setup(
name='ppp_datamodel',
version='0.5',
description='Data model for the Projet Pensées Profondes.',
url='https://github.com/ProjetPP/PPP-datamo... | Bump version number to 0.5
#!/usr/bin/env python3
from setuptools import setup, find_packages
setup(
name='ppp_datamodel',
version='0.4',
description='Data model for the Projet Pensées Profondes.',
url='https://github.com/ProjetPP/PPP-datamodel-Python',
author='Valentin Lorentz',
author_email... |
c25cebf31648466111cb3d576e0a398bb4220ccf | sabnzbd/test_cleanupfilename.py | sabnzbd/test_cleanupfilename.py | import unittest
from cleanupfilename import rename
class TestRename(unittest.TestCase):
files = []
dirs = []
def setUp(self):
self.files = [('filename-sample.x264.mp4', 'filename.mp4'),
('filename.mp4', 'filename.mp4')]
self.dirs = [('filename sample mp4', 'filename'... | Add test for sabnzbd cleanupfilename.py | Add test for sabnzbd cleanupfilename.py
| Python | bsd-3-clause | FreekKalter/linux-scripts,FreekKalter/linux-scripts,FreekKalter/linux-scripts,FreekKalter/linux-scripts | <REPLACE_OLD> <REPLACE_NEW> import unittest
from cleanupfilename import rename
class TestRename(unittest.TestCase):
files = []
dirs = []
def setUp(self):
self.files = [('filename-sample.x264.mp4', 'filename.mp4'),
('filename.mp4', 'filename.mp4')]
self.dirs = [('fil... | Add test for sabnzbd cleanupfilename.py
| |
0ba0d7d1e0b19ef0523c66726cff637018703b4a | tests/test_requesthandler.py | tests/test_requesthandler.py | from unittest import TestCase
from ppp_datamodel.communication import Request
from ppp_datamodel import Triple, Resource, Missing, Sentence
from ppp_libmodule.tests import PPPTestCase
from ppp_spell_checker import app
class RequestHandlerTest(PPPTestCase(app)):
def testCorrectSentence(self):
original = 'W... | from unittest import TestCase
from ppp_datamodel.communication import Request
from ppp_datamodel import Triple, Resource, Missing, Sentence
from ppp_libmodule.tests import PPPTestCase
from ppp_spell_checker import app
class RequestHandlerTest(PPPTestCase(app)):
def testCorrectSentence(self):
original = 'W... | Write tests in a better way | Write tests in a better way
| Python | mit | ProjetPP/PPP-Spell-Checker,ProjetPP/PPP-Spell-Checker | <REPLACE_OLD> self.assertEquals(len(answer), 0)
<REPLACE_NEW> self.assertEqual(len(answer), 0, answer)
<REPLACE_END> <REPLACE_OLD> self.assertEquals(len(answer), 1)
self.assertIsInstance(answer[0].tree, Sentence)
result = answer[0].tree.__getattr__('value')
self.assertEqual(result, expected)... | Write tests in a better way
from unittest import TestCase
from ppp_datamodel.communication import Request
from ppp_datamodel import Triple, Resource, Missing, Sentence
from ppp_libmodule.tests import PPPTestCase
from ppp_spell_checker import app
class RequestHandlerTest(PPPTestCase(app)):
def testCorrectSentence... |
6ce83f65f12fe02c4f9417c610322f21ef6c02c6 | apps/plea/tests/test_timeout.py | apps/plea/tests/test_timeout.py | from django.test import TestCase
from django.test.client import Client
from django.conf import settings
from importlib import import_module
from ..views import PleaOnlineForms
class TestTimeout(TestCase):
def setUp(self):
self.client = Client()
# http://code.djangoproject.com/ticket/10899
... | Add unit tests for session timeout http headers | Add unit tests for session timeout http headers
These tests check for the absence or presence
of the session timeout redirect headers.
[MAPDEV326]
| Python | mit | ministryofjustice/manchester_traffic_offences_pleas,ministryofjustice/manchester_traffic_offences_pleas,ministryofjustice/manchester_traffic_offences_pleas,ministryofjustice/manchester_traffic_offences_pleas | <REPLACE_OLD> <REPLACE_NEW> from django.test import TestCase
from django.test.client import Client
from django.conf import settings
from importlib import import_module
from ..views import PleaOnlineForms
class TestTimeout(TestCase):
def setUp(self):
self.client = Client()
# http://code.djangopro... | Add unit tests for session timeout http headers
These tests check for the absence or presence
of the session timeout redirect headers.
[MAPDEV326]
| |
2ae16c880d6b38c00b5eb48d99facacc5a3ccf7e | python/second-largest.py | python/second-largest.py | # You are given as input an unsorted array of n distinct numbers,
# where n is a power of 2.
# Give an algorithm that identifies the second-largest number in the array,
# and that uses at most n + log2n - 2 comparisons.
A = [4, 512, 8, 64, 16, 2, 32, 256] # Uses at most 9 comparisons
# def second_largest (Array):
... | Add solution to hamming numbers kata | Add solution to hamming numbers kata
| Python | mit | HiccupinGminor/tidbits,HiccupinGminor/tidbits | <REPLACE_OLD> <REPLACE_NEW> # You are given as input an unsorted array of n distinct numbers,
# where n is a power of 2.
# Give an algorithm that identifies the second-largest number in the array,
# and that uses at most n + log2n - 2 comparisons.
A = [4, 512, 8, 64, 16, 2, 32, 256] # Uses at most 9 comparisons
#... | Add solution to hamming numbers kata
| |
5b3d69d2c9338ab0c50fd9ea8cf3c01adf0c1de3 | breakpad.py | breakpad.py | # Copyright (c) 2009 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Breakpad for Python.
Sends a notification when a process stops on an exception."""
import atexit
import getpass
import urllib
import traceback
impor... | # Copyright (c) 2009 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Breakpad for Python.
Sends a notification when a process stops on an exception."""
import atexit
import getpass
import urllib
import traceback
impor... | Disable braekpad automatic registration while we figure out stuff | Disable braekpad automatic registration while we figure out stuff
Review URL: http://codereview.chromium.org/462022
git-svn-id: fd409f4bdeea2bb50a5d34bb4d4bfc2046a5a3dd@33686 0039d316-1c4b-4281-b951-d872f2087c98
| Python | bsd-3-clause | xuyuhan/depot_tools,npe9/depot_tools,SuYiling/chrome_depot_tools,Neozaru/depot_tools,npe9/depot_tools,Midrya/chromium,michalliu/chromium-depot_tools,kaiix/depot_tools,disigma/depot_tools,Chilledheart/depot_tools,fracting/depot_tools,airtimemedia/depot_tools,Midrya/chromium,duongbaoduy/gtools,coreos/depot_tools,duongbao... | <REPLACE_OLD> bad.')
@atexit.register
def <REPLACE_NEW> bad.')
#@atexit.register
def <REPLACE_END> <|endoftext|> # Copyright (c) 2009 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Breakpad for Python.
Sends a not... | Disable braekpad automatic registration while we figure out stuff
Review URL: http://codereview.chromium.org/462022
git-svn-id: fd409f4bdeea2bb50a5d34bb4d4bfc2046a5a3dd@33686 0039d316-1c4b-4281-b951-d872f2087c98
# Copyright (c) 2009 The Chromium Authors. All rights reserved.
# Use of this source code is governed by ... |
7b09f0309460eb306ef74a0bedfcad82ae3d91a0 | regparser/web/jobs/migrations/0012_auto_20161012_2059.py | regparser/web/jobs/migrations/0012_auto_20161012_2059.py | # -*- coding: utf-8 -*-
# Generated by Django 1.9.10 on 2016-10-12 20:59
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('jobs', '0011_auto_20161011_2135'),
]
operations = [
migrations.AlterField(
... | Remove default keyword from hexhash key for RegulationFile. | Remove default keyword from hexhash key for RegulationFile.
| Python | cc0-1.0 | eregs/regulations-parser,tadhg-ohiggins/regulations-parser,tadhg-ohiggins/regulations-parser,eregs/regulations-parser | <INSERT> # -*- coding: utf-8 -*-
# Generated by Django 1.9.10 on 2016-10-12 20:59
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
<INSERT_END> <INSERT> dependencies = [
('jobs', '0011_auto_20161011_2135'),
]
operations = [
... | Remove default keyword from hexhash key for RegulationFile.
| |
e0797f6dbefea651420f474940963b470a0931fd | test/functional/test_framework/txtools.py | test/functional/test_framework/txtools.py | from .cdefs import MIN_TX_SIZE, MAX_TXOUT_PUBKEY_SCRIPT
from .mininode import CTransaction, FromHex, ToHex, CTxOut
from .script import OP_RETURN, CScript
import random
from binascii import hexlify, unhexlify
# Pad outputs until it reaches at least min_size
def pad_tx(tx, min_size=None):
if min_size is None:
... | from .cdefs import MIN_TX_SIZE, MAX_TXOUT_PUBKEY_SCRIPT
from .mininode import CTransaction, FromHex, ToHex, CTxOut
from .script import OP_RETURN, CScript
import random
from binascii import hexlify, unhexlify
# Pad outputs until it reaches at least min_size
def pad_tx(tx, min_size=None):
if min_size is None:
... | Fix pad_tx off by one error + nits | Fix pad_tx off by one error + nits
Summary: See title
Test Plan: test_runner.py
Reviewers: deadalnix, schancel, #bitcoin_abc
Reviewed By: schancel, #bitcoin_abc
Subscribers: teamcity
Differential Revision: https://reviews.bitcoinabc.org/D2096
| Python | mit | Bitcoin-ABC/bitcoin-abc,cculianu/bitcoin-abc,Bitcoin-ABC/bitcoin-abc,cculianu/bitcoin-abc,cculianu/bitcoin-abc,ftrader-bitcoinabc/bitcoin-abc,Bitcoin-ABC/bitcoin-abc,ftrader-bitcoinabc/bitcoin-abc,Bitcoin-ABC/bitcoin-abc,Bitcoin-ABC/bitcoin-abc,cculianu/bitcoin-abc,ftrader-bitcoinabc/bitcoin-abc,Bitcoin-ABC/bitcoin-abc... | <REPLACE_OLD> 1, <REPLACE_NEW> 2, <REPLACE_END> <REPLACE_OLD> padding_len)
<REPLACE_NEW> padding_len - 1)
<REPLACE_END> <DELETE> <DELETE_END> <REPLACE_OLD> min_size=None):
<REPLACE_NEW> min_size=None):
<REPLACE_END> <|endoftext|> from .cdefs import MIN_TX_SIZE, MAX_TXOUT_PUBKEY_SCRIPT
from .mininode import CTrans... | Fix pad_tx off by one error + nits
Summary: See title
Test Plan: test_runner.py
Reviewers: deadalnix, schancel, #bitcoin_abc
Reviewed By: schancel, #bitcoin_abc
Subscribers: teamcity
Differential Revision: https://reviews.bitcoinabc.org/D2096
from .cdefs import MIN_TX_SIZE, MAX_TXOUT_PUBKEY_SCRIPT
from .mininode... |
da6f3cd94e60e4792926bd9f924714bb8a7c1903 | YaDiskClient/__init__.py | YaDiskClient/__init__.py | """
Client for Yandex.Disk.
"""
__version__ = '0.3.2'
from .YaDiskClient import YaDiskException, YaDisk
| """
Client for Yandex.Disk.
"""
__version__ = '0.3.3'
from .YaDiskClient import YaDiskException, YaDisk
| Change version, upload to pypi. | Change version, upload to pypi.
| Python | mit | TyVik/YaDiskClient | <REPLACE_OLD> '0.3.2'
from <REPLACE_NEW> '0.3.3'
from <REPLACE_END> <|endoftext|> """
Client for Yandex.Disk.
"""
__version__ = '0.3.3'
from .YaDiskClient import YaDiskException, YaDisk
| Change version, upload to pypi.
"""
Client for Yandex.Disk.
"""
__version__ = '0.3.2'
from .YaDiskClient import YaDiskException, YaDisk
|
f6a8e84a2557c5edf29a6f3afa4d1cce1d42d389 | tests/basics/try_finally_loops.py | tests/basics/try_finally_loops.py | # Test various loop types, some may be implemented/optimized differently
while True:
try:
break
finally:
print('finally 1')
for i in [1, 5, 10]:
try:
continue
finally:
print('finally 2')
for i in range(3):
try:
continue
finally:
print('finally 3... | # Test various loop types, some may be implemented/optimized differently
while True:
try:
break
finally:
print('finally 1')
for i in [1, 5, 10]:
try:
continue
finally:
print('finally 2')
for i in range(3):
try:
continue
finally:
print('finally 3... | Add test for break from within try within a for-loop. | tests/basics: Add test for break from within try within a for-loop.
| Python | mit | turbinenreiter/micropython,Peetz0r/micropython-esp32,hosaka/micropython,ryannathans/micropython,bvernoux/micropython,tralamazza/micropython,cwyark/micropython,turbinenreiter/micropython,alex-march/micropython,SHA2017-badge/micropython-esp32,dxxb/micropython,swegener/micropython,adafruit/circuitpython,SHA2017-badge/micr... | <REPLACE_OLD> 3')
<REPLACE_NEW> 3')
# break from within try-finally, within for-loop
for i in [1]:
try:
print(i)
break
finally:
print('finally 4')
<REPLACE_END> <|endoftext|> # Test various loop types, some may be implemented/optimized differently
while True:
try:
break
... | tests/basics: Add test for break from within try within a for-loop.
# Test various loop types, some may be implemented/optimized differently
while True:
try:
break
finally:
print('finally 1')
for i in [1, 5, 10]:
try:
continue
finally:
print('finally 2')
for i in rang... |
6a71652e3cfdec22307b05539914aa6325cb4d53 | setup.py | setup.py | #!/usr/bin/env python
from __future__ import with_statement
import sys
from setuptools import setup, find_packages
long_description = """
Pypimirror - A Pypi mirror script that uses threading and requests
"""
install_requires = [
'beautifulsoup4==4.4.1',
'requests==2.9.1',
]
setup(
name='pypimirror',
... | #!/usr/bin/env python
from __future__ import with_statement
import sys
from setuptools import setup, find_packages
long_description = """
Pypimirror - A Pypi mirror script that uses threading and requests
"""
install_requires = [
'beautifulsoup4==4.4.1',
'requests==2.9.1',
]
setup(
name='pypimirror-si... | Change project name to avoid pypi conflict | Change project name to avoid pypi conflict
| Python | mit | wilypomegranate/pypimirror | <REPLACE_OLD> name='pypimirror',
version='0.1.0a',
description='pypimirror',
<REPLACE_NEW> name='pypimirror-simple',
version='0.1.0a0',
description='A simple pypimirror',
<REPLACE_END> <|endoftext|> #!/usr/bin/env python
from __future__ import with_statement
import sys
from setuptools import setup,... | Change project name to avoid pypi conflict
#!/usr/bin/env python
from __future__ import with_statement
import sys
from setuptools import setup, find_packages
long_description = """
Pypimirror - A Pypi mirror script that uses threading and requests
"""
install_requires = [
'beautifulsoup4==4.4.1',
'request... |
be7f3153e1505ecdfca6e5078c4b3a4ed1817c28 | setup.py | setup.py | import os
import json
from setuptools import setup
f = open(os.path.join(os.path.dirname(__file__), 'README.md'))
readme = f.read()
f.close()
f = open(os.path.join(os.path.dirname(__file__), 'package.json'))
package = json.loads(f.read())
f.close()
setup(
name=package['name'],
version=package['version'],
... | import os
import json
from setuptools import setup
f = open(os.path.join(os.path.dirname(__file__), 'README.md'))
readme = f.read()
f.close()
f = open(os.path.join(os.path.dirname(__file__), 'package.json'))
package = json.loads(f.read())
f.close()
setup(
name=package['name'],
version=package['version'],
... | Add description content type for pypi. | Add description content type for pypi.
| Python | mit | bradleyg/django-s3direct,bradleyg/django-s3direct,bradleyg/django-s3direct | <INSERT> long_description_content_type='text/markdown',
<INSERT_END> <|endoftext|> import os
import json
from setuptools import setup
f = open(os.path.join(os.path.dirname(__file__), 'README.md'))
readme = f.read()
f.close()
f = open(os.path.join(os.path.dirname(__file__), 'package.json'))
package = json.loads(f.... | Add description content type for pypi.
import os
import json
from setuptools import setup
f = open(os.path.join(os.path.dirname(__file__), 'README.md'))
readme = f.read()
f.close()
f = open(os.path.join(os.path.dirname(__file__), 'package.json'))
package = json.loads(f.read())
f.close()
setup(
name=package['nam... |
a165962921ccdfbd6ba4eb4a6c7cbd38b57fdf47 | hackerrank_datatype.py | hackerrank_datatype.py | i=10
d=2.5
s="HackerRank"
# Declare second integer, double, and String variables.
ii=int(raw_input())
dd=float(raw_input())
ss=raw_input()
# Read and save an integer, double, and String to your variables.
# Print the sum of both integer variables on a new line.
print i+ii
# Print the sum of the double variables on a n... | Print sum of same data types on a different line | Print sum of same data types on a different line
| Python | mit | kumarisneha/practice_repo | <REPLACE_OLD> <REPLACE_NEW> i=10
d=2.5
s="HackerRank"
# Declare second integer, double, and String variables.
ii=int(raw_input())
dd=float(raw_input())
ss=raw_input()
# Read and save an integer, double, and String to your variables.
# Print the sum of both integer variables on a new line.
print i+ii
# Print the sum o... | Print sum of same data types on a different line
| |
63f9f87a3f04cb03c1e286cc5b6d49306f90e352 | python/004_largest_palindrome_product/palindrome_product.py | python/004_largest_palindrome_product/palindrome_product.py | from itertools import combinations_with_replacement
from operator import mul
three_digit_numbers = tuple(range(100, 1000))
combinations = combinations_with_replacement(three_digit_numbers, 2)
products = [mul(*x) for x in combinations]
max_palindrome = max([x for x in products if str(x)[::-1] == str(x)])
| Add solution for problem 4 | Add solution for problem 4
| Python | bsd-3-clause | gidj/euler,gidj/euler | <REPLACE_OLD> <REPLACE_NEW> from itertools import combinations_with_replacement
from operator import mul
three_digit_numbers = tuple(range(100, 1000))
combinations = combinations_with_replacement(three_digit_numbers, 2)
products = [mul(*x) for x in combinations]
max_palindrome = max([x for x in products if str(x)[... | Add solution for problem 4
| |
8bd738972cebd27b068250bd52db8aacea6c7876 | src/condor_tests/ornithology/plugin.py | src/condor_tests/ornithology/plugin.py | import pytest
from .scripts import SCRIPTS
# This module is loaded as a "plugin" by pytest by a setting in conftest.py
# Any fixtures defined here will be globally available in tests,
# as if they were defined in conftest.py itself.
@pytest.fixture(scope="session")
def path_to_sleep():
return SCRIPTS["sleep"]
| import sys
import pytest
from .scripts import SCRIPTS
# This module is loaded as a "plugin" by pytest by a setting in conftest.py
# Any fixtures defined here will be globally available in tests,
# as if they were defined in conftest.py itself.
@pytest.fixture(scope="session")
def path_to_sleep():
return SCRIPTS[... | Add path_to_python fixture to make writing multiplatform job scripts easier. | Add path_to_python fixture to make writing multiplatform job scripts easier.
| Python | apache-2.0 | htcondor/htcondor,htcondor/htcondor,htcondor/htcondor,htcondor/htcondor,htcondor/htcondor,htcondor/htcondor,htcondor/htcondor,htcondor/htcondor | <INSERT> sys
import <INSERT_END> <REPLACE_OLD> SCRIPTS["sleep"]
<REPLACE_NEW> SCRIPTS["sleep"]
@pytest.fixture(scope="session")
def path_to_python():
return sys.executable
<REPLACE_END> <|endoftext|> import sys
import pytest
from .scripts import SCRIPTS
# This module is loaded as a "plugin" by pytest by a sett... | Add path_to_python fixture to make writing multiplatform job scripts easier.
import pytest
from .scripts import SCRIPTS
# This module is loaded as a "plugin" by pytest by a setting in conftest.py
# Any fixtures defined here will be globally available in tests,
# as if they were defined in conftest.py itself.
@pytes... |
6480e801de5f21486d99444c25006b70329e580e | luigi/tasks/release/process_data.py | luigi/tasks/release/process_data.py | # -*- coding: utf-8 -*-
"""
Copyright [2009-2017] EMBL-European Bioinformatics Institute
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... | # -*- coding: utf-8 -*-
"""
Copyright [2009-2017] EMBL-European Bioinformatics Institute
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... | Add RGD as part of the regular update pipeline | Add RGD as part of the regular update pipeline
I'm not sure if this will always be part of the update, but it is for at
least for this release.
| Python | apache-2.0 | RNAcentral/rnacentral-import-pipeline,RNAcentral/rnacentral-import-pipeline,RNAcentral/rnacentral-import-pipeline,RNAcentral/rnacentral-import-pipeline | <REPLACE_OLD> RfamFamilies
class <REPLACE_NEW> RfamFamilies
from tasks.rgd import Rgd
class <REPLACE_END> <INSERT> yield Rgd()
<INSERT_END> <|endoftext|> # -*- coding: utf-8 -*-
"""
Copyright [2009-2017] EMBL-European Bioinformatics Institute
Licensed under the Apache License, Version 2.0 (the "License");
... | Add RGD as part of the regular update pipeline
I'm not sure if this will always be part of the update, but it is for at
least for this release.
# -*- coding: utf-8 -*-
"""
Copyright [2009-2017] EMBL-European Bioinformatics Institute
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this... |
536746eaf35f4a2899a747bfe0b1e8918f9ec8c9 | httoop/header/__init__.py | httoop/header/__init__.py | # -*- coding: utf-8 -*-
"""HTTP headers
.. seealso:: :rfc:`2616#section-2.2`
.. seealso:: :rfc:`2616#section-4.2`
.. seealso:: :rfc:`2616#section-14`
"""
__all__ = ['Headers']
# FIXME: python3?
# TODO: add a MAXIMUM of 500 headers?
import inspect
from httoop.header.element import HEADER, HeaderElement, HeaderTyp... | # -*- coding: utf-8 -*-
"""HTTP headers
.. seealso:: :rfc:`2616#section-2.2`
.. seealso:: :rfc:`2616#section-4.2`
.. seealso:: :rfc:`2616#section-14`
"""
__all__ = ['Headers']
# FIXME: python3?
# TODO: add a MAXIMUM of 500 headers?
import inspect
from httoop.header.element import HEADER, HeaderElement, HeaderTyp... | Add all header elements to httoop.header | Add all header elements to httoop.header
| Python | mit | spaceone/httoop,spaceone/httoop,spaceone/httoop | <INSERT> member
globals()[_] = <INSERT_END> <|endoftext|> # -*- coding: utf-8 -*-
"""HTTP headers
.. seealso:: :rfc:`2616#section-2.2`
.. seealso:: :rfc:`2616#section-4.2`
.. seealso:: :rfc:`2616#section-14`
"""
__all__ = ['Headers']
# FIXME: python3?
# TODO: add a MAXIMUM of 500 headers?
import inspect
from h... | Add all header elements to httoop.header
# -*- coding: utf-8 -*-
"""HTTP headers
.. seealso:: :rfc:`2616#section-2.2`
.. seealso:: :rfc:`2616#section-4.2`
.. seealso:: :rfc:`2616#section-14`
"""
__all__ = ['Headers']
# FIXME: python3?
# TODO: add a MAXIMUM of 500 headers?
import inspect
from httoop.header.eleme... |
62d3f84155291bf020870b618cf139d8333a04cd | example-flask-python3.6-index/app/main.py | example-flask-python3.6-index/app/main.py | import os
from flask import Flask, send_file
app = Flask(__name__)
@app.route("/hello")
def hello():
return "Hello World from Flask in a uWSGI Nginx Docker container with \
Python 3.6 (from the example template)"
@app.route("/")
def main():
return send_file('./static/index.html')
# Everything not de... | import os
from flask import Flask, send_file
app = Flask(__name__)
@app.route("/hello")
def hello():
return "Hello World from Flask in a uWSGI Nginx Docker container with \
Python 3.6 (from the example template)"
@app.route("/")
def main():
index_path = os.path.join(app.static_folder, 'index.html')
... | Update view function to keep working even when moved to a package project structure | Update view function to keep working even when moved to a package project structure
| Python | apache-2.0 | tiangolo/uwsgi-nginx-flask-docker,tiangolo/uwsgi-nginx-flask-docker,tiangolo/uwsgi-nginx-flask-docker | <INSERT> index_path = os.path.join(app.static_folder, 'index.html')
<INSERT_END> <REPLACE_OLD> send_file('./static/index.html')
# <REPLACE_NEW> send_file(index_path)
# <REPLACE_END> <REPLACE_OLD> './static/' + path
<REPLACE_NEW> os.path.join(app.static_folder, path)
<REPLACE_END> <INSERT> index_path = os.path... | Update view function to keep working even when moved to a package project structure
import os
from flask import Flask, send_file
app = Flask(__name__)
@app.route("/hello")
def hello():
return "Hello World from Flask in a uWSGI Nginx Docker container with \
Python 3.6 (from the example template)"
@app.rou... |
599e2328ba0ab4f5fa467a363e35b8c99392ad3c | elvis/utils.py | elvis/utils.py | from datetime import datetime, timedelta
import pytz
DATE_PREFIX = '/Date('
DATE_SUFFIX = ')/'
ELVIS_TIMEZONE = pytz.timezone('Europe/Tallinn')
def decode_elvis_timestamp(timestamp: str):
"""Try to convert the argument to timestamp using ELVIS rules, return it unmodified if impossible"""
str_timestamp = str... | from datetime import datetime
import pytz
DATE_PREFIX = '/Date('
DATE_SUFFIX = ')/'
ELVIS_TIMEZONE = pytz.timezone('Europe/Tallinn')
UTC = pytz.timezone('UTC')
def decode_elvis_timestamp(timestamp: str):
"""Try to convert the argument to timestamp using ELVIS rules, return it unmodified if impossible"""
str... | Fix date parsing having wrong offset | Fix date parsing having wrong offset
| Python | bsd-2-clause | thorgate/python-lvis | <REPLACE_OLD> datetime, timedelta
import <REPLACE_NEW> datetime
import <REPLACE_END> <REPLACE_OLD> pytz.timezone('Europe/Tallinn')
def <REPLACE_NEW> pytz.timezone('Europe/Tallinn')
UTC = pytz.timezone('UTC')
def <REPLACE_END> <REPLACE_OLD> datetime.fromtimestamp(seconds).astimezone(
ELVIS_TIMEZONE
... | Fix date parsing having wrong offset
from datetime import datetime, timedelta
import pytz
DATE_PREFIX = '/Date('
DATE_SUFFIX = ')/'
ELVIS_TIMEZONE = pytz.timezone('Europe/Tallinn')
def decode_elvis_timestamp(timestamp: str):
"""Try to convert the argument to timestamp using ELVIS rules, return it unmodified if... |
827644a143a0fae0a1fa34ce2c624b199d0c1b63 | bisnode/models.py | bisnode/models.py | from django.db import models
from .constants import COMPANY_RATING_REPORT, RATING_CHOICES
from .bisnode import get_bisnode_company_report
class BisnodeRatingReport(models.Model):
organization_number = models.CharField(max_length=10)
rating = models.CharField(max_length=3, choices=RATING_CHOICES,
... | from datetime import datetime, date
from django.db import models
from .constants import COMPANY_RATING_REPORT, RATING_CHOICES
from .bisnode import get_bisnode_company_report
def bisnode_date_to_date(bisnode_date):
formatted_datetime = datetime.strptime(bisnode_date, "%Y%m%d")
return formatted_datetime.date(... | Save dates from Bisnode correctly | Save dates from Bisnode correctly
| Python | mit | FundedByMe/django-bisnode | <INSERT> datetime import datetime, date
from <INSERT_END> <REPLACE_OLD> RATING_CHOICES
from <REPLACE_NEW> RATING_CHOICES
from <REPLACE_END> <REPLACE_OLD> get_bisnode_company_report
class <REPLACE_NEW> get_bisnode_company_report
def bisnode_date_to_date(bisnode_date):
formatted_datetime = datetime.strptime(bis... | Save dates from Bisnode correctly
from django.db import models
from .constants import COMPANY_RATING_REPORT, RATING_CHOICES
from .bisnode import get_bisnode_company_report
class BisnodeRatingReport(models.Model):
organization_number = models.CharField(max_length=10)
rating = models.CharField(max_length=3, ... |
0997b216ea520aca2d8d62ac31a238c7280302ca | bananas/admin/api/serializers.py | bananas/admin/api/serializers.py | from django.contrib.auth import password_validation
from django.utils.translation import ugettext_lazy as _
from rest_framework import serializers
class AuthenticationSerializer(serializers.Serializer):
username = serializers.CharField(label=_("Username"), write_only=True)
password = serializers.CharField(lab... | from django.contrib.auth.password_validation import password_validators_help_texts
from django.utils.translation import ugettext_lazy as _
from rest_framework import serializers
class AuthenticationSerializer(serializers.Serializer):
username = serializers.CharField(label=_("Username"), write_only=True)
passw... | Use plain password help text instead of html | Use plain password help text instead of html
| Python | mit | 5monkeys/django-bananas,5monkeys/django-bananas,5monkeys/django-bananas | <REPLACE_OLD> django.contrib.auth <REPLACE_NEW> django.contrib.auth.password_validation <REPLACE_END> <REPLACE_OLD> password_validation
from <REPLACE_NEW> password_validators_help_texts
from <REPLACE_END> <REPLACE_OLD> help_text=password_validation.password_validators_help_text_html(),
<REPLACE_NEW> help_text=password... | Use plain password help text instead of html
from django.contrib.auth import password_validation
from django.utils.translation import ugettext_lazy as _
from rest_framework import serializers
class AuthenticationSerializer(serializers.Serializer):
username = serializers.CharField(label=_("Username"), write_only=... |
f8e800219ac2c2c76bb5ac10b2dfdac038edbb5d | circuits/tools/__init__.py | circuits/tools/__init__.py | # Module: __init__
# Date: 8th November 2008
# Author: James Mills, prologic at shortcircuit dot net dot au
"""Circuits Tools
circuits.tools contains a standard set of tools for circuits. These
tools are installed as executables with a prefix of "circuits."
"""
try:
from cStringIO import StringIO
except ImportE... | # Module: __init__
# Date: 8th November 2008
# Author: James Mills, prologic at shortcircuit dot net dot au
"""Circuits Tools
circuits.tools contains a standard set of tools for circuits. These
tools are installed as executables with a prefix of "circuits."
"""
def graph(x):
s = []
d = 0
i = 0
done... | Remove StringIO import. Use a simple list to build up the output and return .join(s) | tools: Remove StringIO import. Use a simple list to build up the output and return .join(s)
| Python | mit | treemo/circuits,eriol/circuits,eriol/circuits,treemo/circuits,treemo/circuits,nizox/circuits,eriol/circuits | <REPLACE_OLD> "circuits."
"""
try:
from cStringIO import StringIO
except ImportError:
from StringIO import StringIO
def <REPLACE_NEW> "circuits."
"""
def <REPLACE_END> <REPLACE_OLD> StringIO()
<REPLACE_NEW> []
<REPLACE_END> <REPLACE_OLD> s.write("%s%s\n" <REPLACE_NEW> s.append("%s%s\n" <REPLACE_END> <REP... | tools: Remove StringIO import. Use a simple list to build up the output and return .join(s)
# Module: __init__
# Date: 8th November 2008
# Author: James Mills, prologic at shortcircuit dot net dot au
"""Circuits Tools
circuits.tools contains a standard set of tools for circuits. These
tools are installed as executa... |
cb7dd3e7bf8fdc195fa0b37479efa61e0091fbec | migrations/versions/201702221443_fb7b6aa148e_delete_legacy_paper_tables.py | migrations/versions/201702221443_fb7b6aa148e_delete_legacy_paper_tables.py | """Delete legacy paper tables
Revision ID: fb7b6aa148e
Revises: 25d478c9d690
Create Date: 2017-02-22 14:43:34.952274
"""
import sqlalchemy as sa
from alembic import context, op
from indico.core.db.sqlalchemy import UTCDateTime, PyIntEnum
from indico.util.struct.enum import RichIntEnum
# revision identifiers, used b... | Add alembic revision to delete legacy paper tables | Add alembic revision to delete legacy paper tables
| Python | mit | pferreir/indico,ThiefMaster/indico,DirkHoffmann/indico,indico/indico,indico/indico,OmeGak/indico,mic4ael/indico,pferreir/indico,mic4ael/indico,OmeGak/indico,ThiefMaster/indico,mvidalgarcia/indico,ThiefMaster/indico,mic4ael/indico,indico/indico,DirkHoffmann/indico,OmeGak/indico,ThiefMaster/indico,DirkHoffmann/indico,mvi... | <REPLACE_OLD> <REPLACE_NEW> """Delete legacy paper tables
Revision ID: fb7b6aa148e
Revises: 25d478c9d690
Create Date: 2017-02-22 14:43:34.952274
"""
import sqlalchemy as sa
from alembic import context, op
from indico.core.db.sqlalchemy import UTCDateTime, PyIntEnum
from indico.util.struct.enum import RichIntEnum
#... | Add alembic revision to delete legacy paper tables
| |
e183578b6211d7311d62100ad643cbaf8408de99 | tests/__init__.py | tests/__init__.py | import unittest.mock
def _test_module_init(module, main_name="main"):
with unittest.mock.patch.object(module, main_name, return_value=0):
with unittest.mock.patch.object(module, "__name__", "__main__"):
with unittest.mock.patch.object(module.sys, "exit") as exit:
module.module_... | import unittest.mock
def _test_module_init(module, main_name="main"):
with unittest.mock.patch.object(
module, main_name, return_value=0
), unittest.mock.patch.object(
module, "__name__", "__main__"
), unittest.mock.patch.object(
module.sys, "exit"
) as exit:
module.mod... | Use multiple context managers on one with statement (thanks Anna) | Use multiple context managers on one with statement (thanks Anna)
| Python | mpl-2.0 | rfinnie/2ping,rfinnie/2ping | <REPLACE_OLD> unittest.mock.patch.object(module, main_name, return_value=0):
<REPLACE_NEW> unittest.mock.patch.object(
<REPLACE_END> <REPLACE_OLD> with unittest.mock.patch.object(module, "__name__", "__main__"):
<REPLACE_NEW> module, main_name, return_value=0
), unittest.mock.patch.object(
<REPLACE_END> <INSERT... | Use multiple context managers on one with statement (thanks Anna)
import unittest.mock
def _test_module_init(module, main_name="main"):
with unittest.mock.patch.object(module, main_name, return_value=0):
with unittest.mock.patch.object(module, "__name__", "__main__"):
with unittest.mock.patch... |
c75a244247988dbce68aa7985241712d8c94a24a | Lib/distutils/command/install_ext.py | Lib/distutils/command/install_ext.py | """install_ext
Implement the Distutils "install_ext" command to install extension modules."""
# created 1999/09/12, Greg Ward
__revision__ = "$Id$"
from distutils.core import Command
from distutils.util import copy_tree
class install_ext (Command):
description = "install C/C++ extension modules"
user... | """install_ext
Implement the Distutils "install_ext" command to install extension modules."""
# created 1999/09/12, Greg Ward
__revision__ = "$Id$"
from distutils.core import Command
from distutils.util import copy_tree
class install_ext (Command):
description = "install C/C++ extension modules"
user... | Fix how we set 'build_dir' and 'install_dir' options from 'install' options -- irrelevant because this file is about to go away, but oh well. | Fix how we set 'build_dir' and 'install_dir' options from 'install' options --
irrelevant because this file is about to go away, but oh well.
| Python | mit | sk-/python2.7-type-annotator,sk-/python2.7-type-annotator,sk-/python2.7-type-annotator | <REPLACE_OLD> ('build_platlib', <REPLACE_NEW> ('build_lib', <REPLACE_END> <REPLACE_OLD> ('install_platlib', <REPLACE_NEW> ('install_lib', <REPLACE_END> <|endoftext|> """install_ext
Implement the Distutils "install_ext" command to install extension modules."""
# created 1999/09/12, Greg Ward
__revision__ = "$Id$"
fr... | Fix how we set 'build_dir' and 'install_dir' options from 'install' options --
irrelevant because this file is about to go away, but oh well.
"""install_ext
Implement the Distutils "install_ext" command to install extension modules."""
# created 1999/09/12, Greg Ward
__revision__ = "$Id$"
from distutils.core impor... |
cad7bdca07f5ba979f14b11e6fd4109b1f7043c9 | terminate_instances.py | terminate_instances.py | s program terminate instances if proper tag is not used
"""
import time
import boto3
start_time = time.time()
ec2 = boto3.resource('ec2')
ec2_client = boto3.client('ec2')
tag_deparment = ['Finance', 'Marketing', 'HumanResources', 'Research'] # Your departments
shutdown_instance = False
for instance in ec2.instanc... | """
this program terminate instances if proper tag is not used
"""
import time
import boto3
start_time = time.time()
ec2 = boto3.resource('ec2')
ec2_client = boto3.client('ec2')
tag_deparment = ['Finance', 'Marketing', 'HumanResources', 'Research'] # Your departments
shutdown_instance = False
for instance in ec2.... | Terminate instances is not proper tag | Terminate instances is not proper tag
| Python | mit | gabrielrojasnyc/AWS | <REPLACE_OLD> s <REPLACE_NEW> """
this <REPLACE_END> <|endoftext|> """
this program terminate instances if proper tag is not used
"""
import time
import boto3
start_time = time.time()
ec2 = boto3.resource('ec2')
ec2_client = boto3.client('ec2')
tag_deparment = ['Finance', 'Marketing', 'HumanResources', 'Research'] ... | Terminate instances is not proper tag
s program terminate instances if proper tag is not used
"""
import time
import boto3
start_time = time.time()
ec2 = boto3.resource('ec2')
ec2_client = boto3.client('ec2')
tag_deparment = ['Finance', 'Marketing', 'HumanResources', 'Research'] # Your departments
shutdown_instanc... |
4551732c93b248e669b63d8ea6a9705c52b69dc3 | projects/urls.py | projects/urls.py | from django.conf.urls import patterns, url
urlpatterns = patterns('projects.views',
url(r'^add/$', 'add_project', name='add_project'),
url(r'^edit/(?P<project_id>\d+)/$', 'edit_project', name='edit_project'),
url(r'^status/(?P<project_id>\d+)/$', 'edit_status', name='edit_status'),
url(r'^archive/$', ... | from django.conf.urls import patterns, url
urlpatterns = patterns('projects.views',
url(r'^add/$', 'add_project', name='add_project'),
url(r'^edit/(?P<project_id>\d+)/$', 'edit_project', name='edit_project'),
url(r'^edit_status/(?P<project_id>\d+)/$', 'edit_status', name='edit_status'),
url(r'^status/... | Add url for project_status_edit option | Add url for project_status_edit option
| Python | mit | Hackfmi/Diaphanum,Hackfmi/Diaphanum | <INSERT> url(r'^edit_status/(?P<project_id>\d+)/$', 'edit_status', name='edit_status'),
<INSERT_END> <|endoftext|> from django.conf.urls import patterns, url
urlpatterns = patterns('projects.views',
url(r'^add/$', 'add_project', name='add_project'),
url(r'^edit/(?P<project_id>\d+)/$', 'edit_project', name... | Add url for project_status_edit option
from django.conf.urls import patterns, url
urlpatterns = patterns('projects.views',
url(r'^add/$', 'add_project', name='add_project'),
url(r'^edit/(?P<project_id>\d+)/$', 'edit_project', name='edit_project'),
url(r'^status/(?P<project_id>\d+)/$', 'edit_status', name... |
6c314451e002db3213ff61d1e6935c091b605a8d | server/nurly/util.py | server/nurly/util.py | import traceback
class NurlyResult():
def __init__(self, code='200 OK', head=None, body=''):
self.head = {} if type(head) != dict else head
self.body = body
self.code = code
class NurlyStatus():
ST_IDLE = 0
ST_BUSY = 1
ST_STOP = 2
ST_MAP = {
ST_IDLE: 'IDLE',
... | import traceback
import types
class NurlyResult():
def __init__(self, code='200 OK', head=None, body=''):
self.head = {} if type(head) != dict else head
self.body = body
self.code = code
class NurlyStatus():
ST_IDLE = 0
ST_BUSY = 1
ST_STOP = 2
ST_MAP = {
ST_IDLE: ... | Support using a module as a call back if it has an function attribute by the same name. | Support using a module as a call back if it has an function attribute by the same name.
| Python | mit | mk23/nurly,mk23/nurly,mk23/nurly,mk23/nurly | <REPLACE_OLD> traceback
class <REPLACE_NEW> traceback
import types
class <REPLACE_END> <REPLACE_OLD> func
<REPLACE_NEW> func if type(func) is not types.ModuleType else getattr(func, func.__name__.split('.')[-1])
<REPLACE_END> <|endoftext|> import traceback
import types
class NurlyResult():
def __init__(self, c... | Support using a module as a call back if it has an function attribute by the same name.
import traceback
class NurlyResult():
def __init__(self, code='200 OK', head=None, body=''):
self.head = {} if type(head) != dict else head
self.body = body
self.code = code
class NurlyStatus():
S... |
dcdaef9fb950a8082dcd46fc6a43c965b09f43b5 | places/views.py | places/views.py | from django.contrib.auth.mixins import LoginRequiredMixin
from django.http import HttpResponseRedirect
from django.urls import reverse
from django.views.generic import TemplateView, View
from django.views.generic.detail import DetailView
from django.views.generic.edit import UpdateView
from django.views.generic.list im... | from django.contrib.auth.mixins import LoginRequiredMixin
from django.http import HttpResponseRedirect
from django.urls import reverse
from django.views.generic import TemplateView, View
from django.views.generic.detail import DetailView
from django.views.generic.edit import UpdateView
from django.views.generic.list im... | Order restaurants by name in ListView | Order restaurants by name in ListView
| Python | mit | huangsam/chowist,huangsam/chowist,huangsam/chowist | <INSERT> ordering = ["name"]
<INSERT_END> <|endoftext|> from django.contrib.auth.mixins import LoginRequiredMixin
from django.http import HttpResponseRedirect
from django.urls import reverse
from django.views.generic import TemplateView, View
from django.views.generic.detail import DetailView
from django.views.gene... | Order restaurants by name in ListView
from django.contrib.auth.mixins import LoginRequiredMixin
from django.http import HttpResponseRedirect
from django.urls import reverse
from django.views.generic import TemplateView, View
from django.views.generic.detail import DetailView
from django.views.generic.edit import Updat... |
a134bdbe2677fdc5a9c7d6408ea021b8e981098b | qtawesome/tests/test_qtawesome.py | qtawesome/tests/test_qtawesome.py | r"""
Tests for QtAwesome.
"""
# Standard library imports
import sys
import subprocess
# Test Library imports
import pytest
# Local imports
import qtawesome as qta
from qtawesome.iconic_font import IconicFont
from PyQt5.QtWidgets import QApplication
def test_segfault_import():
output_number = subprocess.call('py... | r"""
Tests for QtAwesome.
"""
# Standard library imports
import sys
import subprocess
# Test Library imports
import pytest
# Local imports
import qtawesome as qta
from qtawesome.iconic_font import IconicFont
from PyQt5.QtWidgets import QApplication
def test_segfault_import():
output_number = subprocess.call('py... | Add more details in the test docstring. | Add more details in the test docstring.
| Python | mit | spyder-ide/qtawesome | <REPLACE_OLD> name.
<REPLACE_NEW> name. If this test
fails, this probably means that you need to rename the family name of
some fonts. Please see PR #98 for more details on why it is necessary and
on how to do this.
<REPLACE_END> <|endoftext|> r"""
Tests for QtAwesome.
"""
# Standard library imports
imp... | Add more details in the test docstring.
r"""
Tests for QtAwesome.
"""
# Standard library imports
import sys
import subprocess
# Test Library imports
import pytest
# Local imports
import qtawesome as qta
from qtawesome.iconic_font import IconicFont
from PyQt5.QtWidgets import QApplication
def test_segfault_import()... |
12b1e22a16551b3f7fb0e663e42f7d84f9882e2c | pkglib/tests/unit/test_pyinstall_unit.py | pkglib/tests/unit/test_pyinstall_unit.py | import os
import sys
import pytest
from mock import patch
import pytest
from pkglib.scripts import pyinstall
@pytest.mark.skipif('TRAVIS' in os.environ,
reason="Our monkey patch doesn't work with the version of setuptools on Travis. FIXME.")
def test_pyinstall_respects_i_flag():
"""Ensure th... | from __future__ import absolute_import
import os
import sys
import pytest
from mock import patch
from pkglib.scripts import pyinstall
from zc.buildout.easy_install import _get_index
def test_pyinstall_respects_i_flag():
"""Ensure that pyinstall allows us to override the PyPI URL with -i,
even if it's alrea... | Fix for the pyinstall unit test | Fix for the pyinstall unit test
| Python | mit | julietalucia/page-objects,manahl/pytest-plugins,manahl/pytest-plugins | <REPLACE_OLD> import <REPLACE_NEW> from __future__ import absolute_import
import <REPLACE_END> <REPLACE_OLD> patch
import pytest
from <REPLACE_NEW> patch
from <REPLACE_END> <REPLACE_OLD> pyinstall
@pytest.mark.skipif('TRAVIS' in os.environ,
reason="Our monkey patch doesn't work with the version... | Fix for the pyinstall unit test
import os
import sys
import pytest
from mock import patch
import pytest
from pkglib.scripts import pyinstall
@pytest.mark.skipif('TRAVIS' in os.environ,
reason="Our monkey patch doesn't work with the version of setuptools on Travis. FIXME.")
def test_pyinstall_re... |
c9f990ff4095b7fb361b2d59c0c5b2c9555643ff | csunplugged/tests/BaseTest.py | csunplugged/tests/BaseTest.py | """Base test class with methods implemented for Django testing."""
from django.test import TestCase
from django.contrib.auth.models import User
from django.test.client import Client
from django.utils.translation import activate
<<<<<<< HEAD
class BaseTest(SimpleTestCase):
"""Base test class with methods implemen... | """Base test class with methods implemented for Django testing."""
from django.test import TestCase
from django.contrib.auth.models import User
from django.test.client import Client
from django.utils.translation import activate
class BaseTest(SimpleTestCase):
"""Base test class with methods implemented for Djang... | Remove left over merge conflict text | Remove left over merge conflict text
| Python | mit | uccser/cs-unplugged,uccser/cs-unplugged,uccser/cs-unplugged,uccser/cs-unplugged | <REPLACE_OLD> activate
<<<<<<< HEAD
class <REPLACE_NEW> activate
class <REPLACE_END> <|endoftext|> """Base test class with methods implemented for Django testing."""
from django.test import TestCase
from django.contrib.auth.models import User
from django.test.client import Client
from django.utils.translation impo... | Remove left over merge conflict text
"""Base test class with methods implemented for Django testing."""
from django.test import TestCase
from django.contrib.auth.models import User
from django.test.client import Client
from django.utils.translation import activate
<<<<<<< HEAD
class BaseTest(SimpleTestCase):
""... |
bd68b6e44ec65ba8f1f0afeea3a1dce08f579690 | src/bots/chuck.py | src/bots/chuck.py | import re
import requests
import logging
from base import BaseBot
logger = logging.getLogger(__name__)
CHUCK_API_URL = 'http://api.icndb.com'
CHUCK_REGEX = re.compile(r'^!chuck')
def random_chuck_fact():
try:
fact = requests.get('%s/jokes/random' % CHUCK_API_URL.rstrip('/')).json()
return fact['... | import re
import requests
import logging
from base import BaseBot
from HTMLParser import HTMLParser
logger = logging.getLogger(__name__)
html_parser = HTMLParser()
CHUCK_API_URL = 'http://api.icndb.com'
CHUCK_REGEX = re.compile(r'^!chuck')
def random_chuck_fact():
try:
fact = requests.get('%s/jokes/rand... | Fix for html escaped characters | Fix for html escaped characters
| Python | mit | orangeblock/slack-bot | <REPLACE_OLD> BaseBot
logger = logging.getLogger(__name__)
CHUCK_API_URL <REPLACE_NEW> BaseBot
from HTMLParser import HTMLParser
logger = logging.getLogger(__name__)
html_parser = HTMLParser()
CHUCK_API_URL <REPLACE_END> <REPLACE_OLD> fact['value']['joke']
<REPLACE_NEW> html_parser.unescape(fact['value']['joke'])
... | Fix for html escaped characters
import re
import requests
import logging
from base import BaseBot
logger = logging.getLogger(__name__)
CHUCK_API_URL = 'http://api.icndb.com'
CHUCK_REGEX = re.compile(r'^!chuck')
def random_chuck_fact():
try:
fact = requests.get('%s/jokes/random' % CHUCK_API_URL.rstrip('... |
11d6bc9cbea154c7526c31c6cb4d88b102826cc9 | eloqua/endpoints_v2.py | eloqua/endpoints_v2.py | """
API MAPPING FOR Eloqua API V2
"""
mapping_table = {
'content_type': 'application/json',
'path_prefix': '/API/REST/2.0',
# Campaigns
'get_campaign': {
'method': 'GET',
'path': '/assets/campaign/{{campaign_id}}',
'valid_params': ['depth']
},
'list_campaigns': {
... | """
API MAPPING FOR Eloqua API V2
"""
mapping_table = {
'content_type': 'application/json',
'path_prefix': '/API/REST/2.0',
# Campaigns
'get_campaign': {
'method': 'GET',
'path': '/assets/campaign/{{campaign_id}}',
'valid_params': ['depth']
},
'list_campaigns': {
... | Add operation to update campaign. | Add operation to update campaign.
| Python | mit | alexcchan/eloqua | <REPLACE_OLD> ['activateNow','scheduledFor','runAsUserId']
<REPLACE_NEW> ['activateNow','scheduledFor','runAsUserId'],
'status': 201
<REPLACE_END> <|endoftext|> """
API MAPPING FOR Eloqua API V2
"""
mapping_table = {
'content_type': 'application/json',
'path_prefix': '/API/REST/2.0',
# Campaign... | Add operation to update campaign.
"""
API MAPPING FOR Eloqua API V2
"""
mapping_table = {
'content_type': 'application/json',
'path_prefix': '/API/REST/2.0',
# Campaigns
'get_campaign': {
'method': 'GET',
'path': '/assets/campaign/{{campaign_id}}',
'valid_params': ['depth']
... |
e9cca0d736cd388d4834e81ab6bf38ded6625b3d | pynmea2/types/proprietary/grm.py | pynmea2/types/proprietary/grm.py | # Garmin
from ... import nmea
class GRM(nmea.ProprietarySentence):
sentence_types = {}
def __new__(_cls, manufacturer, data):
name = manufacturer + data[0]
cls = _cls.sentence_types.get(name, _cls)
return super(GRM, cls).__new__(cls)
def __init__(self, manufacturer, d... | # Garmin
from decimal import Decimal
from ... import nmea
class GRM(nmea.ProprietarySentence):
sentence_types = {}
def __new__(_cls, manufacturer, data):
name = manufacturer + data[0]
cls = _cls.sentence_types.get(name, _cls)
return super(GRM, cls).__new__(cls)
def... | Add decimal types to Garmin PGRME fields. | Add decimal types to Garmin PGRME fields.
| Python | mit | silentquasar/pynmea2,Knio/pynmea2 | <INSERT> decimal import Decimal
from <INSERT_END> <REPLACE_OLD> "hpe"),
<REPLACE_NEW> "hpe", Decimal),
<REPLACE_END> <REPLACE_OLD> "vpe"),
<REPLACE_NEW> "vpe", Decimal),
<REPLACE_END> <REPLACE_OLD> "osepe"),
<REPLACE_NEW> "osepe", Decimal),
<REPLACE_END> <|endoftext|> # Garmin
from decimal import Deci... | Add decimal types to Garmin PGRME fields.
# Garmin
from ... import nmea
class GRM(nmea.ProprietarySentence):
sentence_types = {}
def __new__(_cls, manufacturer, data):
name = manufacturer + data[0]
cls = _cls.sentence_types.get(name, _cls)
return super(GRM, cls).__new__(cls... |
30bfdd3a6e31db6849f650406bc8014f836dda62 | yolk/__init__.py | yolk/__init__.py | """yolk.
Author: Rob Cakebread <cakebread at gmail>
License : BSD
"""
__version__ = '0.6.2'
| """yolk.
Author: Rob Cakebread <cakebread at gmail>
License : BSD
"""
__version__ = '0.7'
| Increment minor version to 0.7 | Increment minor version to 0.7
| Python | bsd-3-clause | myint/yolk,myint/yolk | <REPLACE_OLD> '0.6.2'
<REPLACE_NEW> '0.7'
<REPLACE_END> <|endoftext|> """yolk.
Author: Rob Cakebread <cakebread at gmail>
License : BSD
"""
__version__ = '0.7'
| Increment minor version to 0.7
"""yolk.
Author: Rob Cakebread <cakebread at gmail>
License : BSD
"""
__version__ = '0.6.2'
|
373f0f4637103d526c75cae304740e621ad3c39c | resize.py | resize.py | # -*- coding: utf-8 -*-
import cv2
import sys
import numpy as np
def resize(src, w_ratio, h_ratio):
height = src.shape[0]
width = src.shape[1]
dst = cv2.resize(src,(width/100*w_ratio,height/100*h_ratio))
return dst
if __name__ == '__main__':
param = sys.argv
if (len(param) != 4):
print... | # -*- coding: utf-8 -*-
import cv2
import sys
def resize(src, w_ratio, h_ratio):
height = src.shape[0]
width = src.shape[1]
dst = cv2.resize(src,((int)(width/100*w_ratio),(int)(height/100*h_ratio)))
return dst
if __name__ == '__main__':
param = sys.argv
if (len(param) != 4):
print ("Us... | Fix bug and delete unused library | Fix bug and delete unused library
| Python | mit | karaage0703/python-image-processing,karaage0703/python-image-processing | <REPLACE_OLD> sys
import numpy as np
def <REPLACE_NEW> sys
def <REPLACE_END> <REPLACE_OLD> cv2.resize(src,(width/100*w_ratio,height/100*h_ratio))
<REPLACE_NEW> cv2.resize(src,((int)(width/100*w_ratio),(int)(height/100*h_ratio)))
<REPLACE_END> <|endoftext|> # -*- coding: utf-8 -*-
import cv2
import sys
def resize(s... | Fix bug and delete unused library
# -*- coding: utf-8 -*-
import cv2
import sys
import numpy as np
def resize(src, w_ratio, h_ratio):
height = src.shape[0]
width = src.shape[1]
dst = cv2.resize(src,(width/100*w_ratio,height/100*h_ratio))
return dst
if __name__ == '__main__':
param = sys.argv
... |
4b488c8d0842bb25c719fcd93ee0ae46978b5680 | meta/util.py | meta/util.py | import os
import sys
import time
import math
from contextlib import contextmanager
@contextmanager
def timeit_msg(msg):
print '{}...'.format(msg),
sys.stdout.flush()
start = time.time()
yield
stop = time.time()
print ' ({:1.3f} s)'.format((stop-start))
def get_file_size(fname):
fstats = os.stat(fname)
size ... | import os
import sys
import time
import math
import sqlite3
from contextlib import contextmanager
import meta
@contextmanager
def timeit_msg(msg):
print '{}...'.format(msg),
sys.stdout.flush()
start = time.time()
yield
stop = time.time()
print ' ({:1.3f} s)'.format((stop-start))
def get_file_size(fname):
fs... | Add support for connecting to NCBI database | Add support for connecting to NCBI database
| Python | mit | abulovic/pgnd-meta | <REPLACE_OLD> math
from <REPLACE_NEW> math
import sqlite3
from <REPLACE_END> <REPLACE_OLD> contextmanager
@contextmanager
def <REPLACE_NEW> contextmanager
import meta
@contextmanager
def <REPLACE_END> <REPLACE_OLD> res)
<REPLACE_NEW> res)
def get_ncbi_db_conn():
dbfile = os.path.join(meta.__path__[0], 'data', '... | Add support for connecting to NCBI database
import os
import sys
import time
import math
from contextlib import contextmanager
@contextmanager
def timeit_msg(msg):
print '{}...'.format(msg),
sys.stdout.flush()
start = time.time()
yield
stop = time.time()
print ' ({:1.3f} s)'.format((stop-start))
def get_file... |
de2b4fca41de35df72a30cc7269f2bc8c0d083ea | setup.py | setup.py | from setuptools import setup
setup(
name='kibana',
version='0.1',
description='Kibana configuration index (.kibana in v4) command line interface and python API (visualization import/export and mappings refresh)',
author='Ryan Farley',
author_email='rfarley@mitre.org',
packages=['kibana'],
i... | from setuptools import setup
setup(
name='kibana',
version='0.1',
description='Kibana configuration index (.kibana in v4) command line interface and python API (visualization import/export and mappings refresh)',
author='Ryan Farley',
author_email='rfarley@mitre.org',
packages=['kibana'],
i... | Add argparse, requests install reqs | Add argparse, requests install reqs
| Python | mit | rfarley3/Kibana | <INSERT> 'argparse',
'requests',
<INSERT_END> <|endoftext|> from setuptools import setup
setup(
name='kibana',
version='0.1',
description='Kibana configuration index (.kibana in v4) command line interface and python API (visualization import/export and mappings refresh)',
author='Ryan F... | Add argparse, requests install reqs
from setuptools import setup
setup(
name='kibana',
version='0.1',
description='Kibana configuration index (.kibana in v4) command line interface and python API (visualization import/export and mappings refresh)',
author='Ryan Farley',
author_email='rfarley@mitre... |
9e900eb16e92027cfe990a07c5703a6adbb41a09 | drivers/python/wappalyzer.py | drivers/python/wappalyzer.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
import PyV8
import urllib
from urlparse import urlparse
try:
import json
except ImportError:
import simplejson as json
class Wappalyzer(object):
def __init__(self, url):
self.file_dir = os.path.dirname(__file__)
f = ope... | Add python driver (depend on PyV8) | Add python driver (depend on PyV8)
| Python | mit | WPO-Foundation/Wappalyzer,WPO-Foundation/Wappalyzer,WPO-Foundation/Wappalyzer,AliasIO/wappalyzer,AliasIO/wappalyzer | <REPLACE_OLD> <REPLACE_NEW> #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
import PyV8
import urllib
from urlparse import urlparse
try:
import json
except ImportError:
import simplejson as json
class Wappalyzer(object):
def __init__(self, url):
self.file_dir = os.path.dirna... | Add python driver (depend on PyV8)
| |
6be8e85b17d390abea25897bd7a2703fb3300261 | app.py | app.py | import logging
import os
import tornado.ioloop
import tornado.log
import tornado.web
def configure_tornado_logging():
fh = logging.handlers.RotatingFileHandler(
'/var/log/ipborg/tornado.log', maxBytes=2**29, backupCount=10)
fmt = logging.Formatter('%(asctime)s:%(levelname)s:%(name)s:%(message)s')
... | import logging
import os
import tornado.ioloop
import tornado.log
import tornado.options
import tornado.web
tornado.options.define('tornado_log_file',
default='/var/log/ipborg/torando.log',
type=str)
tornado.options.define('app_log_file',
default='... | Add Tornado settings and log location command line options. | Add Tornado settings and log location command line options.
| Python | mit | jiffyclub/ipythonblocks.org,jiffyclub/ipythonblocks.org | <REPLACE_OLD> tornado.web
def <REPLACE_NEW> tornado.options
import tornado.web
tornado.options.define('tornado_log_file',
default='/var/log/ipborg/torando.log',
type=str)
tornado.options.define('app_log_file',
default='/var/log/ipborg/app.log',
... | Add Tornado settings and log location command line options.
import logging
import os
import tornado.ioloop
import tornado.log
import tornado.web
def configure_tornado_logging():
fh = logging.handlers.RotatingFileHandler(
'/var/log/ipborg/tornado.log', maxBytes=2**29, backupCount=10)
fmt = logging.F... |
a4825083c9a18fe8665d750bfad00a9d6fa40944 | tartpy/eventloop.py | tartpy/eventloop.py | """
Very basic implementation of an event loop
==========================================
The eventloop is a singleton to schedule and run events.
Exports
-------
- ``EventLoop``: the basic eventloop
"""
import queue
import threading
import time
from .singleton import Singleton
class EventLoop(object, metaclas... | """
Very basic implementation of an event loop
==========================================
The eventloop is a singleton to schedule and run events.
Exports
-------
- ``EventLoop``: the basic eventloop
"""
import queue
import sched
import threading
import time
from .singleton import Singleton
class EventLoop(obj... | Use Python scheduler rather than the home-made one | Use Python scheduler rather than the home-made one | Python | mit | waltermoreira/tartpy | <INSERT> sched
import <INSERT_END> <REPLACE_OLD> self.queue <REPLACE_NEW> self.scheduler <REPLACE_END> <REPLACE_OLD> queue.Queue()
<REPLACE_NEW> sched.scheduler()
<REPLACE_END> <REPLACE_OLD> self.queue.put(event)
<REPLACE_NEW> self.scheduler.enter(0, 1, event)
<REPLACE_END> <DELETE> run_step(self, block=True):
... | Use Python scheduler rather than the home-made one
"""
Very basic implementation of an event loop
==========================================
The eventloop is a singleton to schedule and run events.
Exports
-------
- ``EventLoop``: the basic eventloop
"""
import queue
import threading
import time
from .singleton ... |
ee5bd327bb3070277c87a96f72ca7e019c92f777 | publisher/build_paper.py | publisher/build_paper.py | #!/usr/bin/env python
import docutils.core as dc
from writer import writer
import os.path
import sys
import glob
preamble = '\n'.join([r'% PDF Standard Fonts',
r'\usepackage{mathptmx}',
r'\usepackage[scaled=.80]{helvet}',
r'\usepackage{courier}'],)
... | #!/usr/bin/env python
import docutils.core as dc
from writer import writer
import os.path
import sys
import glob
preamble = r'''
% These preamble commands are from build_paper.py
% PDF Standard Fonts
\usepackage{mathptmx}
\usepackage[scaled=.90]{helvet}
\usepackage{courier}
% Make verbatim environment smaller
\ma... | Update preamble: no indent on quote, smaller verbatim font size. | Update preamble: no indent on quote, smaller verbatim font size.
| Python | bsd-2-clause | dotsdl/scipy_proceedings,sbenthall/scipy_proceedings,juhasch/euroscipy_proceedings,chendaniely/scipy_proceedings,springcoil/euroscipy_proceedings,euroscipy/euroscipy_proceedings,mjklemm/euroscipy_proceedings,mikaem/euroscipy_proceedings,SepidehAlassi/euroscipy_proceedings,sbenthall/scipy_proceedings,katyhuff/scipy_proc... | <REPLACE_OLD> '\n'.join([r'% <REPLACE_NEW> r'''
% These preamble commands are from build_paper.py
% <REPLACE_END> <REPLACE_OLD> Fonts',
r'\usepackage{mathptmx}',
r'\usepackage[scaled=.80]{helvet}',
r'\usepackage{courier}'],)
settings <REPLACE_NEW> Font... | Update preamble: no indent on quote, smaller verbatim font size.
#!/usr/bin/env python
import docutils.core as dc
from writer import writer
import os.path
import sys
import glob
preamble = '\n'.join([r'% PDF Standard Fonts',
r'\usepackage{mathptmx}',
r'\usepackage[scaled... |
5f1f1145d4f01f4b30e8782d284feb44781c21ad | tests/cupyx_tests/scipy_tests/special_tests/test_ufunc_dispatch.py | tests/cupyx_tests/scipy_tests/special_tests/test_ufunc_dispatch.py | import numpy
import cupy
import scipy.special
import cupyx.scipy.special
from cupy import testing
import pytest
scipy_ufuncs = {
f
for f in scipy.special.__all__
if isinstance(getattr(scipy.special, f), numpy.ufunc)
}
cupyx_scipy_ufuncs = {
f
for f in dir(cupyx.scipy.special)
if isinstance(get... | import numpy
import cupy
import scipy.special
import cupyx.scipy.special
from cupy import testing
import pytest
scipy_ufuncs = {
f
for f in scipy.special.__all__
if isinstance(getattr(scipy.special, f), numpy.ufunc)
}
cupyx_scipy_ufuncs = {
f
for f in dir(cupyx.scipy.special)
if isinstance(get... | Use sorted on the set to parametrize tests so that pytest-xdist works | Use sorted on the set to parametrize tests so that pytest-xdist works
| Python | mit | cupy/cupy,cupy/cupy,cupy/cupy,cupy/cupy | <REPLACE_OLD> cupy.ufunc)
}
@testing.gpu
@testing.with_requires("scipy")
@pytest.mark.parametrize("ufunc", cupyx_scipy_ufuncs <REPLACE_NEW> cupy.ufunc)
}
@testing.gpu
@testing.with_requires("scipy")
@pytest.mark.parametrize("ufunc", sorted(cupyx_scipy_ufuncs <REPLACE_END> <REPLACE_OLD> scipy_ufuncs)
class <REPLACE_N... | Use sorted on the set to parametrize tests so that pytest-xdist works
import numpy
import cupy
import scipy.special
import cupyx.scipy.special
from cupy import testing
import pytest
scipy_ufuncs = {
f
for f in scipy.special.__all__
if isinstance(getattr(scipy.special, f), numpy.ufunc)
}
cupyx_scipy_ufunc... |
a3f5e1338cc84c60b867fc04175253f7ab460912 | relay_api/api/backend.py | relay_api/api/backend.py | import json
from relay_api.core.relay import relay
from relay_api.conf.config import relays
def init_relays():
for r in relays:
relays[r]["object"] = relay(relays[r]["gpio"])
relays[r]["state"] = relays[r]["object"].get_state()
def get_all_relays():
relays_dict = __get_relay_dict()
retur... | import json
from relay_api.core.relay import relay
from relay_api.conf.config import relays
def init_relays():
for r in relays:
relays[r]["object"] = relay(relays[r]["gpio"])
relays[r]["state"] = relays[r]["object"].get_state()
def get_all_relays():
relays_dict = __get_relay_dict()
retur... | Add indent in json to improve debugging | Add indent in json to improve debugging
| Python | mit | pahumadad/raspi-relay-api | <REPLACE_OLD> json.dumps(relays_dict)
def <REPLACE_NEW> json.dumps(relays_dict, indent=4)
def <REPLACE_END> <REPLACE_OLD> json.dumps(relay_dict)
def <REPLACE_NEW> json.dumps(relay_dict, indent=4)
def <REPLACE_END> <|endoftext|> import json
from relay_api.core.relay import relay
from relay_api.conf.config import... | Add indent in json to improve debugging
import json
from relay_api.core.relay import relay
from relay_api.conf.config import relays
def init_relays():
for r in relays:
relays[r]["object"] = relay(relays[r]["gpio"])
relays[r]["state"] = relays[r]["object"].get_state()
def get_all_relays():
r... |
0dbc2613fc686471be214ef69f245bc279a7e660 | http_ping.py | http_ping.py | from locust import HttpLocust, TaskSet, task
class HttpPingTasks(TaskSet):
@task
def ping(self):
self.client.get("/")
class SayHelloLocust(HttpLocust):
task_set = HttpPingTasks
min_wait = 100
max_wait = 500
| Add simple pinger for basic locust demo | Add simple pinger for basic locust demo
| Python | apache-2.0 | drednout/locust_on_meetup | <INSERT> from locust import HttpLocust, TaskSet, task
class HttpPingTasks(TaskSet):
<INSERT_END> <INSERT> @task
def ping(self):
self.client.get("/")
class SayHelloLocust(HttpLocust):
task_set = HttpPingTasks
min_wait = 100
max_wait = 500
<INSERT_END> <|endoftext|> from locust import HttpLo... | Add simple pinger for basic locust demo
| |
c6f36b517c294d368a7bc75dc359ab32b5917228 | setup.py | setup.py | from setuptools import setup
setup(
name='django-waffle',
version='0.7',
description='A feature flipper for Django.',
long_description=open('README.rst').read(),
author='James Socol',
author_email='james.socol@gmail.com',
url='http://github.com/jsocol/django-waffle',
license='BSD',
... | from setuptools import setup, find_packages
setup(
name='django-waffle',
version='0.7.1',
description='A feature flipper for Django.',
long_description=open('README.rst').read(),
author='James Socol',
author_email='james.socol@gmail.com',
url='http://github.com/jsocol/django-waffle',
li... | Switch to find_packages. Bump for PyPI. | Switch to find_packages. Bump for PyPI.
| Python | bsd-3-clause | ilanbm/django-waffle,JeLoueMonCampingCar/django-waffle,ilanbm/django-waffle,isotoma/django-waffle,ilanbm/django-waffle,groovecoder/django-waffle,rsalmaso/django-waffle,mark-adams/django-waffle,JeLoueMonCampingCar/django-waffle,rodgomes/django-waffle,TwigWorld/django-waffle,webus/django-waffle,paulcwatts/django-waffle,e... | <REPLACE_OLD> setup
setup(
<REPLACE_NEW> setup, find_packages
setup(
<REPLACE_END> <REPLACE_OLD> version='0.7',
<REPLACE_NEW> version='0.7.1',
<REPLACE_END> <REPLACE_OLD> packages=['waffle', 'waffle.templatetags'],
<REPLACE_NEW> packages=find_packages(exclude=['test_app']),
<REPLACE_END> <|endoftext|> from setu... | Switch to find_packages. Bump for PyPI.
from setuptools import setup
setup(
name='django-waffle',
version='0.7',
description='A feature flipper for Django.',
long_description=open('README.rst').read(),
author='James Socol',
author_email='james.socol@gmail.com',
url='http://github.com/jsoco... |
aa436864f53a4c77b4869baabfb1478d7fea36f0 | tests/products/__init__.py | tests/products/__init__.py | """ Test utilities for ensuring the correctness of products
"""
import arrow
import six
from tilezilla.core import BoundingBox, Band
MAPPING = {
'timeseries_id': str,
'acquired': arrow.Arrow,
'processed': arrow.Arrow,
'platform': str,
'instrument': str,
'bounds': BoundingBox,
'bands': [Ba... | """ Test utilities for ensuring the correctness of products
"""
import arrow
import six
from tilezilla.core import BoundingBox, Band
MAPPING = {
'timeseries_id': six.string_types,
'acquired': arrow.Arrow,
'processed': arrow.Arrow,
'platform': six.string_types,
'instrument': six.string_types,
... | Allow str type comparison in py2/3 | Allow str type comparison in py2/3
| Python | bsd-3-clause | ceholden/landsat_tile,ceholden/landsat_tiles,ceholden/landsat_tiles,ceholden/tilezilla,ceholden/landsat_tile | <REPLACE_OLD> str,
<REPLACE_NEW> six.string_types,
<REPLACE_END> <REPLACE_OLD> str,
<REPLACE_NEW> six.string_types,
<REPLACE_END> <REPLACE_OLD> str,
<REPLACE_NEW> six.string_types,
<REPLACE_END> <REPLACE_OLD> type):
<REPLACE_NEW> (type, tuple)):
# Type declaration one or more types
<REPLACE_END> <IN... | Allow str type comparison in py2/3
""" Test utilities for ensuring the correctness of products
"""
import arrow
import six
from tilezilla.core import BoundingBox, Band
MAPPING = {
'timeseries_id': str,
'acquired': arrow.Arrow,
'processed': arrow.Arrow,
'platform': str,
'instrument': str,
'bo... |
fb3ae8739dc5af77c91660e10e2370ad6df05787 | addisonarches/sequences/stripeyhole/interludes.py | addisonarches/sequences/stripeyhole/interludes.py | #!/usr/bin/env python
# -*- encoding: UTF-8 -*-
# This file is part of Addison Arches.
#
# Addison Arches is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at you... | #!/usr/bin/env python
# -*- encoding: UTF-8 -*-
# This file is part of Addison Arches.
#
# Addison Arches is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at you... | Stop interlude removes non-player characters. | Stop interlude removes non-player characters.
| Python | agpl-3.0 | tundish/addisonarches,tundish/addisonarches,tundish/addisonarches | <REPLACE_OLD> <http://www.gnu.org/licenses/>.
async <REPLACE_NEW> <http://www.gnu.org/licenses/>.
from turberfield.dialogue.types import Player
async <REPLACE_END> <REPLACE_OLD> ensemble, <REPLACE_NEW> ensemble:list, <REPLACE_END> <REPLACE_OLD> ensemble, <REPLACE_NEW> ensemble:list, <REPLACE_END> <INSERT> for entity... | Stop interlude removes non-player characters.
#!/usr/bin/env python
# -*- encoding: UTF-8 -*-
# This file is part of Addison Arches.
#
# Addison Arches is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation... |
c2731d22adbf2abc29d73f5759d5d9f0fa124f5f | tests/fixtures.py | tests/fixtures.py | from . import uuid
def task_crud(self, shotgun, trigger_poll=lambda: None):
name = uuid(8)
a = shotgun.create('Task', {'content': name})
trigger_poll()
b = self.cached.find_one('Task', [('id', 'is', a['id'])], ['content'])
self.assertSameEntity(a, b)
name += '-2'
shotgun.update('Task', a... | from . import uuid
def task_crud(self, shotgun, trigger_poll=lambda: None):
shot_name = uuid(8)
shot = shotgun.create('Shot', {'code': shot_name})
name = uuid(8)
task = shotgun.create('Task', {'content': name, 'entity': shot})
trigger_poll()
x = self.cached.find_one('Task', [('id', 'is', ta... | Add entity link to basic crud tests | Add entity link to basic crud tests
| Python | bsd-3-clause | westernx/sgcache,westernx/sgcache | <INSERT> shot_name = uuid(8)
shot = shotgun.create('Shot', {'code': shot_name})
<INSERT_END> <REPLACE_OLD> a <REPLACE_NEW> task <REPLACE_END> <REPLACE_OLD> name})
<REPLACE_NEW> name, 'entity': shot})
<REPLACE_END> <REPLACE_OLD> trigger_poll()
<REPLACE_NEW> trigger_poll()
<REPLACE_END> <REPLACE_OLD> b <REP... | Add entity link to basic crud tests
from . import uuid
def task_crud(self, shotgun, trigger_poll=lambda: None):
name = uuid(8)
a = shotgun.create('Task', {'content': name})
trigger_poll()
b = self.cached.find_one('Task', [('id', 'is', a['id'])], ['content'])
self.assertSameEntity(a, b)
name... |
c848a5a1d94da7919b3272e9e0ee9748091ba04a | md/data/__init__.py | md/data/__init__.py | DEFAULT_URL = "https://s3-us-west-2.amazonaws.com/openpolicingdata/Maryland-Traffic-Stop-Data-2013.zip" # noqa
DATASET_BASENAME = 'PIALog_16-0806'
# DATASET_BASENAME = 'Small-0806'
| DEFAULT_URL = 'https://s3-us-west-2.amazonaws.com/openpolicingdata/PIALog_16-0806.zip' # noqa
DATASET_BASENAME = 'PIALog_16-0806'
# DATASET_BASENAME = 'Small-0806'
| Fix URL to current MD dataset on S3 | Fix URL to current MD dataset on S3
| Python | mit | OpenDataPolicingNC/Traffic-Stops,OpenDataPolicingNC/Traffic-Stops,OpenDataPolicingNC/Traffic-Stops,OpenDataPolicingNC/Traffic-Stops | <REPLACE_OLD> "https://s3-us-west-2.amazonaws.com/openpolicingdata/Maryland-Traffic-Stop-Data-2013.zip" <REPLACE_NEW> 'https://s3-us-west-2.amazonaws.com/openpolicingdata/PIALog_16-0806.zip' <REPLACE_END> <|endoftext|> DEFAULT_URL = 'https://s3-us-west-2.amazonaws.com/openpolicingdata/PIALog_16-0806.zip' # noqa
DATASE... | Fix URL to current MD dataset on S3
DEFAULT_URL = "https://s3-us-west-2.amazonaws.com/openpolicingdata/Maryland-Traffic-Stop-Data-2013.zip" # noqa
DATASET_BASENAME = 'PIALog_16-0806'
# DATASET_BASENAME = 'Small-0806'
|
f1bdcde329b5b03e453f193720066914c908d46d | api/schemas.py | api/schemas.py | import marshmallow
class StorySchema(marshmallow.Schema):
id = marshmallow.fields.Int(dump_only=True)
title = marshmallow.fields.Str(required=True)
created = marshmallow.fields.DateTime(dump_only=True)
event_time = marshmallow.fields.DateTime(allow_none=True)
location = marshmallow.fields.Str()
... | import marshmallow
class StorySchema(marshmallow.Schema):
id = marshmallow.fields.Int(dump_only=True)
title = marshmallow.fields.Str(required=True)
created = marshmallow.fields.DateTime(dump_only=True)
event_time = marshmallow.fields.DateTime(allow_none=True)
location = marshmallow.fields.Str(allo... | Allow story location and section to be null | Allow story location and section to be null
| Python | mit | thepoly/Pipeline,thepoly/Pipeline,thepoly/Pipeline,thepoly/Pipeline,thepoly/Pipeline | <REPLACE_OLD> marshmallow.fields.Str()
<REPLACE_NEW> marshmallow.fields.Str(allow_none=True)
<REPLACE_END> <REPLACE_OLD> marshmallow.fields.Str()
<REPLACE_NEW> marshmallow.fields.Str(allow_none=True)
<REPLACE_END> <|endoftext|> import marshmallow
class StorySchema(marshmallow.Schema):
id = marshmallow.field... | Allow story location and section to be null
import marshmallow
class StorySchema(marshmallow.Schema):
id = marshmallow.fields.Int(dump_only=True)
title = marshmallow.fields.Str(required=True)
created = marshmallow.fields.DateTime(dump_only=True)
event_time = marshmallow.fields.DateTime(allow_none=Tru... |
7e44a8bd38105144111624710819a1ee54891222 | campos_checkin/__openerp__.py | campos_checkin/__openerp__.py | # -*- coding: utf-8 -*-
# Copyright 2017 Stein & Gabelgaard ApS
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
{
'name': 'Campos Checkin',
'description': """
CampOS Check In functionality""",
'version': '8.0.1.0.0',
'license': 'AGPL-3',
'author': 'Stein & Gabelgaard ApS',
... | # -*- coding: utf-8 -*-
# Copyright 2017 Stein & Gabelgaard ApS
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
{
'name': 'Campos Checkin',
'description': """
CampOS Check In functionality""",
'version': '8.0.1.0.0',
'license': 'AGPL-3',
'author': 'Stein & Gabelgaard ApS',
... | Fix order for menu ref | Fix order for menu ref | Python | agpl-3.0 | sl2017/campos | <DELETE> 'wizards/campos_checkin_grp_wiz.xml',
'views/event_registration.xml',
<DELETE_END> <INSERT> 'wizards/campos_checkin_grp_wiz.xml',
'views/event_registration.xml',
<INSERT_END> <|endoftext|> # -*- coding: utf-8 -*-
# Copyright 2017 Stein & Gabelgaard ApS
# License AGPL-3.0 or late... | Fix order for menu ref
# -*- coding: utf-8 -*-
# Copyright 2017 Stein & Gabelgaard ApS
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
{
'name': 'Campos Checkin',
'description': """
CampOS Check In functionality""",
'version': '8.0.1.0.0',
'license': 'AGPL-3',
'author': 'Ste... |
85be415a27d23951f5ee943710ea3d22571aa697 | mollie/api/objects/list.py | mollie/api/objects/list.py | from .base import Base
class List(Base):
current = None
def __init__(self, result, object_type):
Base.__init__(self, result)
self.object_type = object_type
def get_object_name(self):
return self.object_type.__name__.lower() + 's'
def __iter__(self):
"""Implement iter... | from .base import Base
class List(Base):
current = None
def __init__(self, result, object_type):
Base.__init__(self, result)
self.object_type = object_type
def get_object_name(self):
return self.object_type.__name__.lower() + 's'
def __iter__(self):
"""Implement iter... | Add proxy method for python2 iterator support | Add proxy method for python2 iterator support
| Python | bsd-2-clause | mollie/mollie-api-python | <INSERT> next = __next__ # support python2 iterator interface
<INSERT_END> <|endoftext|> from .base import Base
class List(Base):
current = None
def __init__(self, result, object_type):
Base.__init__(self, result)
self.object_type = object_type
def get_object_name(self):
re... | Add proxy method for python2 iterator support
from .base import Base
class List(Base):
current = None
def __init__(self, result, object_type):
Base.__init__(self, result)
self.object_type = object_type
def get_object_name(self):
return self.object_type.__name__.lower() + 's'
... |
4848baf76e4972401530b624816ba48cb08d9398 | appconf/utils.py | appconf/utils.py | import sys
def import_attribute(import_path, exception_handler=None):
from django.utils.importlib import import_module
module_name, object_name = import_path.rsplit('.', 1)
try:
module = import_module(module_name)
except: # pragma: no cover
if callable(exception_handler):
... | import sys
def import_attribute(import_path, exception_handler=None):
try:
from importlib import import_module
except ImportError:
from django.utils.importlib import import_module
module_name, object_name = import_path.rsplit('.', 1)
try:
module = import_module(module_name)
... | Use import_module from standard library if exists | Use import_module from standard library if exists
Django 1.8+ drops `django.utils.importlib`. I imagine because that is because an older version of Python (either 2.5 and/or 2.6) is being dropped. I haven't checked older versions but `importlib` exists in Python 2.7. | Python | bsd-3-clause | diox/django-appconf,carltongibson/django-appconf,django-compressor/django-appconf,jezdez/django-appconf,jessehon/django-appconf,treyhunner/django-appconf,jezdez-archive/django-appconf | <INSERT> try:
from importlib import import_module
except ImportError:
<INSERT_END> <|endoftext|> import sys
def import_attribute(import_path, exception_handler=None):
try:
from importlib import import_module
except ImportError:
from django.utils.importlib import import_modu... | Use import_module from standard library if exists
Django 1.8+ drops `django.utils.importlib`. I imagine because that is because an older version of Python (either 2.5 and/or 2.6) is being dropped. I haven't checked older versions but `importlib` exists in Python 2.7.
import sys
def import_attribute(import_path, exce... |
7ca17e79f8c3dba7bc04377e7746a383a281562d | serverless_helpers/__init__.py | serverless_helpers/__init__.py | # -*- coding: utf-8 -*-
# MIT Licensed, Copyright (c) 2016 Ryan Scott Brown <sb@ryansb.com>
import dotenv
| # -*- coding: utf-8 -*-
# MIT Licensed, Copyright (c) 2016 Ryan Scott Brown <sb@ryansb.com>
from dotenv import load_dotenv, get_key, set_key, unset_key
def load_envs(path):
import os
path, _ = os.path.split(path)
if path == '/':
# bail out when you reach top of the FS
load_dotenv(os.path.j... | Add `load_envs` to take a base path and recurse up, looking for .envs | Add `load_envs` to take a base path and recurse up, looking for .envs
| Python | mit | serverless/serverless-helpers-py | <REPLACE_OLD> <sb@ryansb.com>
import dotenv
<REPLACE_NEW> <sb@ryansb.com>
from dotenv import load_dotenv, get_key, set_key, unset_key
def load_envs(path):
import os
path, _ = os.path.split(path)
if path == '/':
# bail out when you reach top of the FS
load_dotenv(os.path.join(path, '.env'... | Add `load_envs` to take a base path and recurse up, looking for .envs
# -*- coding: utf-8 -*-
# MIT Licensed, Copyright (c) 2016 Ryan Scott Brown <sb@ryansb.com>
import dotenv
|
28b067ab7fc7385ac5462eb6c9f9371cef9eb496 | ritter/dataprocessors/annotators.py | ritter/dataprocessors/annotators.py | import re
class ArtifactAnnotator:
def linkify_artifacts(marked_tree, artifacts):
big_string = ArtifactAnnotator._marked_tree_to_big_string(marked_tree)
for artifact in artifacts:
link = '(%s "GHOSTDOC-TOKEN")' % artifact['_id']
for token in artifact['tokens']:
... | import re
class ArtifactAnnotator:
excluded_types = set(['heading', 'code'])
def linkify_artifacts(marked_tree, artifacts):
big_string = ArtifactAnnotator._marked_tree_to_big_string(marked_tree)
for artifact in artifacts:
link = '(%s "GHOSTDOC-TOKEN")' % artifact['_id']
... | Improve annotating of code segements | feat: Improve annotating of code segements
| Python | mit | ErikGartner/ghostdoc-ritter | <REPLACE_OLD> ArtifactAnnotator:
<REPLACE_NEW> ArtifactAnnotator:
excluded_types = set(['heading', 'code'])
<REPLACE_END> <REPLACE_OLD> != 'heading' and item[
'type'] != 'code':
<REPLACE_NEW> not in ArtifactAnnotator.excluded_types:
<REPLACE_END> <REPLACE_OLD> != 'heading' and item[
... | feat: Improve annotating of code segements
import re
class ArtifactAnnotator:
def linkify_artifacts(marked_tree, artifacts):
big_string = ArtifactAnnotator._marked_tree_to_big_string(marked_tree)
for artifact in artifacts:
link = '(%s "GHOSTDOC-TOKEN")' % artifact['_id']
... |
e60550b894e882abb4be0ff8b69b33fd8596c35e | docs/conf.py | docs/conf.py | from pathlib import Path
extensions = [
'sphinx.ext.autodoc', 'sphinx.ext.intersphinx', 'sphinx.ext.coverage']
master_doc = 'index'
project = 'cairocffi'
copyright = '2013-2019, Simon Sapin'
release = (Path(__file__).parent / 'cairocffi' / 'VERSION').read_text().strip()
version = '.'.join(release.split('.')[:2])
e... | from pathlib import Path
extensions = [
'sphinx.ext.autodoc', 'sphinx.ext.intersphinx', 'sphinx.ext.coverage']
master_doc = 'index'
project = 'cairocffi'
copyright = '2013-2019, Simon Sapin'
release = (
Path(__file__).parent.parent / 'cairocffi' / 'VERSION').read_text().strip()
version = '.'.join(release.split... | Fix the VERSION path for doc | Fix the VERSION path for doc
| Python | bsd-3-clause | SimonSapin/cairocffi | <REPLACE_OLD> (Path(__file__).parent <REPLACE_NEW> (
Path(__file__).parent.parent <REPLACE_END> <|endoftext|> from pathlib import Path
extensions = [
'sphinx.ext.autodoc', 'sphinx.ext.intersphinx', 'sphinx.ext.coverage']
master_doc = 'index'
project = 'cairocffi'
copyright = '2013-2019, Simon Sapin'
release = ... | Fix the VERSION path for doc
from pathlib import Path
extensions = [
'sphinx.ext.autodoc', 'sphinx.ext.intersphinx', 'sphinx.ext.coverage']
master_doc = 'index'
project = 'cairocffi'
copyright = '2013-2019, Simon Sapin'
release = (Path(__file__).parent / 'cairocffi' / 'VERSION').read_text().strip()
version = '.'.... |
8631a61b9b243e5c1724fb2df06f33b1400fb59e | tests/test_koji_sign.py | tests/test_koji_sign.py | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Tests for koji_sign module.
"""
import unittest
import os
import sys
DIR = os.path.dirname(__file__)
sys.path.insert(0, os.path.join(DIR, ".."))
from releng_sop.common import Environment # noqa: E402
from releng_sop.koji_sign import get_rpmsign_class, LocalRPMSign ... | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Tests for koji_sign module.
"""
import unittest
import os
import sys
# HACK: inject empty koji module to silence failing tests.
# We need to add koji to deps (currently not possible)
# or create a mock object for testing.
import imp
sys.modules["koji"] = imp.new_modu... | Fix failing tests by injecting an empty koji module. | Fix failing tests by injecting an empty koji module.
| Python | mit | release-engineering/releng-sop,release-engineering/releng-sop | <REPLACE_OLD> sys
DIR <REPLACE_NEW> sys
# HACK: inject empty koji module to silence failing tests.
# We need to add koji to deps (currently not possible)
# or create a mock object for testing.
import imp
sys.modules["koji"] = imp.new_module("koji")
DIR <REPLACE_END> <|endoftext|> #!/usr/bin/python
# -*- coding: ut... | Fix failing tests by injecting an empty koji module.
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Tests for koji_sign module.
"""
import unittest
import os
import sys
DIR = os.path.dirname(__file__)
sys.path.insert(0, os.path.join(DIR, ".."))
from releng_sop.common import Environment # noqa: E402
from releng_... |
bca6f6041e9f49d1d25d7a9c4cb88080d88c45b1 | dumper/invalidation.py | dumper/invalidation.py | import dumper.utils
def invalidate_paths(paths):
'''
Invalidate all pages for a certain path.
'''
for path in paths:
for key in all_cache_keys_from_path(path):
dumper.utils.cache.delete(key)
def all_cache_keys_from_path(path):
return [dumper.utils.cache_key(path, method) for ... | import dumper.utils
def invalidate_paths(paths):
'''
Invalidate all pages for a certain path.
'''
for path in paths:
for key in all_cache_keys_from_path(path):
dumper.utils.cache.delete(key)
def all_cache_keys_from_path(path):
'''
Each path can actually have multiple cach... | Comment concerning differences in keys per path | Comment concerning differences in keys per path | Python | mit | saulshanabrook/django-dumper | <INSERT> '''
Each path can actually have multiple cached entries, varying based on different HTTP
methods. So a GET request will have a different cached response from a HEAD request.
In order to invalidate a path, we must first know all the different cache keys that the
path might have been cached ... | Comment concerning differences in keys per path
import dumper.utils
def invalidate_paths(paths):
'''
Invalidate all pages for a certain path.
'''
for path in paths:
for key in all_cache_keys_from_path(path):
dumper.utils.cache.delete(key)
def all_cache_keys_from_path(path):
r... |
e890ac9ef00193beac77b757c62911553cebf656 | test.py | test.py | import urllib
urllib.urlretrieve('http://192.168.0.13:8080/photoaf.jpg', '/home/pi/img/img.jpg') | import urllib
urllib.urlretrieve('http://192.168.0.13:8080/photoaf.jpg', 'img.jpg') | Change save path to local path | Change save path to local path
| Python | mit | adampiskorski/lpr_poc | <REPLACE_OLD> '/home/pi/img/img.jpg') <REPLACE_NEW> 'img.jpg') <REPLACE_END> <|endoftext|> import urllib
urllib.urlretrieve('http://192.168.0.13:8080/photoaf.jpg', 'img.jpg') | Change save path to local path
import urllib
urllib.urlretrieve('http://192.168.0.13:8080/photoaf.jpg', '/home/pi/img/img.jpg') |
7eac12bb8fe31b397c8598af14973f2337ca8c53 | cla_public/apps/contact/tests/test_notes.py | cla_public/apps/contact/tests/test_notes.py | import unittest
from werkzeug.datastructures import MultiDict
from cla_public.app import create_app
from cla_public.apps.contact.forms import ContactForm
def submit(**kwargs):
return ContactForm(MultiDict(kwargs), csrf_enabled=False)
class NotesTest(unittest.TestCase):
def setUp(self):
app = crea... | Add python test for notes length validation | Add python test for notes length validation
| Python | mit | ministryofjustice/cla_public,ministryofjustice/cla_public,ministryofjustice/cla_public,ministryofjustice/cla_public | <INSERT> import unittest
from werkzeug.datastructures import MultiDict
from cla_public.app import create_app
from cla_public.apps.contact.forms import ContactForm
def submit(**kwargs):
<INSERT_END> <INSERT> return ContactForm(MultiDict(kwargs), csrf_enabled=False)
class NotesTest(unittest.TestCase):
def s... | Add python test for notes length validation
| |
8de4cb6e314da95b243f140f53b3c77487695a55 | tests/cyclus_tools.py | tests/cyclus_tools.py | #! /usr/bin/env python
from tools import check_cmd
def run_cyclus(cyclus, cwd, sim_files):
"""Runs cyclus with various inputs and creates output databases
"""
for sim_input, sim_output in zip(sim_files):
holdsrtn = [1] # needed because nose does not send() to test generator
cmd = [cyc... | #! /usr/bin/env python
from tools import check_cmd
def run_cyclus(cyclus, cwd, sim_files):
"""Runs cyclus with various inputs and creates output databases
"""
for sim_input, sim_output in sim_files:
holdsrtn = [1] # needed because nose does not send() to test generator
cmd = [cyclus, ... | Correct zip() error in run_cyclus function | Correct zip() error in run_cyclus function
| Python | bsd-3-clause | Baaaaam/cyBaM,gonuke/cycamore,cyclus/cycaless,gonuke/cycamore,Baaaaam/cycamore,jlittell/cycamore,rwcarlsen/cycamore,Baaaaam/cyBaM,Baaaaam/cycamore,rwcarlsen/cycamore,jlittell/cycamore,gonuke/cycamore,jlittell/cycamore,rwcarlsen/cycamore,Baaaaam/cycamore,jlittell/cycamore,Baaaaam/cyBaM,Baaaaam/cyCLASS,cyclus/cycaless,Ba... | <REPLACE_OLD> zip(sim_files):
<REPLACE_NEW> sim_files:
<REPLACE_END> <|endoftext|> #! /usr/bin/env python
from tools import check_cmd
def run_cyclus(cyclus, cwd, sim_files):
"""Runs cyclus with various inputs and creates output databases
"""
for sim_input, sim_output in sim_files:
holdsrtn =... | Correct zip() error in run_cyclus function
#! /usr/bin/env python
from tools import check_cmd
def run_cyclus(cyclus, cwd, sim_files):
"""Runs cyclus with various inputs and creates output databases
"""
for sim_input, sim_output in zip(sim_files):
holdsrtn = [1] # needed because nose does not... |
b8572aa26114bd9792b83dfb9187e466537303fa | stickord/commands/games.py | stickord/commands/games.py | import discord
from stickord.registry import Command
@Command(['tellen', 'tel'])
async def counting(cont, mesg, client, *args, **kwargs):
count, auth, when = (0, discord.User, None)
if cont:
try:
num = int(cont[0])
if num != count + 1:
return f'Whoops, you done g... | Add framework for counting command | Add framework for counting command
| Python | mit | RobinSikkens/Sticky-discord | <REPLACE_OLD> <REPLACE_NEW> import discord
from stickord.registry import Command
@Command(['tellen', 'tel'])
async def counting(cont, mesg, client, *args, **kwargs):
count, auth, when = (0, discord.User, None)
if cont:
try:
num = int(cont[0])
if num != count + 1:
... | Add framework for counting command
| |
b52037176cd1b8a4d99ff195d72680928ba3790f | cms/djangoapps/export_course_metadata/management/commands/export_course_metadata_for_all_courses.py | cms/djangoapps/export_course_metadata/management/commands/export_course_metadata_for_all_courses.py | """
Export course metadata for all courses
"""
from django.core.management.base import BaseCommand
from xmodule.modulestore.django import modulestore
from cms.djangoapps.export_course_metadata.signals import export_course_metadata
from cms.djangoapps.export_course_metadata.tasks import export_course_metadata_task
... | """
Export course metadata for all courses
"""
from django.core.management.base import BaseCommand
from xmodule.modulestore.django import modulestore
from cms.djangoapps.export_course_metadata.signals import export_course_metadata
from cms.djangoapps.export_course_metadata.tasks import export_course_metadata_task
... | Change how we get course ids to avoid memory issues | Change how we get course ids to avoid memory issues
| Python | agpl-3.0 | angelapper/edx-platform,arbrandes/edx-platform,angelapper/edx-platform,eduNEXT/edx-platform,edx/edx-platform,EDUlib/edx-platform,arbrandes/edx-platform,eduNEXT/edunext-platform,eduNEXT/edunext-platform,eduNEXT/edx-platform,EDUlib/edx-platform,arbrandes/edx-platform,eduNEXT/edunext-platform,angelapper/edx-platform,angel... | <DELETE> module_store = modulestore()
<DELETE_END> <REPLACE_OLD> module_store.get_courses()
<REPLACE_NEW> modulestore().get_course_summaries()
<REPLACE_END> <|endoftext|> """
Export course metadata for all courses
"""
from django.core.management.base import BaseCommand
from xmodule.modulestore.django import mod... | Change how we get course ids to avoid memory issues
"""
Export course metadata for all courses
"""
from django.core.management.base import BaseCommand
from xmodule.modulestore.django import modulestore
from cms.djangoapps.export_course_metadata.signals import export_course_metadata
from cms.djangoapps.export_course... |
5578d11f45e9c41ab9c4311f2bed48b9c24d9bf5 | tests/grammar_term-nonterm_test/NonterminalHaveTest.py | tests/grammar_term-nonterm_test/NonterminalHaveTest.py | #!/usr/bin/env python
"""
:Author Patrik Valkovic
:Created 23.06.2017 16:39
:Licence GNUv3
Part of grammpy
""" | Create file for Nonterminal have method | Create file for Nonterminal have method
| Python | mit | PatrikValkovic/grammpy | <REPLACE_OLD> <REPLACE_NEW> #!/usr/bin/env python
"""
:Author Patrik Valkovic
:Created 23.06.2017 16:39
:Licence GNUv3
Part of grammpy
""" <REPLACE_END> <|endoftext|> #!/usr/bin/env python
"""
:Author Patrik Valkovic
:Created 23.06.2017 16:39
:Licence GNUv3
Part of grammpy
""" | Create file for Nonterminal have method
| |
bfe45a24800817e7445fa12e7cd859679e6452c3 | porchlightapi/views.py | porchlightapi/views.py | # -*- coding: utf-8 -*-
from django.shortcuts import render
# Create your views here.
import django_filters
from rest_framework import viewsets
from rest_framework import filters
from porchlightapi.models import Repository, ValueDataPoint
from porchlightapi.serializers import RepositorySerializer, ValueDataPointSer... | # -*- coding: utf-8 -*-
from django.shortcuts import render
# Create your views here.
from rest_framework import viewsets
from rest_framework import filters
from porchlightapi.models import Repository, ValueDataPoint
from porchlightapi.serializers import RepositorySerializer, ValueDataPointSerializer
class Reposito... | Use DRF's built-in search filter | Use DRF's built-in search filter
| Python | cc0-1.0 | cfpb/porchlight,cfpb/porchlight,cfpb/porchlight | <REPLACE_OLD> here.
import django_filters
from <REPLACE_NEW> here.
from <REPLACE_END> <DELETE> RepositoryFilter(django_filters.FilterSet):
"""
Provide filtering of repository objects based on name or project.
This is 'icontains' filtering, so a repo with the name "Porchlight"
will match 'por', 'Por',... | Use DRF's built-in search filter
# -*- coding: utf-8 -*-
from django.shortcuts import render
# Create your views here.
import django_filters
from rest_framework import viewsets
from rest_framework import filters
from porchlightapi.models import Repository, ValueDataPoint
from porchlightapi.serializers import Repos... |
b9df853ec27106a31d67600483bec660d274d674 | saleor/menu/models.py | saleor/menu/models.py | from django.db import models
from django.utils.translation import pgettext_lazy
from mptt.managers import TreeManager
from mptt.models import MPTTModel
class Menu(models.Model):
slug = models.SlugField(max_length=50)
class Meta:
permissions = (
('view_menu',
pgettext_lazy('Pe... | from django.db import models
from django.db.models import Max
from django.utils.translation import pgettext_lazy
from mptt.managers import TreeManager
from mptt.models import MPTTModel
class Menu(models.Model):
slug = models.SlugField(max_length=50)
class Meta:
permissions = (
('view_menu... | Save sorting order on MenuItem | Save sorting order on MenuItem
| Python | bsd-3-clause | maferelo/saleor,UITools/saleor,UITools/saleor,UITools/saleor,UITools/saleor,maferelo/saleor,mociepka/saleor,UITools/saleor,mociepka/saleor,maferelo/saleor,mociepka/saleor | <INSERT> django.db.models import Max
from <INSERT_END> <REPLACE_OLD> self.name
<REPLACE_NEW> self.name
def get_ordering_queryset(self):
return (
self.menu.items.all() if not self.parent
else self.parent.children.all())
def save(self, *args, **kwargs):
if self.sort_orde... | Save sorting order on MenuItem
from django.db import models
from django.utils.translation import pgettext_lazy
from mptt.managers import TreeManager
from mptt.models import MPTTModel
class Menu(models.Model):
slug = models.SlugField(max_length=50)
class Meta:
permissions = (
('view_menu'... |
fba8f3a2595ebb032e86c09710ef4757ae87c428 | heppy/modules/rgp.py | heppy/modules/rgp.py | from ..Module import Module
from ..TagData import TagData
class rgp(Module):
opmap = {
'infData': 'descend',
}
def parse_rgpStatus(self, response, tag):
status = tag.attrib['s']
response.set(status, tag.text)
def render_default(self, request, data):
ext = self.re... | from ..Module import Module
from ..TagData import TagData
class rgp(Module):
opmap = {
'infData': 'descend',
}
def parse_rgpStatus(self, response, tag):
status = tag.attrib['s']
response.set(status, tag.text)
def render_default(self, request, data):
ext = self.re... | Add RGP request and report | Add RGP request and report
| Python | bsd-3-clause | hiqdev/reppy | <INSERT> def render_request(self, request, data):
return self.render_default(request, data)
def render_report(self, request, data):
ext = self.render_extension(request, 'update')
restore = request.add_subtag(ext, 'rgp:restore', { 'op': 'report'})
report = request.add_subtag(resto... | Add RGP request and report
from ..Module import Module
from ..TagData import TagData
class rgp(Module):
opmap = {
'infData': 'descend',
}
def parse_rgpStatus(self, response, tag):
status = tag.attrib['s']
response.set(status, tag.text)
def render_default(self, request, ... |
6c645b69b91b6a29d4e8786c07e6438d16667415 | emds/formats/exceptions.py | emds/formats/exceptions.py | """
Various parser-related exceptions.
"""
class ParseError(Exception):
"""
Raise this when some unrecoverable error happens while parsing serialized
market data.
"""
pass
| """
Various parser-related exceptions.
"""
from emds.exceptions import EMDSError
class ParseError(EMDSError):
"""
Raise this when some unrecoverable error happens while parsing serialized
market data.
"""
pass
| Make ParseError a child of EMDSError. | Make ParseError a child of EMDSError.
| Python | mit | gtaylor/EVE-Market-Data-Structures | <REPLACE_OLD> exceptions.
"""
class ParseError(Exception):
<REPLACE_NEW> exceptions.
"""
from emds.exceptions import EMDSError
class ParseError(EMDSError):
<REPLACE_END> <|endoftext|> """
Various parser-related exceptions.
"""
from emds.exceptions import EMDSError
class ParseError(EMDSError):
"""
Raise thi... | Make ParseError a child of EMDSError.
"""
Various parser-related exceptions.
"""
class ParseError(Exception):
"""
Raise this when some unrecoverable error happens while parsing serialized
market data.
"""
pass
|
bc9f4d4e5022f4219727e9085164982f9efb005e | editor/views/generic.py | editor/views/generic.py | import git
import os
from django.conf import settings
from django.http import HttpResponseRedirect
from django.shortcuts import render
class SaveContentMixin():
"""Save exam or question content to a git repository and to a database."""
# object = None
# request = None
# template_name = None
... | import git
import os
from django.conf import settings
from django.http import HttpResponseRedirect
from django.shortcuts import render
class SaveContentMixin():
"""Save exam or question content to a git repository and to a database."""
# object = None
# request = None
# template_name = None
... | Set the git author name and e-mail | Set the git author name and e-mail
| Python | apache-2.0 | numbas/editor,numbas/editor,numbas/editor | <INSERT> os.environ['GIT_AUTHOR_NAME'] = 'Numbas'
os.environ['GIT_AUTHOR_EMAIL'] = 'numbas@ncl.ac.uk'
<INSERT_END> <|endoftext|> import git
import os
from django.conf import settings
from django.http import HttpResponseRedirect
from django.shortcuts import render
class SaveContentMixin():
... | Set the git author name and e-mail
import git
import os
from django.conf import settings
from django.http import HttpResponseRedirect
from django.shortcuts import render
class SaveContentMixin():
"""Save exam or question content to a git repository and to a database."""
# object = None
# request ... |
d191a947e34e4d6eee1965f4896a44efc8c7ae91 | feedback/views.py | feedback/views.py | from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
from django.template import RequestContext
from feedback.forms import FeedbackForm
def leave_feedback(request):
form = FeedbackForm(request.POST or None)
if form.is_valid():
feedback = form.save(commit=False)
... | from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
from django.template import RequestContext
from feedback.forms import FeedbackForm
def leave_feedback(request, template_name='feedback/feedback_form.html'):
form = FeedbackForm(request.POST or None)
if form.is_valid()... | Allow passing of template_name to view | Allow passing of template_name to view
| Python | bsd-3-clause | girasquid/django-feedback | <REPLACE_OLD> leave_feedback(request):
<REPLACE_NEW> leave_feedback(request, template_name='feedback/feedback_form.html'):
<REPLACE_END> <REPLACE_OLD> render_to_response('feedback/feedback_form.html', <REPLACE_NEW> render_to_response(template_name, <REPLACE_END> <REPLACE_OLD> context_instance=RequestContext(request))... | Allow passing of template_name to view
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response
from django.template import RequestContext
from feedback.forms import FeedbackForm
def leave_feedback(request):
form = FeedbackForm(request.POST or None)
if form.is_valid():
... |
4719167b6ee1c6dd276218c84b15b9cba4fefc2e | config/pox_sync.py | config/pox_sync.py | from config.experiment_config_lib import ControllerConfig
from sts.control_flow.fuzzer import Fuzzer
from sts.input_traces.input_logger import InputLogger
from sts.simulation_state import SimulationConfig
from sts.invariant_checker import InvariantChecker
from sts.topology import MeshTopology, BufferedPatchPanel
from s... | Add example for using sync protocol in pox | Add example for using sync protocol in pox
| Python | apache-2.0 | jmiserez/sts,jmiserez/sts | <REPLACE_OLD> <REPLACE_NEW> from config.experiment_config_lib import ControllerConfig
from sts.control_flow.fuzzer import Fuzzer
from sts.input_traces.input_logger import InputLogger
from sts.simulation_state import SimulationConfig
from sts.invariant_checker import InvariantChecker
from sts.topology import MeshTopolo... | Add example for using sync protocol in pox
| |
7aa1875f9e542ae539729730cf9457e78d8b775b | walker/main.py | walker/main.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import subprocess
import sys
def execute_command(target):
os.chdir(target)
command = sys.argv[1:]
try:
subprocess.check_call(command)
except Exception as e:
print "ERROR in %s: %s" % (target, e)
def main():
base = os.getcwdu()... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import subprocess
import sys
def execute_command(target):
os.chdir(target)
command = sys.argv[1:]
try:
subprocess.check_call(command)
except Exception as e:
print "ERROR in %s: %s" % (target, e)
def main():
base = os.getcwdu()... | Add a new line before displaying the current dir | Add a new line before displaying the current dir
This makes it easier for my brain to read.
| Python | bsd-3-clause | darylyu/walker,darylyu/walker | <REPLACE_OLD> "walker: <REPLACE_NEW> "\nwalker: <REPLACE_END> <|endoftext|> #!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import subprocess
import sys
def execute_command(target):
os.chdir(target)
command = sys.argv[1:]
try:
subprocess.check_call(command)
except Exception as e:
... | Add a new line before displaying the current dir
This makes it easier for my brain to read.
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import subprocess
import sys
def execute_command(target):
os.chdir(target)
command = sys.argv[1:]
try:
subprocess.check_call(command)
except Exce... |
573f3fd726c7bf1495bfdfeb2201317abc2949e4 | src/parser/menu_item.py | src/parser/menu_item.py | """(c) All rights reserved. ECOLE POLYTECHNIQUE FEDERALE DE LAUSANNE, Switzerland, VPSI, 2017"""
class MenuItem:
""" To store menu item information """
def __init__(self, txt, target, hidden):
""" Constructor
txt - Menu link text
target - Can be several things
-- Referenc... | """(c) All rights reserved. ECOLE POLYTECHNIQUE FEDERALE DE LAUSANNE, Switzerland, VPSI, 2017"""
class MenuItem:
""" To store menu item information """
def __init__(self, txt, target, hidden):
""" Constructor
txt - Menu link text
target - Can be several things
-- Referenc... | Remove previously added method because finally not used... | Remove previously added method because finally not used...
| Python | mit | epfl-idevelop/jahia2wp,epfl-idevelop/jahia2wp,epfl-idevelop/jahia2wp,epfl-idevelop/jahia2wp | <DELETE> target_is_reference(self):
# If it is not another possibility, it is a reference
return not self.target_is_sitemap() and \
not self.target_is_url() and \
self.target is not None
def <DELETE_END> <|endoftext|> """(c) All rights reserved. ECOLE POLYTECHNIQUE FEDERALE ... | Remove previously added method because finally not used...
"""(c) All rights reserved. ECOLE POLYTECHNIQUE FEDERALE DE LAUSANNE, Switzerland, VPSI, 2017"""
class MenuItem:
""" To store menu item information """
def __init__(self, txt, target, hidden):
""" Constructor
txt - Menu link text
... |
e52b58e823e803c0cce47a1e24e41577088a25a0 | future/tests/test_imports_urllib.py | future/tests/test_imports_urllib.py | import unittest
import sys
print([m for m in sys.modules if m.startswith('urllib')])
class MyTest(unittest.TestCase):
def test_urllib(self):
import urllib
print(urllib.__file__)
from future import standard_library
with standard_library.hooks():
import urllib.response
... | Add a new little urllib import test | Add a new little urllib import test
| Python | mit | michaelpacer/python-future,michaelpacer/python-future,QuLogic/python-future,krischer/python-future,krischer/python-future,PythonCharmers/python-future,PythonCharmers/python-future,QuLogic/python-future | <INSERT> import unittest
import sys
print([m for m in sys.modules if m.startswith('urllib')])
class MyTest(unittest.TestCase):
<INSERT_END> <INSERT> def test_urllib(self):
import urllib
print(urllib.__file__)
from future import standard_library
with standard_library.hooks():
... | Add a new little urllib import test
| |
6c61e0a477a03dcd81d90bf828ba6c036c86b355 | pydocstring/docstring.py | pydocstring/docstring.py | class Docstring:
"""Class for storing docstring information.
Following headers are used by this class:
* 'summary' - first line of the docstring
* 'extended' - blocks of extended description concerning the functionality of the code
* 'parameters' - parameters of a method
* 'other parameters' -... | Add general framework for coding | Add general framework for coding
using documentation
| Python | mit | kimt33/pydocstring | <REPLACE_OLD> <REPLACE_NEW> class Docstring:
"""Class for storing docstring information.
Following headers are used by this class:
* 'summary' - first line of the docstring
* 'extended' - blocks of extended description concerning the functionality of the code
* 'parameters' - parameters of a meth... | Add general framework for coding
using documentation
| |
3fe8498b8599238fd18b8f96edff438e1f569f48 | sheldon/storage.py | sheldon/storage.py | # -*- coding: utf-8 -*-
"""
Interface to Redis-storage.
@author: Seva Zhidkov
@contact: zhidkovseva@gmail.com
@license: The MIT license
Copyright (C) 2015
"""
from .utils import logger
# We will catch all import exceptions in bot.py
from redis import StrictRedis
class Storage:
def __init__(self, bot):
... | # -*- coding: utf-8 -*-
"""
Interface to Redis-storage.
@author: Seva Zhidkov
@contact: zhidkovseva@gmail.com
@license: The MIT license
Copyright (C) 2015
"""
from .utils import logger
# We will catch all import exceptions in bot.py
from redis import StrictRedis
class Storage:
def __init__(self, bot):
... | Fix typo in redis error message | Fix typo in redis error message
| Python | mit | lises/sheldon | <REPLACE_OLD> connection <REPLACE_NEW> connecting <REPLACE_END> <|endoftext|> # -*- coding: utf-8 -*-
"""
Interface to Redis-storage.
@author: Seva Zhidkov
@contact: zhidkovseva@gmail.com
@license: The MIT license
Copyright (C) 2015
"""
from .utils import logger
# We will catch all import exceptions in bot.py
from ... | Fix typo in redis error message
# -*- coding: utf-8 -*-
"""
Interface to Redis-storage.
@author: Seva Zhidkov
@contact: zhidkovseva@gmail.com
@license: The MIT license
Copyright (C) 2015
"""
from .utils import logger
# We will catch all import exceptions in bot.py
from redis import StrictRedis
class Storage:
... |
2737723b9f0bae0166e63a7a79d4d89bac3a82d9 | test_passwd_change.py | test_passwd_change.py | #!/usr/bin/env python3
from passwd_change import passwd_change, shadow_change, mails_delete
from unittest import TestCase, TestLoader, TextTestRunner
import os
import subprocess
class PasswdChange_Test(TestCase):
def setUp(self):
"""
Preconditions
"""
subprocess.call(['mkdir', 't... | #!/usr/bin/env python3
from passwd_change import passwd_change, shadow_change, mails_delete
from unittest import TestCase, TestLoader, TextTestRunner
import os
import subprocess
class PasswdChange_Test(TestCase):
def setUp(self):
"""
Preconditions
"""
subprocess.call(['mkdir', 't... | Fix error - rm test dir command is not executed in correct branch. | Fix error - rm test dir command is not executed in correct branch.
| Python | mit | maxsocl/oldmailer | <INSERT> raise
else:
<INSERT_END> <REPLACE_OLD> 'test/'])
raise
<REPLACE_NEW> 'test/'])
<REPLACE_END> <|endoftext|> #!/usr/bin/env python3
from passwd_change import passwd_change, shadow_change, mails_delete
from unittest import TestCase, TestLoader, TextTestRunner
import os
import... | Fix error - rm test dir command is not executed in correct branch.
#!/usr/bin/env python3
from passwd_change import passwd_change, shadow_change, mails_delete
from unittest import TestCase, TestLoader, TextTestRunner
import os
import subprocess
class PasswdChange_Test(TestCase):
def setUp(self):
"""
... |
3149aaa319620c2e39434fea081968cf7040ef6d | common/djangoapps/enrollment/urls.py | common/djangoapps/enrollment/urls.py | """
URLs for the Enrollment API
"""
from django.conf import settings
from django.conf.urls import patterns, url
from .views import (
EnrollmentView,
EnrollmentListView,
EnrollmentCourseDetailView
)
urlpatterns = patterns(
'enrollment.views',
url(
r'^enrollment/{username},{course_key}$'.f... | """
URLs for the Enrollment API
"""
from django.conf import settings
from django.conf.urls import patterns, url
from .views import (
EnrollmentView,
EnrollmentListView,
EnrollmentCourseDetailView
)
urlpatterns = patterns(
'enrollment.views',
url(
r'^enrollment/{username},{course_key}/$'.... | Add options trailing slashes to the Enrollment API. | Add options trailing slashes to the Enrollment API.
This allows the edX REST API Client to perform a sucessful GET against
this API, since Slumber (which our client is based off of) appends the
trailing slash by default.
| Python | agpl-3.0 | gymnasium/edx-platform,mbareta/edx-platform-ft,MakeHer/edx-platform,romain-li/edx-platform,BehavioralInsightsTeam/edx-platform,CourseTalk/edx-platform,Edraak/edraak-platform,hastexo/edx-platform,doganov/edx-platform,MakeHer/edx-platform,teltek/edx-platform,longmen21/edx-platform,Endika/edx-platform,EDUlib/edx-platform,... | <REPLACE_OLD> r'^enrollment/{username},{course_key}$'.format(
<REPLACE_NEW> r'^enrollment/{username},{course_key}/$'.format(
<REPLACE_END> <REPLACE_OLD> r'^enrollment/{course_key}$'.format(course_key=settings.COURSE_ID_PATTERN),
<REPLACE_NEW> r'^enrollment/{course_key}/$'.format(course_key=settings.COURSE_ID_PATTERN... | Add options trailing slashes to the Enrollment API.
This allows the edX REST API Client to perform a sucessful GET against
this API, since Slumber (which our client is based off of) appends the
trailing slash by default.
"""
URLs for the Enrollment API
"""
from django.conf import settings
from django.conf.urls impor... |
0fa938a459293849761fe344c963c503e59e24df | tests/test_cross_validation.py | tests/test_cross_validation.py | import pytest
from lightfm.cross_validation import random_train_test_split
from lightfm.datasets import fetch_movielens
def _assert_disjoint(x, y):
x = x.tocsr()
y = y.tocoo()
for (i, j) in zip(y.row, y.col):
assert x[i, j] == 0.0
@pytest.mark.parametrize('test_percentage',
... | import pytest
from lightfm.cross_validation import random_train_test_split
from lightfm.datasets import fetch_movielens
def _assert_disjoint(x, y):
x = x.tocsr()
y = y.tocoo()
for (i, j) in zip(y.row, y.col):
assert x[i, j] == 0.0
@pytest.mark.parametrize('test_percentage',
... | Make tests work with Python 2.7. | Make tests work with Python 2.7.
| Python | apache-2.0 | lyst/lightfm,maciejkula/lightfm | <REPLACE_OLD> data.nnz <REPLACE_NEW> float(data.nnz) <REPLACE_END> <|endoftext|> import pytest
from lightfm.cross_validation import random_train_test_split
from lightfm.datasets import fetch_movielens
def _assert_disjoint(x, y):
x = x.tocsr()
y = y.tocoo()
for (i, j) in zip(y.row, y.col):
asser... | Make tests work with Python 2.7.
import pytest
from lightfm.cross_validation import random_train_test_split
from lightfm.datasets import fetch_movielens
def _assert_disjoint(x, y):
x = x.tocsr()
y = y.tocoo()
for (i, j) in zip(y.row, y.col):
assert x[i, j] == 0.0
@pytest.mark.parametrize('te... |
7e9db30ee426993b881357b0158d243d0a4c15c9 | djlint/analyzers/db_backends.py | djlint/analyzers/db_backends.py | import ast
from .base import BaseAnalyzer, Result
class DB_BackendsVisitor(ast.NodeVisitor):
def __init__(self):
self.found = []
removed_items = {
'django.db.backends.postgresql':
'django.db.backends.postgresql_psycopg2',
}
def visit_Str(self, node):
if node.s ... | import ast
from .base import BaseAnalyzer, Result
class DB_BackendsVisitor(ast.NodeVisitor):
def __init__(self):
self.found = []
removed_items = {
'django.db.backends.postgresql':
'django.db.backends.postgresql_psycopg2',
}
def visit_Str(self, node):
if node.s ... | Fix database backends analyzer: 'postgresql' backend has been deprecated in 1.2 | Fix database backends analyzer: 'postgresql' backend has been deprecated in 1.2
| Python | isc | alfredhq/djlint | <REPLACE_OLD> 1.3 <REPLACE_NEW> 1.2 <REPLACE_END> <|endoftext|> import ast
from .base import BaseAnalyzer, Result
class DB_BackendsVisitor(ast.NodeVisitor):
def __init__(self):
self.found = []
removed_items = {
'django.db.backends.postgresql':
'django.db.backends.postgresql_psyc... | Fix database backends analyzer: 'postgresql' backend has been deprecated in 1.2
import ast
from .base import BaseAnalyzer, Result
class DB_BackendsVisitor(ast.NodeVisitor):
def __init__(self):
self.found = []
removed_items = {
'django.db.backends.postgresql':
'django.db.backend... |
dddf89e519e40ce118509dcb5823ad932fea88f8 | chainer/training/triggers/__init__.py | chainer/training/triggers/__init__.py | from chainer.training.triggers import interval_trigger # NOQA
from chainer.training.triggers import minmax_value_trigger # NOQA
# import class and function
from chainer.training.triggers.interval_trigger import IntervalTrigger # NOQA
from chainer.training.triggers.manual_schedule_trigger import ManualScheduleTrigg... | from chainer.training.triggers import interval_trigger # NOQA
from chainer.training.triggers import minmax_value_trigger # NOQA
# import class and function
from chainer.training.triggers.early_stopping_trigger import EarlyStoppingTrigger # NOQA
from chainer.training.triggers.interval_trigger import IntervalTrigger... | Fix the order of importing | Fix the order of importing
| Python | mit | niboshi/chainer,wkentaro/chainer,ktnyt/chainer,keisuke-umezawa/chainer,jnishi/chainer,hvy/chainer,chainer/chainer,niboshi/chainer,wkentaro/chainer,hvy/chainer,okuta/chainer,anaruse/chainer,keisuke-umezawa/chainer,tkerola/chainer,keisuke-umezawa/chainer,wkentaro/chainer,okuta/chainer,ktnyt/chainer,keisuke-umezawa/chaine... | <INSERT> chainer.training.triggers.early_stopping_trigger import EarlyStoppingTrigger # NOQA
from <INSERT_END> <DELETE> NOQA
from chainer.training.triggers.early_stopping_trigger import EarlyStoppingTrigger # <DELETE_END> <|endoftext|> from chainer.training.triggers import interval_trigger # NOQA
from chainer.traini... | Fix the order of importing
from chainer.training.triggers import interval_trigger # NOQA
from chainer.training.triggers import minmax_value_trigger # NOQA
# import class and function
from chainer.training.triggers.interval_trigger import IntervalTrigger # NOQA
from chainer.training.triggers.manual_schedule_trigge... |
e4297f0f7149763f6e93536746e3c87f9d1fa699 | tests/test_watchmedo.py | tests/test_watchmedo.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from watchdog import watchmedo
import pytest
import yaml
import os
def test_load_config_valid(tmpdir):
"""Verifies the load of a valid yaml file"""
yaml_file = os.path.join(tmpdir, 'config_file.yaml')
with open(yaml_file, 'w') as f:
... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from watchdog import watchmedo
import pytest
from yaml.constructor import ConstructorError
from yaml.scanner import ScannerError
import os
def test_load_config_valid(tmpdir):
"""Verifies the load of a valid yaml file"""
yaml_file = os.path.join... | Fix watchmedo tests in Windows | Fix watchmedo tests in Windows
Unexpectedly, but on test_load_config_invalid running, PyYAML get_single_data() raises different execptions for Linux and Windows. This PR adds ScannerError for passing tests under Windows. | Python | apache-2.0 | gorakhargosh/watchdog,gorakhargosh/watchdog | <REPLACE_OLD> pytest
import yaml
import <REPLACE_NEW> pytest
from yaml.constructor import ConstructorError
from yaml.scanner import ScannerError
import <REPLACE_END> <INSERT> # PyYAML get_single_data() raises different exceptions for Linux and Windows
<INSERT_END> <REPLACE_OLD> pytest.raises(yaml.constructor.Constr... | Fix watchmedo tests in Windows
Unexpectedly, but on test_load_config_invalid running, PyYAML get_single_data() raises different execptions for Linux and Windows. This PR adds ScannerError for passing tests under Windows.
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from watchdog import watchmedo
im... |
906a5ee2b6e20b09b12d36d61271cd63cac49418 | py2pack/utils.py | py2pack/utils.py | # -*- coding: utf-8 -*-
#
# Copyright (c) 2016, Thomas Bechtold <tbechtold@suse.com>
#
# 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
#
# Unle... | # -*- coding: utf-8 -*-
#
# Copyright (c) 2016, Thomas Bechtold <tbechtold@suse.com>
#
# 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
#
# Unle... | Raise a ValueError from _get_archive_filelist instead of Exception | Raise a ValueError from _get_archive_filelist instead of Exception
Raising the Exception base class is considered bad style, as the more
specialized child classes carry more information about the kind of error that
occurred. And often no-one actually tries to catch the Exception class.
| Python | apache-2.0 | saschpe/py2pack | <REPLACE_OLD> Exception("Can <REPLACE_NEW> ValueError("Can <REPLACE_END> <REPLACE_OLD> '%s'. <REPLACE_NEW> '{!s}'. <REPLACE_END> <INSERT> <INSERT_END> <REPLACE_OLD> file" % filename)
<REPLACE_NEW> file".format(filename))
<REPLACE_END> <|endoftext|> # -*- coding: utf-8 -*-
#
# Copyright (c) 2016, Thomas Bechtold <tbe... | Raise a ValueError from _get_archive_filelist instead of Exception
Raising the Exception base class is considered bad style, as the more
specialized child classes carry more information about the kind of error that
occurred. And often no-one actually tries to catch the Exception class.
# -*- coding: utf-8 -*-
#
# Cop... |
b8b02b41ee5c5712f90c0621d5fd7130004eafb6 | fil_finder/tests/test_profiles.py | fil_finder/tests/test_profiles.py |
'''
Tests for functions in fil_finder.width_profiles.
'''
import pytest
import numpy as np
import numpy.testing as npt
from ..width_profiles.profile_line_width import walk_through_skeleton, return_ends
def make_test_skeleton(shape=(10, 10)):
skel = np.zeros(shape)
crds = np.array([[3, 3, 4], [4, 5, 6]])
... | Add tests for end finding and walk through a skeleton | Add tests for end finding and walk through a skeleton
| Python | mit | e-koch/FilFinder | <REPLACE_OLD> <REPLACE_NEW>
'''
Tests for functions in fil_finder.width_profiles.
'''
import pytest
import numpy as np
import numpy.testing as npt
from ..width_profiles.profile_line_width import walk_through_skeleton, return_ends
def make_test_skeleton(shape=(10, 10)):
skel = np.zeros(shape)
crds = np.a... | Add tests for end finding and walk through a skeleton
| |
a95814afa175d7cd047f35dbf77ca2492d810598 | setup.py | setup.py | #!/usr/bin/env python
#
from setuptools import setup, find_packages
import sys, os
from distutils import versionpredicate
here = os.path.abspath(os.path.dirname(__file__))
README = open(os.path.join(here, 'README')).read()
version = '0.1dev'
install_requires = [
'pyhsm >= 1.0.3',
'ndnkdf >= 0.1',
'py-bcr... | #!/usr/bin/env python
#
from setuptools import setup, find_packages
import sys, os
from distutils import versionpredicate
here = os.path.abspath(os.path.dirname(__file__))
README = open(os.path.join(here, 'README')).read()
version = '0.1dev'
install_requires = [
'pyhsm >= 1.0.3',
'ndnkdf >= 0.1',
'py-bcr... | Change package name from VCCS to vccs_auth. | Change package name from VCCS to vccs_auth.
There will be a separate package containing the authentication client,
and it does not appear possible to (cleanly) generate two packages
from the same setup.py/same repository.
| Python | bsd-3-clause | SUNET/VCCS | <REPLACE_OLD> 2.4.2',
]
setup(name='VCCS',
<REPLACE_NEW> 2.4.2',
]
setup(name='vccs_auth',
<REPLACE_END> <REPLACE_OLD> System",
<REPLACE_NEW> System - authentication backend",
<REPLACE_END> <REPLACE_OLD> packages=find_packages('src'),
<REPLACE_NEW> packages=['vccs_auth',],
<REPLACE_END> <REPLACE_OLD> include_pa... | Change package name from VCCS to vccs_auth.
There will be a separate package containing the authentication client,
and it does not appear possible to (cleanly) generate two packages
from the same setup.py/same repository.
#!/usr/bin/env python
#
from setuptools import setup, find_packages
import sys, os
from distutil... |
263cd80a16f44e900d939322e3e6e1ce0cea31b7 | elements/swift-proxy/check_mk_checks/swift_proxy_healthcheck.py | elements/swift-proxy/check_mk_checks/swift_proxy_healthcheck.py | #!/usr/bin/python
# 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
# dis... | Add check_mk swift proxy diagnostic | Add check_mk swift proxy diagnostic
Added a check_mk script that runs healthcheck to ensure that a
proxy node is up and running with proxy services. This diag is
also check_mk compliant (ie. the output matches check_mk desired
format).
Have not added thecheck_mk-agent element to element-deps file as
even though it is... | Python | apache-2.0 | rdo-management/tripleo-image-elements,radez/tripleo-image-elements,radez/tripleo-image-elements,rdo-management/tripleo-image-elements,openstack/tripleo-image-elements,openstack/tripleo-image-elements | <REPLACE_OLD> <REPLACE_NEW> #!/usr/bin/python
# 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 ... | Add check_mk swift proxy diagnostic
Added a check_mk script that runs healthcheck to ensure that a
proxy node is up and running with proxy services. This diag is
also check_mk compliant (ie. the output matches check_mk desired
format).
Have not added thecheck_mk-agent element to element-deps file as
even though it is... | |
d547d45b7bb8915504b25efc508976cbb0257604 | setup.py | setup.py | import os
from setuptools import setup, find_packages
with open(os.path.join(os.path.dirname(__file__), 'VERSION')) as v_file:
version = v_file.read().strip()
with open(os.path.join(os.path.dirname(__file__), 'README.md')) as readme:
README = readme.read()
setup(
name='canvas_python_sdk',
version=ver... | import os
from setuptools import setup, find_packages
with open(os.path.join(os.path.dirname(__file__), 'VERSION')) as v_file:
version = v_file.read().strip()
with open(os.path.join(os.path.dirname(__file__), 'README.md')) as readme:
README = readme.read()
setup(
name='canvas_python_sdk',
version=ver... | Move sphinx requirement into `extras` | Move sphinx requirement into `extras`
| Python | mit | penzance/canvas_python_sdk | <INSERT> extras_require={
'docs': ['sphinx>=1.2.0'],
},
<INSERT_END> <|endoftext|> import os
from setuptools import setup, find_packages
with open(os.path.join(os.path.dirname(__file__), 'VERSION')) as v_file:
version = v_file.read().strip()
with open(os.path.join(os.path.dirname(__file__), 'READM... | Move sphinx requirement into `extras`
import os
from setuptools import setup, find_packages
with open(os.path.join(os.path.dirname(__file__), 'VERSION')) as v_file:
version = v_file.read().strip()
with open(os.path.join(os.path.dirname(__file__), 'README.md')) as readme:
README = readme.read()
setup(
na... |
97b7ba9d4d6bf948435ce58dd21b60d78d75fd29 | lib-dynload/lzo/__init__.py | lib-dynload/lzo/__init__.py | import sys
import os
p1, p2 = sys.version_info[:2]
curpath = os.path.abspath( sys.argv[0] )
if os.path.islink(curpath):
curpath = os.readlink(curpath)
currentdir = os.path.dirname( curpath )
build_dir = os.path.abspath( os.path.join(currentdir, "lib-dynload", "lzo", "build") )
if not os.path.isdir(build_dir):
... | import sys
import os
p1, p2 = sys.version_info[:2]
curpath = os.path.abspath( sys.argv[0] )
if os.path.islink(curpath):
curpath = os.readlink(curpath)
currentdir = os.path.dirname( curpath )
build_dir = os.path.abspath( os.path.join(currentdir, "lib-dynload", "lzo", "build") )
if not os.path.isdir(build_dir):
... | Adjust maximum block size for lzo | Adjust maximum block size for lzo
| Python | mit | sergey-dryabzhinsky/dedupsqlfs,sergey-dryabzhinsky/dedupsqlfs,sergey-dryabzhinsky/dedupsqlfs,sergey-dryabzhinsky/dedupsqlfs | <INSERT> module.set_block_size(16*1024*1024)
<INSERT_END> <|endoftext|> import sys
import os
p1, p2 = sys.version_info[:2]
curpath = os.path.abspath( sys.argv[0] )
if os.path.islink(curpath):
curpath = os.readlink(curpath)
currentdir = os.path.dirname( curpath )
build_dir = os.path.abspath( os.path.join(... | Adjust maximum block size for lzo
import sys
import os
p1, p2 = sys.version_info[:2]
curpath = os.path.abspath( sys.argv[0] )
if os.path.islink(curpath):
curpath = os.readlink(curpath)
currentdir = os.path.dirname( curpath )
build_dir = os.path.abspath( os.path.join(currentdir, "lib-dynload", "lzo", "build") )
... |
d43750206ef97a39f4bb7cd7d4e69d4f634c13e1 | api/runserver.py | api/runserver.py | import os
from ricardo_api import app
isDebug = False
if os.environ['FLASK_ENV'] == "development":
isDebug = True
app.run(host= '0.0.0.0', debug=isDebug)
| import os
from ricardo_api import app
isDebug = False
if 'FLASK_ENV' in os.environ and os.environ['FLASK_ENV'] == "development":
isDebug = True
app.run(host= '0.0.0.0', debug=isDebug)
| Correct debug mode with env. | [api]: Correct debug mode with env.
| Python | agpl-3.0 | medialab/ricardo,medialab/ricardo,medialab/ricardo,medialab/ricardo | <INSERT> 'FLASK_ENV' in os.environ and <INSERT_END> <|endoftext|> import os
from ricardo_api import app
isDebug = False
if 'FLASK_ENV' in os.environ and os.environ['FLASK_ENV'] == "development":
isDebug = True
app.run(host= '0.0.0.0', debug=isDebug)
| [api]: Correct debug mode with env.
import os
from ricardo_api import app
isDebug = False
if os.environ['FLASK_ENV'] == "development":
isDebug = True
app.run(host= '0.0.0.0', debug=isDebug)
|
7fea0e2fb875a655898915f9f0f8375684d9e6bd | juriscraper/oral_args/united_states/state/__init__.py | juriscraper/oral_args/united_states/state/__init__.py | __all__ = [
'ill', 'illappct_1st_dist' #'md',
]
| __all__ = [
'ill',
'illappct_1st_dist',
#'md',
]
| Clean up to ill imports. | Clean up to ill imports.
Style issue, but it's better to put these vertically. It makes it harder to forget a comma.
| Python | bsd-2-clause | freelawproject/juriscraper,freelawproject/juriscraper | <REPLACE_OLD> 'ill', 'illappct_1st_dist' <REPLACE_NEW> 'ill',
'illappct_1st_dist',
<REPLACE_END> <|endoftext|> __all__ = [
'ill',
'illappct_1st_dist',
#'md',
]
| Clean up to ill imports.
Style issue, but it's better to put these vertically. It makes it harder to forget a comma.
__all__ = [
'ill', 'illappct_1st_dist' #'md',
]
|
c441eee6acd694553e5ed79f4014eef387b9bd9e | s3file/checks.py | s3file/checks.py | from django.core.checks import Error
from django.core.files.storage import FileSystemStorage, default_storage
def storage_check(app_configs, **kwargs):
if isinstance(default_storage, FileSystemStorage):
return [
Error(
'FileSystemStorage should not be used in a production envir... | from django.core.checks import Error
from django.core.files.storage import FileSystemStorage, default_storage
def storage_check(app_configs, **kwargs):
if isinstance(default_storage, FileSystemStorage):
return [
Error(
'FileSystemStorage should not be used in a production envir... | Fix deployment check return value | Fix deployment check return value
AssertionError: The function <function storage_check at 0x7f8571c1a048> did not return a list. All functions registered with the checks registry must return a list.
| Python | mit | codingjoe/django-s3file,codingjoe/django-s3file,codingjoe/django-s3file | <INSERT> return []
<INSERT_END> <|endoftext|> from django.core.checks import Error
from django.core.files.storage import FileSystemStorage, default_storage
def storage_check(app_configs, **kwargs):
if isinstance(default_storage, FileSystemStorage):
return [
Error(
'FileSyst... | Fix deployment check return value
AssertionError: The function <function storage_check at 0x7f8571c1a048> did not return a list. All functions registered with the checks registry must return a list.
from django.core.checks import Error
from django.core.files.storage import FileSystemStorage, default_storage
def sto... |
8bdeefa23ce44a0c0aad3913ec59d4167d2b0eff | duralex/AddCommitMessageVisitor.py | duralex/AddCommitMessageVisitor.py | # -*- coding: utf-8 -*-
from AbstractVisitor import AbstractVisitor
from duralex.alinea_parser import *
import duralex.node_type
def int_to_roman(integer):
string = ''
table = [
['M',1000], ['CM',900], ['D',500], ['CD',400], ['C',100], ['XC',90], ['L',50], ['XL',40], ['X',10], ['IX',9],
['V'... | Add a visitor to generate commit messages on each 'edit" node. | Add a visitor to generate commit messages on each 'edit" node.
| Python | mit | Legilibre/duralex | <REPLACE_OLD> <REPLACE_NEW> # -*- coding: utf-8 -*-
from AbstractVisitor import AbstractVisitor
from duralex.alinea_parser import *
import duralex.node_type
def int_to_roman(integer):
string = ''
table = [
['M',1000], ['CM',900], ['D',500], ['CD',400], ['C',100], ['XC',90], ['L',50], ['XL',40], ['X... | Add a visitor to generate commit messages on each 'edit" node.
| |
b812a8da81ec9943d11b8cb9f709e234c90a2282 | stylo/utils.py | stylo/utils.py | from uuid import uuid4
class MessageBus:
"""A class that is used behind the scenes to coordinate events and timings of
animations.
"""
def __init__(self):
self.subs = {}
def new_id(self):
"""Use this to get a name to use for your events."""
return str(uuid4())
def re... | import inspect
from uuid import uuid4
def get_parameters(f):
return list(inspect.signature(f).parameters.keys())
class MessageBus:
"""A class that is used behind the scenes to coordinate events and timings of
animations.
"""
def __init__(self):
self.subs = {}
def new_id(self):
... | Add the function back for now | Add the function back for now
| Python | mit | alcarney/stylo,alcarney/stylo | <REPLACE_OLD> from <REPLACE_NEW> import inspect
from <REPLACE_END> <REPLACE_OLD> uuid4
class <REPLACE_NEW> uuid4
def get_parameters(f):
return list(inspect.signature(f).parameters.keys())
class <REPLACE_END> <|endoftext|> import inspect
from uuid import uuid4
def get_parameters(f):
return list(inspect.s... | Add the function back for now
from uuid import uuid4
class MessageBus:
"""A class that is used behind the scenes to coordinate events and timings of
animations.
"""
def __init__(self):
self.subs = {}
def new_id(self):
"""Use this to get a name to use for your events."""
... |
2cbc3a5197694905606ce5251516c825b28927d7 | setup.py | setup.py | import os
from setuptools import setup
longDesc = ""
if os.path.exists("README.rst"):
longDesc = open("README.rst").read().strip()
setup(
name = "pytesseract",
version = "0.1.7",
author = "Samuel Hoffstaetter",
author_email="pytesseract@madmaze.net",
maintainer = "Matthias Lee",
maintainer_e... | import os
from setuptools import setup
README_PATH = 'README.rst'
longDesc = ""
if os.path.exists(README_PATH):
with open(README_PATH) as readme:
longDesc = readme.read()
setup(
name = "pytesseract",
version = "0.1.7",
author = "Samuel Hoffstaetter",
author_email="pytesseract@madmaze.net"... | Fix long_description loading for PyPI | Fix long_description loading for PyPI | Python | apache-2.0 | madmaze/pytesseract | <REPLACE_OLD> setup
longDesc <REPLACE_NEW> setup
README_PATH = 'README.rst'
longDesc <REPLACE_END> <REPLACE_OLD> os.path.exists("README.rst"):
longDesc <REPLACE_NEW> os.path.exists(README_PATH):
with open(README_PATH) as readme:
longDesc <REPLACE_END> <REPLACE_OLD> open("README.rst").read().strip()
se... | Fix long_description loading for PyPI
import os
from setuptools import setup
longDesc = ""
if os.path.exists("README.rst"):
longDesc = open("README.rst").read().strip()
setup(
name = "pytesseract",
version = "0.1.7",
author = "Samuel Hoffstaetter",
author_email="pytesseract@madmaze.net",
maintai... |
e548713f5192d125b1313fa955240965a1136de8 | plugin/__init__.py | plugin/__init__.py | ########
# Copyright (c) 2014 GigaSpaces Technologies Ltd. All rights reserved
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless... | # -*- coding: utf-8 -*-
########
# Copyright (c) 2014 GigaSpaces Technologies Ltd. All rights reserved
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/license... | UPDATE init; add utf-8 encoding | UPDATE init; add utf-8 encoding
| Python | apache-2.0 | fastconnect/cloudify-azure-plugin | <REPLACE_OLD> ########
# <REPLACE_NEW> # -*- coding: utf-8 -*-
########
# <REPLACE_END> <|endoftext|> # -*- coding: utf-8 -*-
########
# Copyright (c) 2014 GigaSpaces Technologies Ltd. All rights reserved
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in complianc... | UPDATE init; add utf-8 encoding
########
# Copyright (c) 2014 GigaSpaces Technologies Ltd. All rights reserved
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.or... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.