commit stringlengths 40 40 | old_file stringlengths 4 236 | new_file stringlengths 4 236 | old_contents stringlengths 1 3.26k | new_contents stringlengths 16 4.43k | subject stringlengths 16 624 | message stringlengths 17 3.29k | lang stringclasses 5
values | license stringclasses 13
values | repos stringlengths 5 91.5k |
|---|---|---|---|---|---|---|---|---|---|
f25a32dd0180af91277ace186fc878c8baffed65 | heisen/core/__init__.py | heisen/core/__init__.py | from heisen.config import settings
from heisen.core.log import logger
from jsonrpclib.request import Connection
def get_rpc_connection():
servers = {
'self': [
('127.0.0.1', settings.RPC_PORT, 'aliehsanmilad', 'Key1_s!3cr3t')
],
}
servers.update(getattr(settings, 'RPC_SERVERS'... | from heisen.config import settings
from heisen.core.log import logger
from jsonrpclib.request import ConnectionPool
def get_rpc_connection():
if settings.CREDENTIALS:
username, passowrd = settings.CREDENTIALS[0]
else:
username = passowrd = None
servers = {'self': [('localhost', settings.R... | Use connection pool for jsonrpc | Use connection pool for jsonrpc
| Python | mit | HeisenCore/heisen |
57164efc9827f7975cdfa171a5a88e6fcc4059e5 | neutron/conf/policies/service_type.py | neutron/conf/policies/service_type.py | # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed u... | # Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed u... | Implement secure RBAC for service providers API | Implement secure RBAC for service providers API
This commit updates the policies for service providers API
to understand scope checking and account for a read-only role.
This is part of a broader series of changes across OpenStack to
provide a consistent RBAC experience and improve security.
Partially-Implements blu... | Python | apache-2.0 | mahak/neutron,mahak/neutron,openstack/neutron,openstack/neutron,openstack/neutron,mahak/neutron |
026d887dd85bdcc5db97d65706509a18252de8ba | l10n_ar_aeroo_sale/__openerp__.py | l10n_ar_aeroo_sale/__openerp__.py | # -*- coding: utf-8 -*-
{
'name': 'Argentinian Like Sale Order Aeroo Report',
'version': '1.0',
'category': 'Localization/Argentina',
'sequence': 14,
'summary': '',
'description': """
Argentinian Like Sale Order / Quotation Aeroo Report
====================================================
""... | # -*- coding: utf-8 -*-
{
'name': 'Argentinian Like Sale Order Aeroo Report',
'version': '1.0',
'category': 'Localization/Argentina',
'sequence': 14,
'summary': '',
'description': """
Argentinian Like Sale Order / Quotation Aeroo Report
====================================================
""... | FIX dependency on aeroo rpoert | FIX dependency on aeroo rpoert
| Python | agpl-3.0 | ingadhoc/argentina-reporting |
6f745ae05a22031a36cb5cedc6b627cbf7ba6512 | import_goodline_iptv.py | import_goodline_iptv.py | #!/usr/bin/env python3
import configargparse
from goodline_iptv.importer import do_import
if __name__ == '__main__':
parser = configargparse.ArgParser()
parser.add_argument('-o', '--out-dir', required=True, help='Output directory')
parser.add_argument('-e', '--encoding',
default... | #!/usr/bin/env python3
import configargparse
from goodline_iptv.importer import do_import
if __name__ == '__main__':
parser = configargparse.ArgParser()
parser.add_argument('-o', '--out-dir',
required=True,
env_var='OUTDIR',
help='Outpu... | Add environment variable for ability to set the output directory | Add environment variable for ability to set the output directory
| Python | mit | nsadovskiy/goodline_tv |
5c8fd314dd89d8964cc5cb75c2b57ed32be275c5 | plsync/users.py | plsync/users.py |
# NOTE: User roles are not managed here. Visit PlanetLab to change user roles.
user_list = [('Stephen', 'Stuart', 'sstuart@google.com'),
('Will', 'Hawkins', 'hawkinsw@opentechinstitute.org'),
('Jordan', 'McCarthy', 'mccarthy@opentechinstitute.org'),
('Chris', 'Ritzo', 'cri... |
# NOTE: User roles are not managed here. Visit PlanetLab to change user roles.
user_list = [('Stephen', 'Stuart', 'sstuart@google.com'),
('Will', 'Hawkins', 'hawkinsw@opentechinstitute.org'),
('Jordan', 'McCarthy', 'mccarthy@opentechinstitute.org'),
('Chris', 'Ritzo', 'cri... | Add pboothe temporarily for testing | Add pboothe temporarily for testing
| Python | apache-2.0 | jheretic/operator,stephen-soltesz/operator,nkinkade/operator,critzo/operator,critzo/operator,jheretic/operator,nkinkade/operator,m-lab/operator,salarcon215/operator,m-lab/operator,salarcon215/operator,stephen-soltesz/operator |
88b81ee89800592bccf0a714ae79be74507c8f29 | test_engine.py | test_engine.py | import engine
VALID_COORDS = [(x, y) for x in xrange(97, 105) for y in xrange(49, 57)]
INVALID_COORDS = [
(0, 0), (-1, -1),
(96, 49), (96, 48),
(105, 49), (104, 48),
(96, 56), (97, 57),
(105, 56), (104, 57)
]
VALID_A1 = [chr(x) + chr(y) for x in xrange(97, 105) for y in xrange(49, 57)]
INVALID... | import engine
VALID_COORDS = [(x, y) for x in xrange(97, 105) for y in xrange(49, 57)]
INVALID_COORDS = [
(0, 0), (-1, -1),
(96, 49), (96, 48),
(105, 49), (104, 48),
(96, 56), (97, 57),
(105, 56), (104, 57)
]
VALID_A1 = [chr(x) + chr(y) for x in xrange(97, 105) for y in xrange(49, 57)]
INVALID... | Add test_a1_to_coord() to assert that only valid board coordinates are in teh _a1_to_coord dictionary | Add test_a1_to_coord() to assert that only valid board coordinates are in teh _a1_to_coord dictionary
| Python | mit | EyuelAbebe/gamer,EyuelAbebe/gamer |
4c3dd0c9d27af0f186f81c4fed0003a9190b4d9e | jal_stats/stats/serializers.py | jal_stats/stats/serializers.py | # from django.contrib.auth.models import User
from rest_framework import serializers
from .models import Activity, Stat
class StatSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Stat
fields = ('id', 'activity', 'reps', 'date')
def create(self, validated_data):
... | # from django.contrib.auth.models import User
from rest_framework import serializers
from .models import Activity, Stat
class StatAddSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Stat
fields = ('id', 'reps', 'date')
class StatSerializer(StatAddSerializer):
class M... | Add new serializer for StatAdd that doesn't have activity | Add new serializer for StatAdd that doesn't have activity
| Python | mit | jal-stats/django |
fd6702fbb43eb4e6c5129ac6026908946f03c1a7 | paws/handler.py | paws/handler.py | from .request import Request
from .response import response
class Handler(object):
'''
Simple dispatcher class.
'''
def __call__(self, event, context):
self.request = request = Request(event, context)
func = getattr(self, self.event['httpMethod'], self.invalid)
return func(req... | from .request import Request
from .response import response
class Handler(object):
'''
Simple dispatcher class.
'''
def __init__(self, event, context):
self.request = Request(event, context)
def __call__(self, event, context):
func = getattr(self, self.event['httpMethod'], self.in... | Move request construction to init | Move request construction to init
| Python | bsd-3-clause | funkybob/paws |
bdcf90a0fdf782b1c6cfd261e0dbb208e013eb1b | python/day12.py | python/day12.py | #!/usr/local/bin/python3
import json
import pathlib
input_file = pathlib.Path(__file__).parent.parent.joinpath('day12_input.txt')
def sum_data(d):
total = 0
if isinstance(d, dict):
d = d.values()
for item in d:
if isinstance(item, int):
total += item
elif isinstance(... | #!/usr/local/bin/python3
import json
import pathlib
input_file = pathlib.Path(__file__).parent.parent.joinpath('day12_input.txt')
def sum_data(d):
total = 0
if isinstance(d, dict):
d = d.values()
if 'red' in d: return 0
for item in d:
if isinstance(item, int):
total ... | Add day 12 part two solution in python | Add day 12 part two solution in python
| Python | mit | robjwells/adventofcode-solutions,robjwells/adventofcode-solutions,robjwells/adventofcode-solutions,robjwells/adventofcode-solutions,robjwells/adventofcode-solutions,robjwells/adventofcode-solutions |
3436b94a4c69b843c65f6ddf6756c18ca540c090 | linked-list/is-list-palindrome.py | linked-list/is-list-palindrome.py | # Given a singly linked list of integers, determine whether or not it's a palindrome
class Node(object): # define constructor
def __init__(self, value):
self.value = value
self.next = None
def is_list_palindrome(l):
if not l.value or not l.next.value:
return True
def create_nodes(l):
root = Node(-1)
current... | # Given a singly linked list of integers, determine whether or not it's a palindrome
class Node(object): # define constructor
def __init__(self, value):
self.value = value
self.next = None
def is_list_palindrome(l):
if not l.value or not l.next.value:
return True
fake_head = Node(None)
fake_head.next = l
f... | Create fast node that is twice the speed of slow node to get to center of list | Create fast node that is twice the speed of slow node to get to center of list
| Python | mit | derekmpham/interview-prep,derekmpham/interview-prep |
a1a9ab2b2c0ca7749984f5ad6e6430980e0d0ecc | tests/basics/list_sort.py | tests/basics/list_sort.py | l = [1, 3, 2, 5]
print(l)
l.sort()
print(l)
l.sort(key=lambda x: -x)
print(l)
l.sort(key=lambda x: -x, reverse=True)
print(l)
l.sort(reverse=True)
print(l)
l.sort(reverse=False)
print(l)
| l = [1, 3, 2, 5]
print(l)
print(sorted(l))
l.sort()
print(l)
print(l == sorted(l))
print(sorted(l, key=lambda x: -x))
l.sort(key=lambda x: -x)
print(l)
print(l == sorted(l, key=lambda x: -x))
print(sorted(l, key=lambda x: -x, reverse=True))
l.sort(key=lambda x: -x, reverse=True)
print(l)
print(l == sorted(l, key=lam... | Add tests for sorted() function and check that sorted(list) produces same output as list.sort() | Add tests for sorted() function
and check that sorted(list) produces same output as list.sort()
| Python | mit | MrSurly/micropython-esp32,KISSMonX/micropython,mpalomer/micropython,mianos/micropython,ernesto-g/micropython,dxxb/micropython,tuc-osg/micropython,lbattraw/micropython,turbinenreiter/micropython,swegener/micropython,swegener/micropython,praemdonck/micropython,SungEun-Steve-Kim/test-mp,pfalcon/micropython,pozetroninc/mic... |
2d688f97b9869fdfed9237b91fdce287278e3c6c | wsgi.py | wsgi.py | import os
from elasticsearch_raven.transport import ElasticsearchTransport
from elasticsearch_raven.utils import get_index
host = os.environ.get('ELASTICSEARCH_HOST', 'localhost:9200')
transport = ElasticsearchTransport(host)
def application(environ, start_response):
index = get_index(environ)
transport.sen... | import os
from queue import Queue
from threading import Thread
from elasticsearch_raven.transport import ElasticsearchTransport
from elasticsearch_raven.utils import get_index
host = os.environ.get('ELASTICSEARCH_HOST', 'localhost:9200')
transport = ElasticsearchTransport(host)
blocking_queue = Queue()
def send():
... | Send data to elasticsearch asynchronously. | Send data to elasticsearch asynchronously.
| Python | mit | socialwifi/elasticsearch-raven,pozytywnie/elasticsearch-raven,serathius/elasticsearch-raven |
d703d7cb8d75a5c660beabccdd0082794a8471d1 | edisgo/tools/networkx_helper.py | edisgo/tools/networkx_helper.py | from networkx import OrderedGraph
def translate_df_to_graph(buses_df, lines_df, transformers_df=None):
graph = OrderedGraph()
buses = buses_df.index
# add nodes
graph.add_nodes_from(buses)
# add branches
branches = []
for line_name, line in lines_df.iterrows():
branches.append(
... | from networkx import Graph
def translate_df_to_graph(buses_df, lines_df, transformers_df=None):
graph = Graph()
buses = []
for bus_name, bus in buses_df.iterrows():
pos = (bus.x, bus.y)
buses.append((bus_name, {'pos': pos}))
# add nodes
graph.add_nodes_from(buses)
# add br... | Include the position into the graph | Include the position into the graph
| Python | agpl-3.0 | openego/eDisGo,openego/eDisGo |
80271752183c3f71fba9139bb77466427bd48a0a | alfred_listener/__main__.py | alfred_listener/__main__.py | #!/usr/bin/env python
import os
from argh import arg, ArghParser
from functools import wraps
CONFIG = os.environ.get('ALFRED_LISTENER_CONFIG')
def with_app(func, args):
if CONFIG is None:
raise RuntimeError('ALFRED_LISTENER_CONFIG env variable is not set.')
@wraps(func)
def wrapper(*args, **kwa... | #!/usr/bin/env python
import os
from argh import arg, ArghParser
from functools import wraps
def with_app(func):
@arg('--config', help='Path to config file')
@wraps(func)
def wrapper(*args, **kwargs):
config = args[0].config
from alfred_listener import create_app
app = create_app(... | Change the way to determine path to config file | Change the way to determine path to config file
| Python | isc | alfredhq/alfred-listener |
9516caa0c62289c89b605b9b8a34622a0bb54e2b | tests/70_program_libpfasst_swe_sphere_timestepper_convergence_l1/postprocessing_pickle.py | tests/70_program_libpfasst_swe_sphere_timestepper_convergence_l1/postprocessing_pickle.py | #! /usr/bin/env python3
import sys
import math
import glob
from mule_local.postprocessing.pickle_SphereDataPhysicalDiff import *
from mule.exec_program import *
pickle_SphereDataPhysicalDiff()
| #! /usr/bin/env python3
import sys
import math
import glob
from mule_local.postprocessing.pickle_SphereDataSpectralDiff import *
from mule.exec_program import *
pickle_SphereDataSpectralDiff()
| Use SphereDataSpectral instead of SphereDataPhysical | Use SphereDataSpectral instead of SphereDataPhysical
The script for physical data requires CSV files as default output files,
whereas the spectral script uses .sweet binary files as default.
Since libpfasst_swe_sphere's CSV output is not in the same format as
swe_sphere's CSV output, the CSV parsing does not work --> ... | Python | mit | schreiberx/sweet,schreiberx/sweet,schreiberx/sweet,schreiberx/sweet |
33f4036825c6ff4d9df0038471727648e0df100d | feder/virus_scan/engine/base.py | feder/virus_scan/engine/base.py | from django.contrib.sites.shortcuts import get_current_site
from django.urls import reverse
from django.core.signing import TimestampSigner
class BaseEngine:
def __init__(self):
self.signer = TimestampSigner()
def get_webhook_url(self):
return "{}://{}{}?token={}".format(
"https",... | import urllib.parse
from django.contrib.sites.shortcuts import get_current_site
from django.urls import reverse
from django.core.signing import TimestampSigner
class BaseEngine:
def __init__(self):
self.signer = TimestampSigner()
def get_webhook_url(self):
return "{}://{}{}?token={}".format(... | Fix urlencode in webhook url | Fix urlencode in webhook url | Python | mit | watchdogpolska/feder,watchdogpolska/feder,watchdogpolska/feder,watchdogpolska/feder |
d618f430c143874011b70afe0a4fa62c06f5e28c | md5bot.py | md5bot.py | """
md5bot.py -- Twitter bot that tweets the current time as an md5 value
"""
import time
import hashlib
import tweepy
CONSUMER_KEY = 'xxxxxxxxxxxx'
CONSUMER_SECRET = 'xxxxxxxxxxxx'
ACCESS_KEY = 'xxxxxxxxxxxx'
ACCESS_SECRET = 'xxxxxxxxxxxx'
auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
auth.set_access_to... | #!/usr/bin/env python
__author__ = "Patrick Guelcher"
__copyright__ = "(C) 2016 Patrick Guelcher"
__license__ = "MIT"
__version__ = "1.0"
"""
A bot for Twitter that checks the time and then posts it as an md5 hash value.
"""
import time
import hashlib
import tweepy
# Configuration (Twitter API Settings)
CONSUMER_KE... | Clean code and conform to python conventions | Clean code and conform to python conventions
Some things are still a bit weird, mostly due to my limited knowledge of
Python.
Also fixed code to conform to Python naming conventions for
variables/functions.
| Python | mit | aerovolts/python-scripts |
1a39eea8225ebdf7f654df9ba5b87479e9dbc867 | minify.py | minify.py | """
Copyright 2016 Dee Reddy
"""
import sys
import re
args = sys.argv[1:]
def minify(filepath, comments=False):
""" Minifies/uglifies file
:param
file_:
comments: Boolean. If False, deletes comments during output.
:return:
Minified string.
"""
pattern = re.compile(r"... | """
Copyright 2016 Dee Reddy
"""
import sys
import re
args = sys.argv[1:]
def minify(input_path, output_path, comments=False):
""" Minifies/uglifies file
args:
input_path: input file path
output_path: write-out file path
comments: Boolean. If False, deletes comments during output... | Update regex. Add file write-out. | feat: Update regex. Add file write-out.
Regex is bugged, however. Need to fix regex pattern.
| Python | apache-2.0 | Deesus/Punt |
fe6e24d3cadd71b7c613926f7baa26947f6caadd | webmention_plugin.py | webmention_plugin.py | from webmentiontools.send import WebmentionSend
from webmentiontools.urlinfo import UrlInfo
def handle_new_or_edit(post):
url = post.permalink_url
info = UrlInfo(url)
in_reply_to = info.inReplyTo()
if url and in_reply_to:
sender = WebmentionSend(url, in_reply_to, verify=False)
... | from webmentiontools.send import WebmentionSend
from webmentiontools.urlinfo import UrlInfo
def handle_new_or_edit(post):
url = post.permalink_url
in_reply_to = post.in_reply_to
if url and in_reply_to:
print "Sending webmention {} to {}".format(url, in_reply_to)
sender = WebmentionSend(... | Update webmention plugin to new version | Update webmention plugin to new version
| Python | bsd-2-clause | thedod/redwind,Lancey6/redwind,Lancey6/redwind,thedod/redwind,Lancey6/redwind |
1bc674ea94209ff20a890b9743a28bc0b9d8cb89 | motels/serializers.py | motels/serializers.py | from .models import Comment
from .models import Motel
from .models import Town
from rest_framework import serializers
class CommentSerializer(serializers.ModelSerializer):
created_date = serializers.DateTimeField(format='%d/%m/%Y %H:%M')
class Meta:
model = Comment
fields = ('id', 'motel', 'bo... | from .models import Comment
from .models import Motel
from .models import Town
from rest_framework import serializers
class CommentSerializer(serializers.ModelSerializer):
created_date = serializers.DateTimeField(format='%d/%m/%Y %H:%M', required=False)
class Meta:
model = Comment
fields = ('i... | Fix bug with comment POST (created_date was required) | Fix bug with comment POST (created_date was required)
| Python | mit | amartinez1/5letrasAPI |
7c425075280fea87b1c8dd61b43f51e19e84b770 | astropy/utils/exceptions.py | astropy/utils/exceptions.py | # Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
This module contains errors/exceptions and warnings of general use for
astropy. Exceptions that are specific to a given subpackage should *not*
be here, but rather in the particular subpackage.
"""
from __future__ import (absolute_import, division, pri... | # Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
This module contains errors/exceptions and warnings of general use for
astropy. Exceptions that are specific to a given subpackage should *not*
be here, but rather in the particular subpackage.
"""
from __future__ import (absolute_import, division, pri... | Remove DeprecationWarning superclass for AstropyDeprecationWarning | Remove DeprecationWarning superclass for AstropyDeprecationWarning
we do this because in py2.7, DeprecationWarning and subclasses are hidden by default, but we want astropy's deprecations to get shown by default
| Python | bsd-3-clause | bsipocz/astropy,astropy/astropy,funbaker/astropy,StuartLittlefair/astropy,StuartLittlefair/astropy,larrybradley/astropy,lpsinger/astropy,dhomeier/astropy,funbaker/astropy,MSeifert04/astropy,stargaser/astropy,dhomeier/astropy,mhvk/astropy,AustereCuriosity/astropy,saimn/astropy,pllim/astropy,larrybradley/astropy,joergdie... |
98ab2a2ac0279f504195e49d55ff7be817592a75 | kirppu/app/checkout/urls.py | kirppu/app/checkout/urls.py | from django.conf.urls import url, patterns
from .api import AJAX_FUNCTIONS
__author__ = 'jyrkila'
_urls = [url('^checkout.js$', 'checkout_js', name='checkout_js')]
_urls.extend([
url(func.url, func.name, name=func.view_name)
for func in AJAX_FUNCTIONS.itervalues()
])
urlpatterns = patterns('kirppu.app.checko... | from django.conf import settings
from django.conf.urls import url, patterns
from .api import AJAX_FUNCTIONS
__author__ = 'jyrkila'
if settings.KIRPPU_CHECKOUT_ACTIVE:
# Only activate API when checkout is active.
_urls = [url('^checkout.js$', 'checkout_js', name='checkout_js')]
_urls.extend([
url(... | Fix access to checkout API. | Fix access to checkout API.
Prevent access to checkout API urls when checkout is not activated by
not creating urlpatterns.
| Python | mit | mniemela/kirppu,jlaunonen/kirppu,jlaunonen/kirppu,mniemela/kirppu,jlaunonen/kirppu,mniemela/kirppu,jlaunonen/kirppu |
535b07758a16dec2ce79781f19b34a96044b99d3 | fluent_contents/conf/plugin_template/models.py | fluent_contents/conf/plugin_template/models.py | from django.db import models
from django.utils.six import python_2_unicode_compatible
from django.utils.translation import ugettext_lazy as _
from fluent_contents.models import ContentItem
@python_2_unicode_compatible
class {{ model }}(ContentItem):
"""
CMS plugin data model to ...
"""
title = models... | from django.db import models
from django.utils.translation import gettext_lazy as _
from fluent_contents.models import ContentItem
class {{ model }}(ContentItem):
"""
CMS plugin data model to ...
"""
title = models.CharField(_("Title"), max_length=200)
class Meta:
verbose_name = _("{{ mo... | Update plugin_template to Python 3-only standards | Update plugin_template to Python 3-only standards
| Python | apache-2.0 | edoburu/django-fluent-contents,django-fluent/django-fluent-contents,edoburu/django-fluent-contents,edoburu/django-fluent-contents,django-fluent/django-fluent-contents,django-fluent/django-fluent-contents |
505f7f6b243502cb4d6053ac7d54e0ecad15c557 | functional_tests/test_question_page.py | functional_tests/test_question_page.py | from selenium import webdriver
import unittest
from django.test import TestCase
from functional_tests import SERVER_URL
class AskQuestion(TestCase):
"""Users can ask questions."""
def setUp(self):
"""Selenium browser."""
self.browser = webdriver.Firefox()
self.browser.implicitly_wait(... | from selenium import webdriver
from hamcrest import *
import unittest
from django.test import TestCase
from functional_tests import SERVER_URL
class AskQuestion(TestCase):
"""Users can ask questions."""
def setUp(self):
"""Selenium browser."""
self.browser = webdriver.Firefox()
self.b... | Test for submitting and viewing questions. | Test for submitting and viewing questions.
| Python | agpl-3.0 | bjaress/shortanswer |
8b1818aefd6180548cf3b9770eb7a4d93e827fd7 | alignak_app/__init__.py | alignak_app/__init__.py | #!/usr/bin/env python
# -*- codinf: utf-8 -*-
"""
Alignak App
This module is an Alignak App Indicator
"""
# Specific Application
from alignak_app import alignak_data, application, launch
# Application version and manifest
VERSION = (0, 2, 0)
__application__ = u"Alignak-App"
__short_version__ = '.'.join((str... | #!/usr/bin/env python
# -*- codinf: utf-8 -*-
"""
Alignak App
This module is an Alignak App Indicator
"""
# Application version and manifest
VERSION = (0, 2, 0)
__application__ = u"Alignak-App"
__short_version__ = '.'.join((str(each) for each in VERSION[:2]))
__version__ = '.'.join((str(each) for each in VER... | Remove import of all Class app | Remove import of all Class app
| Python | agpl-3.0 | Alignak-monitoring-contrib/alignak-app,Alignak-monitoring-contrib/alignak-app |
f5747773e05fc892883c852e495f9e166888d1ea | rapt/connection.py | rapt/connection.py | import os
import getpass
from urlparse import urlparse
import keyring
from vr.common.models import Velociraptor
def auth_domain(url):
hostname = urlparse(url).hostname
_, _, default_domain = hostname.partition('.')
return default_domain
def set_password(url, username):
hostname = auth_domain(url)... | import os
import getpass
from urlparse import urlparse
import keyring
from vr.common.models import Velociraptor
def auth_domain(url):
hostname = urlparse(url).hostname
_, _, default_domain = hostname.partition('.')
return default_domain
def set_password(url, username):
hostname = auth_domain(url)... | Set the hostname when it localhost | Set the hostname when it localhost
| Python | bsd-3-clause | yougov/rapt,yougov/rapt |
4a0491fb018cd96e510f25141dda5e7ceff423b4 | client/test/server_tests.py | client/test/server_tests.py | from mockito import *
import unittest
from source.server import *
from source.exception import *
from source.commands.system import *
class ServerTestCase(unittest.TestCase):
def createCommandResponse(self, command, parameters = {}, timeout = None):
response = mock()
response.status_code = 200
json = ... | from mockito import *
import unittest
from source.server import *
from source.exception import *
from source.commands.system import *
class ServerTestCase(unittest.TestCase):
def createCommandResponse(self, command, parameters = {}, timeout = None):
response = mock()
response.status_code = 200
json = ... | Remove tearDown not used method | Remove tearDown not used method
| Python | mit | CaminsTECH/owncloud-test |
a0863e53ccc8f548486eaa5f3e1f79774dea4b75 | tests/api/views/clubs/list_test.py | tests/api/views/clubs/list_test.py | from tests.data import add_fixtures, clubs
def test_list_all(db_session, client):
sfn = clubs.sfn()
lva = clubs.lva()
add_fixtures(db_session, sfn, lva)
res = client.get("/clubs")
assert res.status_code == 200
assert res.json == {
"clubs": [
{"id": lva.id, "name": "LV Aach... | from pytest_voluptuous import S
from voluptuous.validators import ExactSequence
from tests.data import add_fixtures, clubs
def test_list_all(db_session, client):
add_fixtures(db_session, clubs.sfn(), clubs.lva())
res = client.get("/clubs")
assert res.status_code == 200
assert res.json == S(
... | Use `pytest-voluptuous` to simplify JSON compare code | api/clubs/list/test: Use `pytest-voluptuous` to simplify JSON compare code
| Python | agpl-3.0 | skylines-project/skylines,skylines-project/skylines,skylines-project/skylines,skylines-project/skylines |
93e447512b32e61ce41d25e73bb1592a3f8ac556 | gitfs/views/history.py | gitfs/views/history.py | from .view import View
class HistoryView(View):
pass
| from datetime import datetime
from errno import ENOENT
from stat import S_IFDIR
from pygit2 import GIT_SORT_TIME
from gitfs import FuseOSError
from log import log
from .view import View
class HistoryView(View):
def getattr(self, path, fh=None):
'''
Returns a dictionary with keys identical to th... | Add minimal working version for HistoryView (to be refactored). | Add minimal working version for HistoryView (to be refactored).
| Python | apache-2.0 | ksmaheshkumar/gitfs,rowhit/gitfs,bussiere/gitfs,PressLabs/gitfs,PressLabs/gitfs |
4811de79c618134cec922e401ec447ef156ffc78 | scripts/pystart.py | scripts/pystart.py | import os,sys,re
from time import sleep
home = os.path.expanduser('~')
if (sys.version_info > (3, 0)):
# Python 3 code in this block
exec(open(home+'/homedir/scripts/hexecho.py').read())
else:
# Python 2 code in this block
execfile(home+'/homedir/scripts/hexecho.py')
hexoff
print ("Ran pystart and did import os... | import os,sys,re
from time import sleep
from pprint import pprint
home = os.path.expanduser('~')
if (sys.version_info > (3, 0)):
# Python 3 code in this block
exec(open(home+'/homedir/scripts/hexecho.py').read())
else:
# Python 2 code in this block
execfile(home+'/homedir/scripts/hexecho.py')
hexoff
print ("Ran... | Add pprint to default python includes | Add pprint to default python includes
| Python | mit | jdanders/homedir,jdanders/homedir,jdanders/homedir,jdanders/homedir |
9a5fa9b32d822848dd8fcbdbf9627c8c89bcf66a | deen/main.py | deen/main.py | import sys
import logging
import pathlib
from PyQt5.QtWidgets import QApplication
from PyQt5.QtGui import QIcon
from deen.widgets.core import Deen
ICON = str(pathlib.PurePath(__file__).parent / 'icon.png')
LOGGER = logging.getLogger()
logging.basicConfig(format='[%(lineno)s - %(funcName)s() ] %(message)s')
def mai... | import sys
import logging
import os.path
from PyQt5.QtWidgets import QApplication
from PyQt5.QtGui import QIcon
from deen.widgets.core import Deen
ICON = os.path.dirname(os.path.abspath(__file__)) + '/icon.png'
LOGGER = logging.getLogger()
logging.basicConfig(format='[%(lineno)s - %(funcName)s() ] %(message)s')
de... | Use os.path instead of pathlib | Use os.path instead of pathlib
| Python | apache-2.0 | takeshixx/deen,takeshixx/deen |
47530321c413976241e0d4e314f2a8e1532f38c9 | hackarena/utilities.py | hackarena/utilities.py | # -*- coding: utf-8 -*-
class Utilities(object):
def get_session_string(self, original_session_string):
session_attributes = original_session_string.split(' ')
return session_attributes[0] + ' ' + session_attributes[1]
def get_session_middle_part(self, original_session_string):
return... | # -*- coding: utf-8 -*-
class Utilities(object):
@classmethod
def get_session_string(cls, original_session_string):
session_attributes = original_session_string.split(' ')
return session_attributes[0] + ' ' + session_attributes[1]
@classmethod
def get_session_middle_part(cls, origina... | Fix classmethods on utility class | Fix classmethods on utility class
| Python | mit | verekia/hackarena,verekia/hackarena,verekia/hackarena,verekia/hackarena |
b2155e167b559367bc24ba614f51360793951f12 | mythril/support/source_support.py | mythril/support/source_support.py | from mythril.solidity.soliditycontract import SolidityContract
from mythril.ethereum.evmcontract import EVMContract
class Source:
def __init__(
self, source_type=None, source_format=None, source_list=None, meta=None
):
self.source_type = source_type
self.source_format = source_format
... | from mythril.solidity.soliditycontract import SolidityContract
from mythril.ethereum.evmcontract import EVMContract
class Source:
def __init__(
self, source_type=None, source_format=None, source_list=None, meta=None
):
self.source_type = source_type
self.source_format = source_format
... | Remove meta from source class (belongs to issue not source) | Remove meta from source class (belongs to issue not source)
| Python | mit | b-mueller/mythril,b-mueller/mythril,b-mueller/mythril,b-mueller/mythril |
356891c9b0fbf1d57f67a22ca977d3d1016e5dc1 | numpy/array_api/_set_functions.py | numpy/array_api/_set_functions.py | from __future__ import annotations
from ._array_object import Array
from typing import Tuple, Union
import numpy as np
def unique(x: Array, /, *, return_counts: bool = False, return_index: bool = False, return_inverse: bool = False) -> Union[Array, Tuple[Array, ...]]:
"""
Array API compatible wrapper for :p... | from __future__ import annotations
from ._array_object import Array
from typing import Tuple, Union
import numpy as np
def unique(x: Array, /, *, return_counts: bool = False, return_index: bool = False, return_inverse: bool = False) -> Union[Array, Tuple[Array, ...]]:
"""
Array API compatible wrapper for :p... | Fix the array API unique() function | Fix the array API unique() function
| Python | mit | cupy/cupy,cupy/cupy,cupy/cupy,cupy/cupy |
09d356f7b124368ac2ca80efa981d115ea847196 | django_ethereum_events/web3_service.py | django_ethereum_events/web3_service.py | from django.conf import settings
from web3 import Web3, RPCProvider
from .singleton import Singleton
class Web3Service(metaclass=Singleton):
"""Creates a `web3` instance based on the given `RPCProvider`."""
def __init__(self, *args, **kwargs):
"""Initializes the `web3` object.
Args:
... | from django.conf import settings
from web3 import Web3
try:
from web3 import HTTPProvider
RPCProvider = None
except ImportError:
from web3 import RPCProvider
HTTPProvider = None
from .singleton import Singleton
class Web3Service(metaclass=Singleton):
"""Creates a `web3` instance based on the give... | Support for Web3 4.0beta: HTTPProvider | Support for Web3 4.0beta: HTTPProvider
In Web3 3.16 the class is called RPCProvider, but in the
upcoming 4.0 series it's replaced with HTTPProvider.
This commit ensures both versions are supported in this regard.
| Python | mit | artemistomaras/django-ethereum-events,artemistomaras/django-ethereum-events |
3039b00e761f02eb0586dad51049377a31329491 | reggae/reflect.py | reggae/reflect.py | from __future__ import (unicode_literals, division,
absolute_import, print_function)
from reggae.build import Build, DefaultOptions
from inspect import getmembers
def get_build(module):
builds = [v for n, v in getmembers(module) if isinstance(v, Build)]
assert len(builds) == 1
re... | from __future__ import (unicode_literals, division,
absolute_import, print_function)
from reggae.build import Build, DefaultOptions
from inspect import getmembers
def get_build(module):
builds = [v for n, v in getmembers(module) if isinstance(v, Build)]
assert len(builds) == 1
re... | Use absolute paths for dependencies | Use absolute paths for dependencies
| Python | bsd-3-clause | atilaneves/reggae-python |
827bc2751add4905b3fca57568c879e7cb8e70a0 | django_tml/inline_translations/middleware.py | django_tml/inline_translations/middleware.py | from .. import inline_translations as _
from django.conf import settings
class InlineTranslationsMiddleware(object):
""" Turn off/on inline tranlations with cookie """
def process_request(self, request, *args, **kwargs):
""" Check signed cookie for inline tranlations """
try:
... | # encoding: UTF-8
from .. import inline_translations as _
from django.conf import settings
class InlineTranslationsMiddleware(object):
""" Turn off/on inline tranlations with cookie """
def process_request(self, request, *args, **kwargs):
""" Check signed cookie for inline tranlations """
try:
... | Delete cookie on reset inline mode | Delete cookie on reset inline mode
| Python | mit | translationexchange/tml-python,translationexchange/tml-python |
8284a8e61ed6c4e6b3402c55d2247f7e468a6872 | tests/test_integrations/test_get_a_token.py | tests/test_integrations/test_get_a_token.py | # -*- coding: utf-8 -*-
import os
import unittest
from dotenv import load_dotenv
from auth0plus.oauth import get_token
load_dotenv('.env')
class TestGetAToken(unittest.TestCase):
def setUp(self):
"""
Get a non-interactive client secret
"""
self.domain = os.getenv('DOMAIN')
... | # -*- coding: utf-8 -*-
import os
import unittest
from dotenv import load_dotenv
from auth0plus.oauth import get_token
load_dotenv('.env')
class TestGetAToken(unittest.TestCase):
@unittest.skipIf(skip, 'SKIP_INTEGRATION_TESTS==1')
def setUp(self):
"""
Get a non-interactive client secret
... | Add unittest skip for CI | Add unittest skip for CI
| Python | isc | bretth/auth0plus |
557d536aebe40bb115d2f0056aaaddf450ccc157 | test/params/test_arguments_parsing.py | test/params/test_arguments_parsing.py | import unittest
from hamcrest import *
from lib.params import parse_args
class test_arguments_parsing(unittest.TestCase):
def test_default_secret_and_token_to_data_dir(self):
argument = parse_args("")
assert_that(argument.client_secrets, is_('data/client_secrets.json'))
assert_that(argum... | import unittest
from hamcrest import *
from lib.params import parse_args
class test_arguments_parsing(unittest.TestCase):
def test_default_secret_and_token_to_data_dir(self):
argument = parse_args([])
assert_that(argument.client_secrets, is_('data/client_secrets.json'))
assert_that(argum... | Test for parsing argument parameters | Test for parsing argument parameters
| Python | mit | gds-attic/transactions-explorer,gds-attic/transactions-explorer,alphagov/transactions-explorer,gds-attic/transactions-explorer,alphagov/transactions-explorer,alphagov/transactions-explorer,gds-attic/transactions-explorer,alphagov/transactions-explorer,gds-attic/transactions-explorer,alphagov/transactions-explorer |
07b81828c100879795b629185bcc68bd69d30748 | setup.py | setup.py | from distutils.core import setup
setup(name="stellar-magnate",
version="0.1",
description="A space-themed commodity trading game",
long_description="""
Stellar Magnate is a space-themed trading game in the spirit of Planetary
Travel by Brian Winn.
""",
author="Toshio Kuratomi",
... | from distutils.core import setup
setup(name="stellar-magnate",
version="0.1",
description="A space-themed commodity trading game",
long_description="""
Stellar Magnate is a space-themed trading game in the spirit of Planetary
Travel by Brian Winn.
""",
author="Toshio Kuratomi",
... | Add more libraries that are used at runtime | Add more libraries that are used at runtime
| Python | agpl-3.0 | abadger/stellarmagnate |
98ca83d54eab97c81c5df86b415eb9ff0b201902 | src/__init__.py | src/__init__.py | import os
import logging
from socket import gethostbyname, gethostname
from kaa.base import ipc
from client import *
from server import *
__all__ = [ 'connect', 'DEFAULT_EPG_PORT', 'GuideClient', 'GuideServer' ]
# connected client object
_client = None
def connect(epgdb, address='127.0.0.1', logfile='/tmp/kaa-epg.l... | import os
import logging
from socket import gethostbyname, gethostname
from kaa.base import ipc
from client import *
from server import *
__all__ = [ 'connect', 'DEFAULT_EPG_PORT', 'GuideClient', 'GuideServer' ]
# connected client object
_client = None
def connect(epgdb, address='127.0.0.1', logfile='/tmp/kaa-epg.l... | Fix starting inet client when should use unix socket instead. Fix port to be int. | Fix starting inet client when should use unix socket instead.
Fix port to be int.
git-svn-id: ffaf500d3baede20d2f41eac1d275ef07405e077@1240 a8f5125c-1e01-0410-8897-facf34644b8e
| Python | lgpl-2.1 | freevo/kaa-epg |
d90544ad2051e92a63da45d7270c7f66545edb82 | openedx/core/djangoapps/content/course_overviews/migrations/0009_readd_facebook_url.py | openedx/core/djangoapps/content/course_overviews/migrations/0009_readd_facebook_url.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models, OperationalError, connection
from openedx.core.djangoapps.content.course_overviews.models import CourseOverview
class Migration(migrations.Migration):
dependencies = [
('course_overviews', '0008_rem... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models, connection
def table_description():
"""Handle Mysql/Pg vs Sqlite"""
# django's mysql/pg introspection.get_table_description tries to select *
# from table and fails during initial migrations from scra... | Migrate correctly from scratch also | Migrate correctly from scratch also
Unfortunately, instrospection.get_table_description runs
select * from course_overview_courseoverview, which of course
does not exist while django is calculating initial migrations, causing
this to fail. Additionally, sqlite does not support information_schema,
but does not do a se... | Python | agpl-3.0 | Edraak/edx-platform,Edraak/circleci-edx-platform,Edraak/circleci-edx-platform,Edraak/edx-platform,Edraak/edx-platform,Edraak/circleci-edx-platform,Edraak/circleci-edx-platform,Edraak/edx-platform,Edraak/edx-platform,Edraak/circleci-edx-platform |
577da237d219aacd4413cb789fb08c76ca218223 | ws/plugins/accuweather/__init__.py | ws/plugins/accuweather/__init__.py |
import numpy as np
import pickle
import os
import sys
import ws.bad as bad
mydir = os.path.abspath(os.path.dirname(__file__))
print(mydir)
lookupmatrix = pickle.load(open( \
mydir +'/accuweather_location_codes.dump','rb'))
lookuplist = lookupmatrix.tolist()
def build_url(city):
... | import numpy as np
import pickle
import os
import sys
import ws.bad as bad
mydir = os.path.abspath(os.path.dirname(__file__))
lookupmatrix = pickle.load(open(os.path.join(mydir, 'accuweather_location_codes.dump'), 'rb'))
lookuplist = lookupmatrix.tolist()
def build_url(city):
# check whether input is a string
... | Use os.path.join() to join paths | Use os.path.join() to join paths
| Python | bsd-3-clause | BCCN-Prog/webscraping |
d84e37089a287fd151824f0b48624f243fdded09 | d1lod/tests/test_dataone.py | d1lod/tests/test_dataone.py | """test_dataone.py
Test the DataOne utility library.
"""
from d1lod.dataone import extractIdentifierFromFullURL as extract
def test_extracting_identifiers_from_urls():
# Returns None when it should
assert extract('asdf') is None
assert extract(1) is None
assert extract('1') is None
assert extract... | """test_dataone.py
Test the DataOne utility library.
"""
from d1lod import dataone
def test_parsing_resource_map():
pid = 'resourceMap_df35d.3.2'
aggd_pids = dataone.getAggregatedIdentifiers(pid)
assert len(aggd_pids) == 7
def test_extracting_identifiers_from_urls():
# Returns None when it should
... | Change imports in dataone test and add test for resource map parsing | Change imports in dataone test and add test for resource map parsing
| Python | apache-2.0 | ec-geolink/d1lod,ec-geolink/d1lod,ec-geolink/d1lod,ec-geolink/d1lod |
fd4f6fb2eef3fd24d427836023918103bac08ada | acme/acme/__init__.py | acme/acme/__init__.py | """ACME protocol implementation.
This module is an implementation of the `ACME protocol`_. Latest
supported version: `draft-ietf-acme-01`_.
.. _`ACME protocol`: https://github.com/ietf-wg-acme/acme/
.. _`draft-ietf-acme-01`:
https://github.com/ietf-wg-acme/acme/tree/draft-ietf-acme-acme-01
"""
| """ACME protocol implementation.
This module is an implementation of the `ACME protocol`_. Latest
supported version: `draft-ietf-acme-01`_.
.. _`ACME protocol`: https://ietf-wg-acme.github.io/acme
.. _`draft-ietf-acme-01`:
https://github.com/ietf-wg-acme/acme/tree/draft-ietf-acme-acme-01
"""
| Use GH pages for IETF spec repo link | Use GH pages for IETF spec repo link
| Python | apache-2.0 | mitnk/letsencrypt,mitnk/letsencrypt,twstrike/le_for_patching,DavidGarciaCat/letsencrypt,kuba/letsencrypt,DavidGarciaCat/letsencrypt,letsencrypt/letsencrypt,jsha/letsencrypt,thanatos/lets-encrypt-preview,TheBoegl/letsencrypt,kuba/letsencrypt,brentdax/letsencrypt,wteiken/letsencrypt,brentdax/letsencrypt,jtl999/certbot,Vl... |
091b1f5eb7c999a8d9b2448c1ca75941d2efb926 | opentaxii/auth/sqldb/models.py | opentaxii/auth/sqldb/models.py | import bcrypt
from sqlalchemy.schema import Column
from sqlalchemy.types import Integer, String
from sqlalchemy.ext.declarative import declarative_base
__all__ = ['Base', 'Account']
Base = declarative_base()
MAX_STR_LEN = 256
class Account(Base):
__tablename__ = 'accounts'
id = Column(Integer, primary_ke... | import hmac
import bcrypt
from sqlalchemy.schema import Column
from sqlalchemy.types import Integer, String
from sqlalchemy.ext.declarative import declarative_base
__all__ = ['Base', 'Account']
Base = declarative_base()
MAX_STR_LEN = 256
class Account(Base):
__tablename__ = 'accounts'
id = Column(Integ... | Use constant time string comparison for password checking | Use constant time string comparison for password checking
| Python | bsd-3-clause | EclecticIQ/OpenTAXII,Intelworks/OpenTAXII,EclecticIQ/OpenTAXII,Intelworks/OpenTAXII |
2faca854148a0661946ac944e4b8aa0684c773f6 | request.py | request.py | __author__ = 'brock'
"""
Taken from: https://gist.github.com/1094140
"""
from functools import wraps
from flask import request, current_app
def jsonp(func):
"""Wraps JSONified output for JSONP requests."""
@wraps(func)
def decorated_function(*args, **kwargs):
callback = request.args.get('callba... | __author__ = 'brock'
"""
Taken from: https://gist.github.com/1094140
"""
from functools import wraps
from flask import request, current_app
def jsonp(func):
"""Wraps JSONified output for JSONP requests."""
@wraps(func)
def decorated_function(*args, **kwargs):
callback = request.args.get('callba... | Add get param as int | Add get param as int
| Python | bsd-3-clause | Sendhub/flashk_util |
6c351939243f758119ed91de299d6d37dc305359 | application/main/routes/__init__.py | application/main/routes/__init__.py | # coding: utf-8
from .all_changes import AllChanges
from .show_change import ShowChange
from .changes_for_date import ChangesForDate
from .changes_for_class import ChangesForClass
all_routes = [
(r'/', AllChanges),
(r'/changes/show/([0-9A-Za-z\-_]+)', ShowChange),
(r'/changes/by_date/([0-9]{4}-[0-9]{2}-[0... | # coding: utf-8
from .all_changes import AllChanges
from .show_change import ShowChange
from .changes_for_date import ChangesForDate
from .changes_for_class import ChangesForClass
all_routes = [
(r'/', AllChanges),
(r'/changes/show/([0-9A-Za-z\-_]+)', ShowChange),
(r'/changes/by_date/([0-9]{4}-[0-9]{2}-[0... | Expand class name routing target | Expand class name routing target
| Python | bsd-3-clause | p22co/edaemon,paulsnar/edaemon,p22co/edaemon,p22co/edaemon,paulsnar/edaemon,paulsnar/edaemon |
0bbe6a915f8c289a9960f3cba9354955a19854f4 | inpassing/pass_util.py | inpassing/pass_util.py | # Copyright (c) 2016 Luke San Antonio Bialecki
# All rights reserved.
from sqlalchemy.sql import and_
from .models import Pass
def query_user_passes(session, user_id, verified=None):
if verified:
# Only verified passes
return session.query(Pass).filter(
and_(Pass.owner_id == user_id,... | # Copyright (c) 2016 Luke San Antonio Bialecki
# All rights reserved.
from sqlalchemy.sql import and_
from .models import Pass
def query_user_passes(session, user_id, verified=None):
if verified:
# Only verified passes
return session.query(Pass).filter(
and_(Pass.owner_id == user_id,... | Fix bug in user pass code | Fix bug in user pass code
The functions to query user and org passes return non-verified passes when
verified=None, which was not intended.
| Python | mit | lukesanantonio/inpassing-backend,lukesanantonio/inpassing-backend |
7439a2c4b73707dc301117d3d8d368cfc31bc774 | akanda/rug/api/keystone.py | akanda/rug/api/keystone.py | # Copyright (c) 2015 Akanda, Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable la... | # Copyright (c) 2015 Akanda, Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable la... | Use KSC auth's register_conf_options instead of oslo.cfg import | Use KSC auth's register_conf_options instead of oslo.cfg import
A newer keystoneclient is not happy with simply using oslo_config to
import the config group. Instead, use register_conf_options()
from keystoneclient.auth.
Change-Id: I798dad7ad5bd90362e1fa10c2eecb3e1d5bade71
| Python | apache-2.0 | openstack/akanda-rug,openstack/akanda-rug,stackforge/akanda-rug,stackforge/akanda-rug |
9d0ba593ae5f7e23a1bd32573ad8e80dac6eb845 | stalkr/cache.py | stalkr/cache.py | import os
import requests
class Cache:
extensions = ["gif", "jpeg", "jpg", "png"]
def __init__(self, directory):
self.directory = directory
if not os.path.isdir(directory):
os.mkdir(directory)
def get(self, key):
for extension in self.extensions:
filename =... | import os
import requests
class UnknownExtensionException:
def __init__(self, extension):
self.extension = extension
def __str__(self):
return repr("{0}: unknown extension".format(self.extension))
class Cache:
extensions = ["gif", "jpeg", "jpg", "png"]
def __init__(self, directory):
... | Raise exception if the image file extension is unknown | Raise exception if the image file extension is unknown
| Python | isc | helderm/stalkr,helderm/stalkr,helderm/stalkr,helderm/stalkr |
5c5956dc11bbe9e65f6b9403cf0dbe5470eab257 | iterm2_tools/images.py | iterm2_tools/images.py | from __future__ import print_function, division, absolute_import
import sys
import os
import base64
# See https://iterm2.com/images.html
IMAGE_CODE = '\033]1337;File={file};inline={inline};size={size}:{base64_img}\a'
def image_bytes(b, filename=None, inline=1):
data = {
'file': base64.b64encode((filename... | from __future__ import print_function, division, absolute_import
import sys
import os
import base64
# See https://iterm2.com/images.html
IMAGE_CODE = '\033]1337;File={file};inline={inline};size={size}:{base64_img}\a'
def image_bytes(b, filename=None, inline=1):
"""
Display the image given by the bytes b in t... | Add a docstring to image_bytes | Add a docstring to image_bytes
| Python | mit | asmeurer/iterm2-tools |
eba55b9b4eb59af9a56965086aae240c6615ba1f | author/urls.py | author/urls.py | from django.conf.urls import patterns
from django.conf.urls import url
from django.views.generic.base import RedirectView
from django.core.urlresolvers import reverse_lazy
from django.contrib.contenttypes.models import ContentType
from django.contrib.auth.models import Permission
from django.contrib.auth.views import l... | from django.conf.urls import patterns
from django.conf.urls import url
from django.views.generic.base import RedirectView
from django.core.urlresolvers import reverse_lazy
from django.contrib.auth.views import login
from django.contrib.auth.decorators import login_required
from django.contrib.auth.decorators import per... | Fix bug with author permission check | Fix bug with author permission check
| Python | bsd-3-clause | stefantsov/blackbox3,stefantsov/blackbox3,stefantsov/blackbox3 |
ca9c4f7c3f1f7690395948b9dcdfd917cc33bfa8 | array/sudoku-check.py | array/sudoku-check.py | # Implement an algorithm that will check whether a given grid of numbers represents a valid Sudoku puzzle
def check_rows(grid):
i = 0
while i < len(grid):
j = 0
ref_check = {}
while j < len(grid[i]):
if grid[i][j] != '.' and grid[i][j] in ref_check:
return False
else:
ref_check[grid[i][j]] = 1
... | # Implement an algorithm that will check whether a given grid of numbers represents a valid Sudoku puzzle
def check_rows(grid):
i = 0
while i < len(grid):
j = 0
ref_check = {}
while j < len(grid[i]):
if grid[i][j] != '.' and grid[i][j] in ref_check:
return False
else:
ref_check[grid[i][j]] = 1
... | Add create sub grid method | Add create sub grid method
| Python | mit | derekmpham/interview-prep,derekmpham/interview-prep |
dba22abf151ddee20aeb886e2bca6401a17d7cea | properties/spatial.py | properties/spatial.py | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import six
from .base import Property
from . import vmath
class Vector(Property):
"""class properties.Vector
Vector property, using properties.vmath.Vector
... | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import six
from .base import Property
from . import vmath
class Vector(Property):
"""class properties.Vector
Vector property, using properties.vmath.Vector
... | Improve vector property error message | Improve vector property error message
| Python | mit | aranzgeo/properties,3ptscience/properties |
b0b067c70d3bfc8fb599bd859116cce60f6759da | examples/dft/12-camb3lyp.py | examples/dft/12-camb3lyp.py | #!/usr/bin/env python
#
# Author: Qiming Sun <osirpt.sun@gmail.com>
#
'''
The default XC functional library (libxc) supports the energy and nuclear
gradients for range separated functionals. Nuclear Hessian and TDDFT gradients
need xcfun library. See also example 32-xcfun_as_default.py for how to set
xcfun library a... | #!/usr/bin/env python
#
# Author: Qiming Sun <osirpt.sun@gmail.com>
#
'''Density functional calculations can be run with either the default
backend library, libxc, or an alternative library, xcfun. See also
example 32-xcfun_as_default.py for how to set xcfun as the default XC
functional library.
'''
from pyscf impor... | Update the camb3lyp example to libxc 5 series | Update the camb3lyp example to libxc 5 series
| Python | apache-2.0 | sunqm/pyscf,sunqm/pyscf,sunqm/pyscf,sunqm/pyscf |
35aec417f31fce87ff31f255b0781352def48217 | examples/generate_images.py | examples/generate_images.py | from __future__ import print_function
import subprocess
# Compile examples and export them as images
#
# Dependencies:
# * LaTeX distribution (MiKTeX or TeXLive)
# * ImageMagick
#
# Known issue: ImageMagick's "convert" clashes with Windows' "convert"
# Please make a symlink to convert:
# mklink convert-im.exe <path t... | from subprocess import run
# Compile examples and export them as images
#
# Dependencies:
# * LaTeX distribution (MiKTeX or TeXLive)
# * ImageMagick
#
# Known issue: ImageMagick's "convert" clashes with Windows' "convert"
# Please make a symlink to convert:
# mklink convert-im.exe <path to ImageMagick's convert.exe>
... | Refactor examples generation to Python 3 | Refactor examples generation to Python 3
| Python | mit | mp4096/blockschaltbilder |
3974d63721c49564be638c9912ee3e940ca2695d | decisiontree/tasks.py | decisiontree/tasks.py | from threadless_router.router import Router
from decisiontree.models import Session
from celery.task import Task
from celery.registry import tasks
import logging
logger = logging.getLogger()
logging.getLogger().setLevel(logging.DEBUG)
class PeriodicTask(Task):
"""celery task to notice when we haven't gotten a ... | from celery.task import task
from decisiontree.models import Session
@task
def check_for_session_timeout():
"""
Check sessions and send a reminder if they have not responded in
the given threshold.
Note: this requires the threadless router to run.
"""
from threadless_router.router import Rou... | Restructure decisiontree task to use more modern celery patterns and use a soft requirement on using the threadless router. | Restructure decisiontree task to use more modern celery patterns and use a soft requirement on using the threadless router.
| Python | bsd-3-clause | caktus/rapidsms-decisiontree-app,eHealthAfrica/rapidsms-decisiontree-app,ehealthafrica-ci/rapidsms-decisiontree-app,eHealthAfrica/rapidsms-decisiontree-app,caktus/rapidsms-decisiontree-app,ehealthafrica-ci/rapidsms-decisiontree-app,caktus/rapidsms-decisiontree-app |
cb8fe795aff58078a16ae1fac655c04762145abd | subscription/api.py | subscription/api.py | from tastypie import fields
from tastypie.resources import ModelResource
from tastypie.authentication import ApiKeyAuthentication
from tastypie.authorization import Authorization
from subscription.models import Subscription, MessageSet
from djcelery.models import PeriodicTask
class PeriodicTaskResource(ModelResource):... | from tastypie import fields
from tastypie.resources import ModelResource, ALL
from tastypie.authentication import ApiKeyAuthentication
from tastypie.authorization import Authorization
from subscription.models import Subscription, MessageSet
from djcelery.models import PeriodicTask
class PeriodicTaskResource(ModelResou... | Add filter for getting user subs: | Add filter for getting user subs:
| Python | bsd-3-clause | praekelt/ndoh-control,praekelt/ndoh-control,praekelt/ndoh-control,praekelt/ndoh-control |
934ec1300e70be518021d5851bdc380fef844393 | billjobs/tests/tests_export_account_email.py | billjobs/tests/tests_export_account_email.py | from django.test import TestCase
from django.http import HttpResponse
from django.contrib.admin.sites import AdminSite
from django.contrib.auth.models import User
from billjobs.admin import UserAdmin
class MockRequest(object):
pass
class EmailExportTestCase(TestCase):
""" Tests for email account expor... | from django.test import TestCase
from django.http import HttpResponse
from django.contrib.admin.sites import AdminSite
from django.contrib.auth.models import User
from billjobs.admin import UserAdmin
class MockRequest(object):
pass
class EmailExportTestCase(TestCase):
""" Tests for email account expor... | Add comment and reformat code | Add comment and reformat code
| Python | mit | ioO/billjobs |
b35befc9677541295609f4e55eea6fc2c4d7ab08 | office365/runtime/odata/odata_path_parser.py | office365/runtime/odata/odata_path_parser.py | from requests.compat import basestring
class ODataPathParser(object):
@staticmethod
def parse_path_string(string):
pass
@staticmethod
def from_method(method_name, method_parameters):
url = ""
if method_name:
url = method_name
url += "("
if method_p... | from requests.compat import basestring
class ODataPathParser(object):
@staticmethod
def parse_path_string(string):
pass
@staticmethod
def from_method(method_name, method_parameters):
url = ""
if method_name:
url = method_name
url += "("
if method_p... | Add more OData parameter format escapes | Add more OData parameter format escapes
| Python | mit | vgrem/SharePointOnline-REST-Python-Client,vgrem/Office365-REST-Python-Client |
b5601797b0e734514e5958be64576abe9fe684d7 | src/cli.py | src/cli.py | from cmd2 import Cmd, options, make_option
import h5_wrapper
import sys
import os
class CmdApp(Cmd):
def do_ls(self, args, opts=None):
for g in self.explorer.list_groups():
print(g+"/")
for ds in self.explorer.list_datasets():
print(ds)
def do_cd(self, args, o... | from cmd2 import Cmd, options, make_option
import h5_wrapper
import sys
import os
class CmdApp(Cmd):
def do_ls(self, args, opts=None):
if len(args.strip()) > 0:
for g in self.explorer.list_groups(args):
print(g+"/")
for ds in self.explorer.list_dataset... | Allow ls to pass arguments | Allow ls to pass arguments
| Python | mit | ksunden/h5cli |
c01b01bd8ab640f74da0796ac1b6f05f5dc3ebc1 | pytest_cram/tests/test_options.py | pytest_cram/tests/test_options.py | import pytest_cram
pytest_plugins = "pytester"
def test_version():
assert pytest_cram.__version__
def test_cramignore(testdir):
testdir.makeini("""
[pytest]
cramignore =
sub/a*.t
a.t
c*.t
""")
testdir.tmpdir.ensure("sub/a.t")
testdir.tmpdir.en... | import pytest_cram
pytest_plugins = "pytester"
def test_version():
assert pytest_cram.__version__
def test_nocram(testdir):
"""Ensure that --nocram collects .py but not .t files."""
testdir.makefile('.t', " $ true")
testdir.makepyfile("def test_(): assert True")
result = testdir.runpytest("--n... | Test the --nocram command line option | Test the --nocram command line option
| Python | mit | tbekolay/pytest-cram,tbekolay/pytest-cram |
15c51102f8e9f37bb08f9f6c04c7da2d75250cd2 | cabot/cabot_config.py | cabot/cabot_config.py | import os
GRAPHITE_API = os.environ.get('GRAPHITE_API')
GRAPHITE_USER = os.environ.get('GRAPHITE_USER')
GRAPHITE_PASS = os.environ.get('GRAPHITE_PASS')
GRAPHITE_FROM = os.getenv('GRAPHITE_FROM', '-10minute')
JENKINS_API = os.environ.get('JENKINS_API')
JENKINS_USER = os.environ.get('JENKINS_USER')
JENKINS_PASS = os.env... | import os
GRAPHITE_API = os.environ.get('GRAPHITE_API')
GRAPHITE_USER = os.environ.get('GRAPHITE_USER')
GRAPHITE_PASS = os.environ.get('GRAPHITE_PASS')
GRAPHITE_FROM = os.getenv('GRAPHITE_FROM', '-10minute')
JENKINS_API = os.environ.get('JENKINS_API')
JENKINS_USER = os.environ.get('JENKINS_USER')
JENKINS_PASS = os.env... | Convert *_INTERVAL variables to int | Convert *_INTERVAL variables to int
ALERT_INTERVAL and NOTIFICATION_INTERVAL are now converted to
numbers. This allows user-defined ALERT_INTERVAL and
NOTIFICATION_INTERVAL env variables to work without throwing
TypeErrors:
return self.run(*args, **kwargs)
File "/cabot/cabot/cabotapp/tasks.py", line 68, in upda... | Python | mit | arachnys/cabot,reddit/cabot,cmclaughlin/cabot,cmclaughlin/cabot,bonniejools/cabot,dever860/cabot,lghamie/cabot,jdycar/cabot,jdycar/cabot,movermeyer/cabot,xinity/cabot,lghamie/cabot,dever860/cabot,lghamie/cabot,dever860/cabot,cmclaughlin/cabot,arachnys/cabot,maks-us/cabot,mcansky/cabotapp,xinity/cabot,cmclaughlin/cabot,... |
b0c27402da5522db7d8e1b65c81a28b3a19500b0 | pyinfra/modules/virtualenv.py | pyinfra/modules/virtualenv.py | # pyinfra
# File: pyinfra/modules/pip.py
# Desc: manage virtualenvs
'''
Manage Python virtual environments
'''
from __future__ import unicode_literals
from pyinfra.api import operation
from pyinfra.modules import files
@operation
def virtualenv(
state, host,
path, python=None, site_packages=False, always_c... | # pyinfra
# File: pyinfra/modules/pip.py
# Desc: manage virtualenvs
'''
Manage Python virtual environments
'''
from __future__ import unicode_literals
from pyinfra.api import operation
from pyinfra.modules import files
@operation
def virtualenv(
state, host,
path, python=None, site_packages=False, always_c... | Fix relying on pyinfra generator unroll | Fix relying on pyinfra generator unroll
| Python | mit | Fizzadar/pyinfra,Fizzadar/pyinfra |
0ebac1925b3d4b32188a6f2c9e40760b21d933ce | backend/uclapi/dashboard/app_helpers.py | backend/uclapi/dashboard/app_helpers.py | from binascii import hexlify
import os
def generate_api_token():
key = hexlify(os.urandom(30)).decode()
dashes_key = ""
for idx, char in enumerate(key):
if idx % 15 == 0 and idx != len(key)-1:
dashes_key += "-"
else:
dashes_key += char
final = "uclapi" + dashes... | from binascii import hexlify
from random import choice
import os
import string
def generate_api_token():
key = hexlify(os.urandom(30)).decode()
dashes_key = ""
for idx, char in enumerate(key):
if idx % 15 == 0 and idx != len(key)-1:
dashes_key += "-"
else:
dashes_k... | Add helpers to the dashboard code to generate OAuth keys | Add helpers to the dashboard code to generate OAuth keys
| Python | mit | uclapi/uclapi,uclapi/uclapi,uclapi/uclapi,uclapi/uclapi |
63f650855dfc707c6850add17d9171ba003bebcb | ckeditor_demo/urls.py | ckeditor_demo/urls.py | from __future__ import absolute_import
import django
from django.conf import settings
from django.conf.urls import include, url
from django.conf.urls.static import static
from django.contrib import admin
from django.contrib.staticfiles import views
from .demo_application.views import ckeditor_form_view
if django.VER... | from __future__ import absolute_import
import django
from django.conf import settings
from django.conf.urls import include, url
from django.contrib import admin
from django.contrib.staticfiles import views
from .demo_application.views import ckeditor_form_view
if django.VERSION >= (1, 8):
urlpatterns = [
... | Fix media handling in demo application. | Fix media handling in demo application.
| Python | bsd-3-clause | MarcJoan/django-ckeditor,gushedaoren/django-ckeditor,luzfcb/django-ckeditor,luzfcb/django-ckeditor,luzfcb/django-ckeditor,gushedaoren/django-ckeditor,zatarus/django-ckeditor,zatarus/django-ckeditor,Josephpaik/django-ckeditor,MarcJoan/django-ckeditor,gushedaoren/django-ckeditor,zatarus/django-ckeditor,MarcJoan/django-ck... |
543509e991f88ecad7e5ed69db6d3b175fe44351 | tests/constants.py | tests/constants.py | TEST_TOKEN = 'azGDORePK8gMaC0QOYAMyEEuzJnyUi'
TEST_USER = 'uQiRzpo4DXghDmr9QzzfQu27cmVRsG'
TEST_GROUP = ''
TEST_BAD_USER = '1234'
TEST_DEVICES = ['droid2', 'iPhone']
TEST_TITLE = 'Backup finished - SQL1'
TEST_MESSAGE = 'Backup of database "example" finished in 16 minutes.'
TEST_REQUEST_ID = 'e460545a8b333d0da2f3602aff3... | TEST_TOKEN = 'azGDORePK8gMaC0QOYAMyEEuzJnyUi'
TEST_USER = 'uQiRzpo4DXghDmr9QzzfQu27cmVRsG'
TEST_BAD_USER = '1234'
TEST_GROUP = 'gznej3rKEVAvPUxu9vvNnqpmZpokzF'
TEST_DEVICES = ['droid2', 'iPhone']
TEST_TITLE = 'Backup finished - SQL1'
TEST_MESSAGE = 'Backup of database "example" finished in 16 minutes.'
TEST_REQUEST_ID ... | Add a test group key | Add a test group key
| Python | mit | scolby33/pushover_complete |
8e0f2271b19504886728ccf5d060778c027c79ca | ide/views.py | ide/views.py | import json
from werkzeug.routing import BaseConverter
from flask import render_template, request, abort
import requests
from ide import app
from ide.projects import get_all_projects, Project
MCLABAAS_URL = 'http://localhost:4242'
@app.route('/')
def index():
return render_template('index.html', projects=get_al... | import json
from werkzeug.routing import BaseConverter
from flask import render_template, request, abort
import requests
from ide import app
from ide.projects import get_all_projects, Project
MCLABAAS_URL = 'http://localhost:4242'
@app.route('/')
def index():
return render_template('index.html', projects=get_al... | Check if project exists inside ProjectConverter. | Check if project exists inside ProjectConverter.
| Python | apache-2.0 | Sable/mclab-ide,Sable/mclab-ide,Sable/mclab-ide,Sable/mclab-ide,Sable/mclab-ide,Sable/mclab-ide |
5eb96c599dbbef56853dfb9441ab2eb54d36f9b7 | ckanext/syndicate/tests/test_plugin.py | ckanext/syndicate/tests/test_plugin.py | from mock import patch
import unittest
import ckan.model as model
from ckan.model.domain_object import DomainObjectOperation
from ckanext.syndicate.plugin import SyndicatePlugin
class TestNotify(unittest.TestCase):
def setUp(self):
super(TestNotify, self).setUp()
self.entity = model.Package()
... | from mock import patch
import unittest
import ckan.model as model
from ckan.model.domain_object import DomainObjectOperation
from ckanext.syndicate.plugin import SyndicatePlugin
class TestNotify(unittest.TestCase):
def setUp(self):
super(TestNotify, self).setUp()
self.entity = model.Package()
... | Add test for notify dataset/delete | Add test for notify dataset/delete
| Python | agpl-3.0 | aptivate/ckanext-syndicate,aptivate/ckanext-syndicate,sorki/ckanext-redmine-autoissues,sorki/ckanext-redmine-autoissues |
c9631819179eb99728c0ad7f3d6b46aef6dea079 | polygraph/types/object_type.py | polygraph/types/object_type.py | from collections import OrderedDict
from graphql.type.definition import GraphQLObjectType
from marshmallow import Schema, SchemaOpts
from polygraph.utils.trim_docstring import trim_docstring
class ObjectTypeOpts(SchemaOpts):
def __init__(self, meta, **kwargs):
SchemaOpts.__init__(self, meta, **kwargs)
... | from collections import OrderedDict
from graphql.type.definition import GraphQLObjectType
from marshmallow import Schema, SchemaOpts
from polygraph.utils.trim_docstring import trim_docstring
class ObjectTypeOpts(SchemaOpts):
def __init__(self, meta, **kwargs):
SchemaOpts.__init__(self, meta, **kwargs)
... | Fix ObjectType name and description attributes | Fix ObjectType name and description attributes
| Python | mit | polygraph-python/polygraph |
ac5b9765d69139915f06bd52d96b1abaa3d41331 | scuole/districts/views.py | scuole/districts/views.py | # -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from django.views.generic import DetailView, ListView
from .models import District
class DistrictListView(ListView):
queryset = District.objects.all().select_related('county__name')
class DistrictDetailView(DetailView):
query... | # -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from django.views.generic import DetailView, ListView
from .models import District
class DistrictListView(ListView):
queryset = District.objects.all().defer('shape')
class DistrictDetailView(DetailView):
queryset = District.o... | Remove unused select_related, defer the loading of shape for speed | Remove unused select_related, defer the loading of shape for speed
| Python | mit | texastribune/scuole,texastribune/scuole,texastribune/scuole,texastribune/scuole |
924be2b545a4d00b9eacc5aa1c974e8ebf407c2f | shade/tests/unit/test_shade.py | shade/tests/unit/test_shade.py | # -*- coding: utf-8 -*-
# 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, softw... | # -*- coding: utf-8 -*-
# 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, softw... | Add basic unit test for shade.openstack_cloud | Add basic unit test for shade.openstack_cloud
Just getting basic minimal surface area unit tests to help when making
changes. This exposed some python3 incompatibilities in
os-client-config, which is why the change Depends on
Ia78bd8edd17c7d2360ad958b3de734503d400774.
Change-Id: I9cf5082d01861a0b6b372728a33ce9df9ee8d... | Python | apache-2.0 | stackforge/python-openstacksdk,openstack-infra/shade,openstack/python-openstacksdk,openstack/python-openstacksdk,openstack-infra/shade,dtroyer/python-openstacksdk,stackforge/python-openstacksdk,dtroyer/python-openstacksdk,jsmartin/shade,jsmartin/shade |
3f29248fc8159030417750e900a0e4c940883b4e | conf/models.py | conf/models.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.contrib.auth import get_user_model
from django.db import models
from django.db.models.signals import post_save
from django.contrib.sites.models import Site
from django.dispatch import receiver
class Conf(models.Model):
site = models.OneT... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.contrib.auth import get_user_model
from django.db import models
from django.db.models.signals import post_save
from django.contrib.sites.models import Site
from django.dispatch import receiver
class Conf(models.Model):
site = models.OneT... | Add verbose name to Conf model. | Add verbose name to Conf model.
| Python | bsd-2-clause | overshard/timestrap,overshard/timestrap,muhleder/timestrap,cdubz/timestrap,muhleder/timestrap,overshard/timestrap,cdubz/timestrap,muhleder/timestrap,cdubz/timestrap |
b9b4089fcd7f26ebf339c568ba6454d538a1813e | zk_shell/cli.py | zk_shell/cli.py | from __future__ import print_function
import argparse
import logging
import sys
from . import __version__
from .shell import Shell
try:
raw_input
except NameError:
raw_input = input
class CLI(object):
def run(self):
logging.basicConfig(level=logging.ERROR)
params = self.get_params()
... | from __future__ import print_function
import argparse
import logging
import sys
from . import __version__
from .shell import Shell
try:
raw_input
except NameError:
raw_input = input
class CLI(object):
def run(self):
logging.basicConfig(level=logging.ERROR)
params = self.get_params()
... | Handle IOError in run_once mode so paging works | Handle IOError in run_once mode so paging works
Signed-off-by: Raul Gutierrez S <f25f6873bbbde69f1fe653b3e6bd40d543b8d0e0@itevenworks.net>
| Python | apache-2.0 | harlowja/zk_shell,harlowja/zk_shell,rgs1/zk_shell,rgs1/zk_shell |
623b170985a69a713db2d3c4887ed3b2ed8dc368 | feincms_extensions/content_types.py | feincms_extensions/content_types.py | from feincms.content.medialibrary.models import MediaFileContent
from feincms.content.richtext.models import RichTextContent
from feincms.content.section.models import SectionContent
class JsonRichTextContent(RichTextContent):
class Meta(RichTextContent.Meta):
abstract = True
def json(self, **kwargs)... | from feincms.content.medialibrary.models import MediaFileContent
from feincms.content.richtext.models import RichTextContent
from feincms.content.section.models import SectionContent
class JsonRichTextContent(RichTextContent):
class Meta(RichTextContent.Meta):
abstract = True
def json(self, **kwargs)... | Add id to json content types | Add id to json content types
Tests will probably fail! | Python | bsd-2-clause | incuna/feincms-extensions,incuna/feincms-extensions |
45ee26fae4a8d31b66e3307c0ab4aed21678b4b6 | scrubadub/filth/named_entity.py | scrubadub/filth/named_entity.py | from .base import Filth
class NamedEntityFilth(Filth):
"""
Named entity filth. Upon initialisation provide a label for named entity (e.g. name, org)
"""
type = 'named_entity'
def __init__(self, *args, label: str, **kwargs):
super(NamedEntityFilth, self).__init__(*args, **kwargs)
s... | from .base import Filth
class NamedEntityFilth(Filth):
"""
Named entity filth. Upon initialisation provide a label for named entity (e.g. name, org)
"""
type = 'named_entity'
def __init__(self, *args, label: str, **kwargs):
super(NamedEntityFilth, self).__init__(*args, **kwargs)
s... | Revert NamedEntityFilth name because it was a bad idea | Revert NamedEntityFilth name because it was a bad idea
| Python | mit | deanmalmgren/scrubadub,datascopeanalytics/scrubadub,deanmalmgren/scrubadub,datascopeanalytics/scrubadub |
6c0e6e79c05b95001ad4c7c1f6ab3b505ffbd6a5 | examples/comparator_example.py | examples/comparator_example.py | import pprint
import maec.bindings.maec_bundle as maec_bundle_binding
from maec.bundle.bundle import Bundle
# Matching properties dictionary
match_on_dictionary = {'FileObjectType': ['file_name'],
'WindowsRegistryKeyObjectType': ['hive', 'values.name/data'],
'WindowsMutexOb... | import pprint
import maec.bindings.maec_bundle as maec_bundle_binding
from maec.bundle.bundle import Bundle
# Matching properties dictionary
match_on_dictionary = {'FileObjectType': ['full_name'],
'WindowsRegistryKeyObjectType': ['hive', 'values.name/data'],
'WindowsMutexOb... | Change comparison parameter in example | Change comparison parameter in example
| Python | bsd-3-clause | MAECProject/python-maec |
c3e034de03ee45bb161c06bcff870839f9ed4d4b | django_lti_tool_provider/tests/urls.py | django_lti_tool_provider/tests/urls.py | from django.conf.urls import patterns, url
from django_lti_tool_provider import views as lti_views
urlpatterns = [
url(r'', lti_views.LTIView.as_view(), name='home'),
url('^accounts/login/$', 'django.contrib.auth.views.login'),
url(r'^lti$', lti_views.LTIView.as_view(), name='lti')
] | from django.conf.urls import url
from django_lti_tool_provider import views as lti_views
urlpatterns = [
url(r'', lti_views.LTIView.as_view(), name='home'),
url('^accounts/login/$', 'django.contrib.auth.views.login'),
url(r'^lti$', lti_views.LTIView.as_view(), name='lti')
] | Remove reference to deprecated "patterns" function. | Remove reference to deprecated "patterns" function.
This function is no longer available starting with Django 1.10.
Cf. https://docs.djangoproject.com/en/2.1/releases/1.10/#features-removed-in-1-10
| Python | agpl-3.0 | open-craft/django-lti-tool-provider |
18fec1124bb86f90183350e7b9c86eb946a01884 | whatchanged/main.py | whatchanged/main.py | #!/usr/bin/env python
from __future__ import absolute_import, print_function
# Standard library
from os import walk
from os.path import exists, isdir, join
# Local library
from .util import is_py_file
from .diff import diff_files
def main():
import sys
if sys.argv < 3:
print('Usage: %s <module1> <... | #!/usr/bin/env python
from __future__ import absolute_import, print_function
# Standard library
from os import walk
from os.path import exists, isdir, join
# Local library
from .util import is_py_file
from .diff import diff_files
def main():
import sys
if len(sys.argv) < 3:
print('Usage: %s <packa... | Fix minor bug in length comparison. | Fix minor bug in length comparison.
| Python | bsd-2-clause | punchagan/what-changed |
2a08a8a6d5cdac0ddcbaf34977c119c5b75bbe8d | wtforms_webwidgets/__init__.py | wtforms_webwidgets/__init__.py | """
WTForms Extended Widgets
########################
This package aims to one day eventually contain advanced widgets for all the
common web UI frameworks.
Currently this module contains widgets for:
- Boostrap
"""
# from .common import *
from .common import CustomWidgetMixin, custom_widget_wrapper, FieldRender... | """
WTForms Extended Widgets
########################
This package aims to one day eventually contain advanced widgets for all the
common web UI frameworks.
Currently this module contains widgets for:
- Boostrap
"""
from .common import *
| Revert "Possible fix for docs not rendering auto" | Revert "Possible fix for docs not rendering auto"
This reverts commit 88c3fd3c4b23b12f4b68d3f5a13279870486d4b2.
| Python | mit | nickw444/wtforms-webwidgets |
0e7edc1359726ce3257cf67dbb88408979be6a0b | doc/quickstart/testlibs/LoginLibrary.py | doc/quickstart/testlibs/LoginLibrary.py | import os
import sys
class LoginLibrary:
def __init__(self):
self._sut_path = os.path.join(os.path.dirname(__file__),
'..', 'sut', 'login.py')
self._status = ''
def create_user(self, username, password):
self._run_command('create', username, pass... | import os
import sys
import subprocess
class LoginLibrary:
def __init__(self):
self._sut_path = os.path.join(os.path.dirname(__file__),
'..', 'sut', 'login.py')
self._status = ''
def create_user(self, username, password):
self._run_command('creat... | Use subprocess isntead of popen to get Jython working too | Use subprocess isntead of popen to get Jython working too
| Python | apache-2.0 | ldtri0209/robotframework,ldtri0209/robotframework,waldenner/robotframework,waldenner/robotframework,fiuba08/robotframework,waldenner/robotframework,ldtri0209/robotframework,fiuba08/robotframework,waldenner/robotframework,ldtri0209/robotframework,fiuba08/robotframework,waldenner/robotframework,fiuba08/robotframework,fiu... |
ea3f4934ffa8b88d8716f6550134c37e300c4003 | sqlitebiter/_const.py | sqlitebiter/_const.py | # encoding: utf-8
"""
.. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com>
"""
from __future__ import absolute_import, unicode_literals
PROGRAM_NAME = "sqlitebiter"
MAX_VERBOSITY_LEVEL = 2
IPYNB_FORMAT_NAME_LIST = ["ipynb"]
TABLE_NOT_FOUND_MSG_FORMAT = "table not found in {}"
| # encoding: utf-8
"""
.. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com>
"""
from __future__ import absolute_import, unicode_literals
PROGRAM_NAME = "sqlitebiter"
MAX_VERBOSITY_LEVEL = 2
IPYNB_FORMAT_NAME_LIST = ["ipynb"]
TABLE_NOT_FOUND_MSG_FORMAT = "convertible table not found in {}"
| Modify a log message template | Modify a log message template
| Python | mit | thombashi/sqlitebiter,thombashi/sqlitebiter |
15490a05696e5e37aa98af905669967fe406eb1d | runtests.py | runtests.py | #!/usr/bin/env python
from os.path import dirname, abspath
import sys
from django.conf import settings
if not settings.configured:
from django import VERSION
settings_dict = dict(
INSTALLED_APPS=(
'localeurl',
),
ROOT_URLCONF='localeurl.tests.test_urls',
)
... | #!/usr/bin/env python
from os.path import dirname, abspath
import sys
from django.conf import settings
if not settings.configured:
from django import VERSION
settings_dict = dict(
INSTALLED_APPS=(
'localeurl',
'django.contrib.sites', # for sitemap test
),
R... | Include contrib.sites when running tests; needed for sitemaps in Django >= 1.2. | Include contrib.sites when running tests; needed for sitemaps in Django >= 1.2.
| Python | mit | simonluijk/django-localeurl,jmagnusson/django-localeurl |
4e6ee7ed1d0e6cc105dad537dc79e12bdcbe9a40 | geozones/factories.py | geozones/factories.py | # coding: utf-8
import factory
import random
from .models import Location, Region
class RegionFactory(factory.Factory):
FACTORY_FOR = Region
name = factory.Sequence(lambda n: "Region_%s" % n)
slug = factory.LazyAttribute(lambda a: a.name.lower())
latitude = random.uniform(-90.0, 90.0)
longitude... | # coding: utf-8
import factory
import random
from .models import Location, Region
class RegionFactory(factory.Factory):
FACTORY_FOR = Region
name = factory.Sequence(lambda n: "Region_%s" % n)
slug = factory.LazyAttribute(lambda a: a.name.lower())
latitude = random.uniform(-90.0, 90.0)
longitude... | Fix location factory field name | Fix location factory field name
| Python | mit | sarutobi/flowofkindness,sarutobi/Rynda,sarutobi/ritmserdtsa,sarutobi/Rynda,sarutobi/Rynda,sarutobi/flowofkindness,sarutobi/Rynda,sarutobi/ritmserdtsa,sarutobi/ritmserdtsa,sarutobi/flowofkindness,sarutobi/flowofkindness,sarutobi/ritmserdtsa |
989abb47041e6a172765453c750c31144a92def5 | doc/rst2html-manual.py | doc/rst2html-manual.py | #!/usr/bin/env python3
"""
A minimal front end to the Docutils Publisher, producing HTML.
"""
import locale
from docutils.core import publish_cmdline, default_description
from docutils.parsers.rst import directives
from docutils.parsers.rst import roles
from rst2pdf.directives import code_block
from rst2pdf.directi... | #!/usr/bin/env python3
# -*- coding: utf8 -*-
# :Copyright: © 2015 Günter Milde.
# :License: Released under the terms of the `2-Clause BSD license`_, in short:
#
# Copying and distribution of this file, with or without modification,
# are permitted in any medium without royalty provided the copyright
# notice ... | Switch rst2html to HTML5 builder | Switch rst2html to HTML5 builder
This gives a prettier output and every browser in widespread usage has
supported it for years. The license, which was previously missing, is
added.
Signed-off-by: Stephen Finucane <06fa905d7f2aaced6dc72e9511c71a2a51e8aead@that.guru>
| Python | mit | rst2pdf/rst2pdf,rst2pdf/rst2pdf |
8244b6196ce84949e60174f844f80357c8a23478 | build/fbcode_builder/specs/fbthrift.py | build/fbcode_builder/specs/fbthrift.py | #!/usr/bin/env python
# Copyright (c) Facebook, Inc. and its affiliates.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import specs.folly as folly
import specs.fizz as fizz
import specs.rsocket as rsocket
import spec... | #!/usr/bin/env python
# Copyright (c) Facebook, Inc. and its affiliates.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import specs.folly as folly
import specs.fizz as fizz
import specs.fmt as fmt
import specs.rsocke... | Migrate from Folly Format to fmt | Migrate from Folly Format to fmt
Summary: Migrate from Folly Format to fmt which provides smaller compile times and per-call binary code size.
Reviewed By: alandau
Differential Revision: D14954926
fbshipit-source-id: 9d2c39e74a5d11e0f90c8ad0d71b79424c56747f
| Python | apache-2.0 | facebook/wangle,facebook/wangle,facebook/wangle |
18818a8dfebcc44f9e8b582c15d6185f9a7a0c45 | minicms/templatetags/cms.py | minicms/templatetags/cms.py | from ..models import Block
from django.template import Library
register = Library()
@register.simple_tag
def show_block(name):
try:
return Block.objects.get(name=name).content
except Block.DoesNotExist:
return ''
except Block.MultipleObjectsReturned:
return 'Error: Multiple blocks ... | from ..models import Block
from django.template import Library
register = Library()
@register.simple_tag
def show_block(name):
try:
return Block.objects.get(name=name).content
except Block.DoesNotExist:
return ''
except Block.MultipleObjectsReturned:
return 'Error: Multiple blocks ... | Allow "Home" to be active menu item | Allow "Home" to be active menu item
| Python | bsd-3-clause | adieu/allbuttonspressed,adieu/allbuttonspressed |
2efff9eb852ec2a8f38b4c21ecc6e62898891901 | test/run_tests.py | test/run_tests.py | # Monary - Copyright 2011-2013 David J. C. Beach
# Please see the included LICENSE.TXT and NOTICE.TXT for licensing information.
import os
from os import listdir
from os.path import isfile, join
from inspect import getmembers, isfunction
def main():
abspath = os.path.abspath(__file__)
test_path = list(os.path... | # Monary - Copyright 2011-2013 David J. C. Beach
# Please see the included LICENSE.TXT and NOTICE.TXT for licensing information.
"""
Note: This runs all of the tests. Maybe
this will be removed eventually?
"""
import os
from os import listdir
from os.path import isfile, join
from inspect import getmembers, isfu... | Add quick comment to explain test_runner.py | Add quick comment to explain test_runner.py
| Python | apache-2.0 | ksuarz/monary,ksuarz/mongo-monary-driver,ksuarz/monary,ksuarz/monary,ksuarz/mongo-monary-driver,ksuarz/monary,ksuarz/monary,ksuarz/monary |
f2703d18fc758033e7df582772b3abb973497562 | message/serializers.py | message/serializers.py | # -*- coding: utf-8 -*-
from rest_framework import serializers
from message.models import Message
class MessageSerializer(serializers.ModelSerializer):
class Meta:
model = Message
class MapMessageSerializer(serializers.ModelSerializer):
lat = serializers.Field(source='location.latitude')
lon =... | # -*- coding: utf-8 -*-
from rest_framework import serializers
from message.models import Message
class MessageSerializer(serializers.ModelSerializer):
class Meta:
model = Message
class MapMessageSerializer(serializers.ModelSerializer):
lat = serializers.Field(source='location.latitude')
lon =... | Add message type field for api serializer | Add message type field for api serializer
| Python | mit | sarutobi/Rynda,sarutobi/flowofkindness,sarutobi/ritmserdtsa,sarutobi/Rynda,sarutobi/ritmserdtsa,sarutobi/Rynda,sarutobi/Rynda,sarutobi/flowofkindness,sarutobi/ritmserdtsa,sarutobi/flowofkindness,sarutobi/ritmserdtsa,sarutobi/flowofkindness |
03d4c298add892e603e48ca35b1a5070f407d6ff | actions/cloudbolt_plugins/recurring_jobs/remove_.zip_from_tmp.py | actions/cloudbolt_plugins/recurring_jobs/remove_.zip_from_tmp.py | """
This action removes all the zip files from CloudBolt /tmp/systemd-private* directory.
"""
from common.methods import set_progress
import glob
import os
def run(job, *args, **kwargs):
zip_file_list = glob.glob("/tmp/systemd-private*/tmp/*.zip")
set_progress("Found following zip files in /tmp:... | """
This action removes all the zip files from CloudBolt /tmp/systemd-private* directory.
"""
from common.methods import set_progress
import glob
import os
import time
def run(job, *args, **kwargs):
zip_file_list = glob.glob("/tmp/systemd-private*/tmp/*.zip")
set_progress("Found following zip f... | Remove only those files that were stored 5 minutes ago. | Remove only those files that were stored 5 minutes ago.
[https://cloudbolt.atlassian.net/browse/DEV-12629]
| Python | apache-2.0 | CloudBoltSoftware/cloudbolt-forge,CloudBoltSoftware/cloudbolt-forge,CloudBoltSoftware/cloudbolt-forge,CloudBoltSoftware/cloudbolt-forge |
617919d11722e2cc191f3dcecabfbe08f5d93caf | lib/utils.py | lib/utils.py | # General utility library
from re import match
import inspect
import sys
import ctypes
import logging
logger = logging.getLogger(__name__)
def comma_sep_list(lst):
"""Set up string or list to URL list parameter format"""
if not isinstance(lst, basestring):
# Convert list to proper format for URL para... | # General utility library
from re import match
import inspect
import sys
import ctypes
import logging
logger = logging.getLogger(__name__)
def comma_sep_list(input_lst):
"""Set up string or list to URL list parameter format"""
if not isinstance(input_lst, basestring):
# Convert list to proper format ... | Fix issue where last email was truncated | Fix issue where last email was truncated
| Python | unlicense | CodingAnarchy/Amon |
c79e6b16e29dc0c756bfe82d62b9e01a5702c47f | testanalyzer/pythonanalyzer.py | testanalyzer/pythonanalyzer.py | import re
from fileanalyzer import FileAnalyzer
class PythonAnalyzer(FileAnalyzer):
def get_class_count(self, content):
return len(
re.findall("[^\"](class +[a-zA-Z0-9_]+ *\(?[a-zA-Z0-9_, ]*\)? *:)+[^\"]",
content))
def get_function_count(self, content):
ret... | import re
from fileanalyzer import FileAnalyzer
class PythonAnalyzer(FileAnalyzer):
def get_class_count(self, content):
matches = re.findall("\"*class +[a-zA-Z0-9_]+ *\(?[a-zA-Z0-9_, ]*\)? *:\"*", content)
matches = [m for m in matches if m.strip()[0] != "\"" and m.strip()[-1] != "\""]
ret... | Fix counter to ignore quoted lines | Fix counter to ignore quoted lines
| Python | mpl-2.0 | CheriPai/TestAnalyzer,CheriPai/TestAnalyzer,CheriPai/TestAnalyzer |
f7f1960176c32569397441229a0a3bcac926cd82 | go_contacts/backends/tests/test_riak.py | go_contacts/backends/tests/test_riak.py | """
Tests for riak contacts backend and collection.
"""
from twisted.trial.unittest import TestCase
from zope.interface.verify import verifyObject
from go_api.collections import ICollection
from go_contacts.backends.riak import (
RiakContactsBackend, RiakContactsCollection)
class TestRiakContactsBackend(TestCa... | """
Tests for riak contacts backend and collection.
"""
from twisted.trial.unittest import TestCase
from zope.interface.verify import verifyObject
from go_api.collections import ICollection
from go_contacts.backends.riak import (
RiakContactsBackend, RiakContactsCollection)
class TestRiakContactsBackend(TestCa... | Add stubby test for getting a contact. | Add stubby test for getting a contact.
| Python | bsd-3-clause | praekelt/go-contacts-api,praekelt/go-contacts-api |
7e6a8de053383a322ecc2416dc1a2700ac5fed29 | tests/argument.py | tests/argument.py | from spec import Spec, eq_, skip, ok_, raises
from invoke.parser import Argument
class Argument_(Spec):
def may_take_names_list(self):
names = ('--foo', '-f')
a = Argument(names=names)
for name in names:
assert a.answers_to(name)
def may_take_name_arg(self):
asser... | from spec import Spec, eq_, skip, ok_, raises
from invoke.parser import Argument
class Argument_(Spec):
def may_take_names_list(self):
names = ('--foo', '-f')
a = Argument(names=names)
for name in names:
assert a.answers_to(name)
def may_take_name_arg(self):
asser... | Add .names to Argument API | Add .names to Argument API
| Python | bsd-2-clause | mattrobenolt/invoke,singingwolfboy/invoke,frol/invoke,pyinvoke/invoke,pfmoore/invoke,tyewang/invoke,frol/invoke,pyinvoke/invoke,mattrobenolt/invoke,pfmoore/invoke,kejbaly2/invoke,mkusz/invoke,mkusz/invoke,kejbaly2/invoke,sophacles/invoke,alex/invoke |
532c80a61bb428fa9b2d73cfd227dc6e95a77c00 | tests/conftest.py | tests/conftest.py | collect_ignore = []
try:
import asyncio
except ImportError:
collect_ignore.append('test_asyncio.py')
| from sys import version_info as v
collect_ignore = []
if not (v[0] >= 3 and v[1] >= 5):
collect_ignore.append('test_asyncio.py')
| Exclude asyncio tests from 3.4 | Exclude asyncio tests from 3.4
| Python | mit | jfhbrook/pyee |
c9340c70bd6d974e98244a1c3208c3a061aec9bb | tests/cortests.py | tests/cortests.py | #!/usr/bin/python
import unittest
import numpy as np
from corfunc import porod, guinier, fitguinier
class TestStringMethods(unittest.TestCase):
def test_porod(self):
self.assertEqual(porod(1, 1, 0), 1)
def test_guinier(self):
self.assertEqual(guinier(1, 1, 0), 1)
def test_sane_fit(self)... | #!/usr/bin/python
import unittest
import numpy as np
from corfunc import porod, guinier, fitguinier, smooth
class TestStringMethods(unittest.TestCase):
def test_porod(self):
self.assertEqual(porod(1, 1, 0), 1)
def test_guinier(self):
self.assertEqual(guinier(1, 1, 0), 1)
def test_sane_f... | Add tests for function smoothing | Add tests for function smoothing
| Python | mit | rprospero/corfunc-py |
1d7cd9fd4bd52cc5917373ff543c5cdb2b22e9bb | tests/test_now.py | tests/test_now.py | # -*- coding: utf-8 -*-
from freezegun import freeze_time
from jinja2 import Environment, exceptions
import pytest
@pytest.fixture(scope='session')
def environment():
return Environment(extensions=['jinja2_time.TimeExtension'])
def test_tz_is_required(environment):
with pytest.raises(exceptions.TemplateSyn... | # -*- coding: utf-8 -*-
import pytest
from freezegun import freeze_time
from jinja2 import Environment, exceptions
@pytest.fixture(scope='session')
def environment():
return Environment(extensions=['jinja2_time.TimeExtension'])
def test_tz_is_required(environment):
with pytest.raises(exceptions.TemplateSy... | Add a parametrized test for valid timezones | Add a parametrized test for valid timezones
| Python | mit | hackebrot/jinja2-time |
db32e404651533acb857c59a565f539805011c7f | user/consumers.py | user/consumers.py | import json
from channels import Group
from channels.auth import channel_session_user, channel_session_user_from_http
from django.dispatch import receiver
from django.db.models.signals import post_save
from event.models import Event
@receiver(post_save, sender=Event)
def send_update(sender, instance, **kwargs):
... | import json
from channels import Group
from channels.auth import channel_session_user, channel_session_user_from_http
from django.dispatch import receiver
from django.db.models.signals import post_save
from event.models import Event
@receiver(post_save, sender=Event)
def send_update(sender, instance, **kwargs):
... | Add sending a message to event subscribers | Add sending a message to event subscribers
| Python | mit | FedorSelitsky/eventrack,FedorSelitsky/eventrack,FedorSelitsky/eventrack,FedorSelitsky/eventrack |
a3811c7ba8ac59853002e392d29ab4b3800bf096 | src/test/testlexer.py | src/test/testlexer.py |
from cStringIO import StringIO
from nose.tools import *
from parse import EeyoreLexer
def _lex( string ):
return list( EeyoreLexer.Lexer( StringIO( string ) ) )
def _assert_token( token, text, tp, line = None, col = None ):
assert_equal( token.getText(), text )
assert_equal( token.getType(), tp )
if... |
from cStringIO import StringIO
from nose.tools import *
from parse import EeyoreLexer
def _lex( string ):
return list( EeyoreLexer.Lexer( StringIO( string ) ) )
def _assert_token( token, text, tp, line = None, col = None ):
assert_equal( token.getText(), text )
assert_equal( token.getType(), tp )
if... | Add a test for lexing an import statment. | Add a test for lexing an import statment.
| Python | mit | andybalaam/pepper,andybalaam/pepper,andybalaam/pepper,andybalaam/pepper,andybalaam/pepper |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.