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 |
|---|---|---|---|---|---|---|---|---|---|
8aae2526f4e565982f8c57c25d796c59d17e6c46 | components/lie_graph/lie_graph/graph_model_classes/model_files.py | components/lie_graph/lie_graph/graph_model_classes/model_files.py | # -*- coding: utf-8 -*-
"""
file: model_files.py
Graph model classes for working with files
"""
import os
import logging
from lie_graph.graph_mixin import NodeEdgeToolsBaseClass
class FilePath(NodeEdgeToolsBaseClass):
@property
def exists(self):
path = self.get()
if path:
ret... | # -*- coding: utf-8 -*-
"""
file: model_files.py
Graph model classes for working with files
"""
import os
import logging
from lie_graph.graph_mixin import NodeEdgeToolsBaseClass
class FilePath(NodeEdgeToolsBaseClass):
@property
def exists(self):
path = self.get()
if path:
ret... | Rename create_dirs method to makedirs in line with os.path method | Rename create_dirs method to makedirs in line with os.path method
| Python | apache-2.0 | MD-Studio/MDStudio,MD-Studio/MDStudio,MD-Studio/MDStudio,MD-Studio/MDStudio,MD-Studio/MDStudio |
3e488750a460afa549795d7189f5c5b1c43f96e0 | avalon/houdini/__init__.py | avalon/houdini/__init__.py | from .pipeline import (
install,
uninstall,
Creator,
ls,
containerise,
)
from .lib import (
lsattr,
lsattrs,
read,
maintained_selection,
unique_name
)
__all__ = [
"install",
"uninstall",
"Creator",
"ls",
"containerise",
# Utility functions
"m... | from .pipeline import (
install,
uninstall,
Creator,
ls,
containerise,
)
from .lib import (
lsattr,
lsattrs,
read,
maintained_selection,
unique_name
)
__all__ = [
"install",
"uninstall",
"Creator",
"ls",
"containerise",
# Utility functions
"l... | Reorder so it's similar to imports, purely cosmetics/readability | Reorder so it's similar to imports, purely cosmetics/readability
| Python | mit | getavalon/core,mindbender-studio/core,mindbender-studio/core,getavalon/core |
eda7125f28a9da3c5ccefb3ec5c604ddd23d3034 | plantcv/plantcv/plot_image.py | plantcv/plantcv/plot_image.py | # Plot image to screen
import cv2
import numpy
import matplotlib
from plantcv.plantcv import params
from matplotlib import pyplot as plt
from plantcv.plantcv import fatal_error
def plot_image(img, cmap=None):
"""Plot an image to the screen.
:param img: numpy.ndarray
:param cmap: str
:return:
"""
... | # Plot image to screen
import cv2
import numpy
import matplotlib
from plantcv.plantcv import params
from matplotlib import pyplot as plt
from plantcv.plantcv import fatal_error
def plot_image(img, cmap=None):
"""Plot an image to the screen.
:param img: numpy.ndarray
:param cmap: str
:return:
"""
... | Create a new figure for each plot | Create a new figure for each plot
| Python | mit | danforthcenter/plantcv,stiphyMT/plantcv,danforthcenter/plantcv,danforthcenter/plantcv,stiphyMT/plantcv,stiphyMT/plantcv |
607ba7481abc7556c247e140b963dfc9d5bd2161 | examples/strings.py | examples/strings.py | import collections
import collections.abc
def strings_have_format_map_method():
"""
As of Python 3.2 you can use the .format_map() method on a string object
to use mapping objects (not just builtin dictionaries) when formatting
a string.
"""
class Default(dict):
def __missing__(self,... | import collections
import collections.abc
def strings_have_format_map_method():
"""
As of Python 3.2 you can use the .format_map() method on a string object
to use mapping objects (not just builtin dictionaries) when formatting
a string.
"""
class Default(dict):
def __missing__(self,... | Make string example a bit less confusing | Make string example a bit less confusing
| Python | mit | svisser/python-3-examples |
ca9cd229faaa0fc43a2ac0e4c6354331c0b57550 | nengo_spinnaker/simulator.py | nengo_spinnaker/simulator.py | import sys
from pacman103.core import control
from pacman103 import conf
from . import builder
class Simulator(object):
def __init__(self, model, dt=0.001, seed=None):
# Build the model
self.builder = builder.Builder()
self.dao = self.builder(model, dt, seed)
self.dao.writeTextSp... | import sys
from pacman103.core import control
from pacman103 import conf
from . import builder
class Simulator(object):
def __init__(self, model, dt=0.001, seed=None):
# Build the model
self.builder = builder.Builder()
self.dao = self.builder(model, dt, seed)
self.dao.writeTextSp... | Allow vertices to define a `prepare_vertex` function which will be called just once at some point in the build process. | Allow vertices to define a `prepare_vertex` function which will be called just once at some point in the build process.
| Python | mit | ctn-archive/nengo_spinnaker_2014,ctn-archive/nengo_spinnaker_2014,ctn-archive/nengo_spinnaker_2014,ctn-archive/nengo_spinnaker_2014 |
7cfdde79d161b463bf720cd7e222812280d09cdc | src/fabfile.py | src/fabfile.py | import os
# pylint: disable=unused-wildcard-import,unused-import,wildcard-import
SRC_DIR = os.path.dirname(os.path.abspath(__file__)) # elife-builder/src/
# once called 'THIS_DIR', now deprecated as confusing.
PROJECT_DIR = os.path.dirname(SRC_DIR) # elife-builder/
from cfn import *
# aws tasks are not working ... | import os
# pylint: disable=unused-wildcard-import,unused-import,wildcard-import
SRC_DIR = os.path.dirname(os.path.abspath(__file__)) # elife-builder/src/
# once called 'THIS_DIR', now deprecated as confusing.
PROJECT_DIR = os.path.dirname(SRC_DIR) # elife-builder/
from cfn import *
# aws tasks are not working ... | Remove commented out packer import | Remove commented out packer import
| Python | mit | elifesciences/builder,elifesciences/builder |
d731b4172592ef905101868b43817f25f5b04063 | virtstrap/exceptions.py | virtstrap/exceptions.py | class CommandConfigError(Exception):
"""Exception for command configuration errors"""
pass
| class CommandConfigError(Exception):
"""Exception for command configuration errors"""
pass
class RequirementsConfigError(Exception):
"""Exception for command configuration errors"""
pass
| Add a requirements configuration exception | Add a requirements configuration exception
| Python | mit | ravenac95/virtstrap-core,ravenac95/testvirtstrapdocs,ravenac95/virtstrap-core |
9bdd1c9a33bd48cde186a5d4c425fc8745017cd9 | lifx.py | lifx.py | # -*- encoding: utf8 -*-
from __future__ import division, print_function, division
import pylifx
if __name__ == '__main__':
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('bulb_addr')
parser.add_argument('state', choices=('on', 'off'))
args = parser.parse_args()
wit... | # -*- encoding: utf8 -*-
from __future__ import division, print_function, division
import pylifx
def power(bulb, state):
if state == 'on':
bulb.on()
elif state == 'off':
bulb.off()
else:
raise ValueError('Invalid State specified %s' % state)
if __name__ == '__main__':
import... | Add subparsers for power, rgb, hsb and temperature | Add subparsers for power, rgb, hsb and temperature
| Python | bsd-3-clause | MichaelAquilina/lifx-cmd |
6377284c022f26cfd9528b09af3ec61fc91a2c54 | api/tests/__init__.py | api/tests/__init__.py | import json
from django.test import TestCase, Client
# Create your tests here.
from login.models import myuser
from rest_framework.authtoken.models import Token
class APITestCase(TestCase):
test_schema = 'schema1'
test_table = 'population2'
@classmethod
def setUpClass(cls):
super(APITestC... | import json
from django.test import TestCase, Client
# Create your tests here.
from login.models import myuser
from rest_framework.authtoken.models import Token
class APITestCase(TestCase):
test_schema = 'schema1'
test_table = 'population2'
@classmethod
def setUpClass(cls):
super(APITestC... | Add another user for permission testing | Add another user for permission testing
| Python | agpl-3.0 | tom-heimbrodt/oeplatform,tom-heimbrodt/oeplatform,tom-heimbrodt/oeplatform,openego/oeplatform,openego/oeplatform,openego/oeplatform,openego/oeplatform |
833a83a109bc52b034bbfeabc9a9e2d99d8226f9 | app.tmpl/__init__.py | app.tmpl/__init__.py | # Main application file
#
# Copyright (c) 2017, Alexandre Hamelin <alexandre.hamelin gmail.com>
import os
from flask import Flask
from flask_login import LoginManager
app = Flask(__name__)
app.secret_key = 'default-secret-key'
app.config.from_object('plbackend.config.DefaultConfig')
if 'PLBACKEND_CONFIG' in os.envir... | # Main application file
#
# Copyright (c) 2017, Alexandre Hamelin <alexandre.hamelin gmail.com>
import os
from flask import Flask
from flask_login import LoginManager
app = Flask(__name__)
app.secret_key = 'default-secret-key'
app.config.from_object(app.name + '.config.DefaultConfig')
if 'APP_CONFIG' in os.environ:
... | Fix the app config loading process | Fix the app config loading process
| Python | mit | 0xquad/flask-app-template,0xquad/flask-app-template,0xquad/flask-app-template |
90405c60b5d2ce583597382bc72e116cb9a450bd | project/library/models.py | project/library/models.py | from django.db import models
class Author(models.Model):
'''Object for book author'''
first_name = models.CharField(max_length=128)
last_name = models.CharField(max_length=128)
def __unicode__(self):
return self.last_name + ", " + self.first_name
class Book(models.Model):
'''Object for library books'... | from datetime import datetime
from django.db import models
class Author(models.Model):
'''Object for book author'''
first_name = models.CharField(max_length=128)
last_name = models.CharField(max_length=128)
def __unicode__(self):
return self.last_name + ", " + self.first_name
class Book(models.Model):
... | Update reservation object to use current time | Update reservation object to use current time
| Python | mit | DUCSS/ducss-site-old,DUCSS/ducss-site-old,DUCSS/ducss-site-old |
58ed8c24288ee8f470acfa85cc6ae267f0ad2fd8 | pbag/tests/test_serialize.py | pbag/tests/test_serialize.py | from pbag.serialize import dump, load
data = [b'Hello\n', 1, b'world!', None]
def test_core():
with open('_foo.pack', 'wb') as f:
dump(data, f)
with open('_foo.pack', 'rb') as f:
data2 = load(f)
assert data == data2
def test_multiple_dumps():
with open('_foo.pack', 'wb') as f:
... | from tempfile import TemporaryFile
from pbag.serialize import dump, load
data = [b'Hello\n', 1, b'world!', None]
def test_core():
with TemporaryFile(mode='wb+') as f:
dump(data, f)
f.seek(0)
data2 = load(f)
assert data == data2
def test_multiple_dumps():
with TemporaryFile(mod... | Use temporary files for testing. | Use temporary files for testing.
| Python | bsd-3-clause | jakirkham/dask,clarkfitzg/dask,marianotepper/dask,ContinuumIO/dask,esc/dask,pombredanne/dask,wiso/dask,jcrist/dask,mraspaud/dask,hainm/dask,pombredanne/dask,jakirkham/dask,ssanderson/dask,mraspaud/dask,cpcloud/dask,wiso/dask,mrocklin/dask,minrk/dask,ContinuumIO/dask,PhE/dask,PhE/dask,esc/dask,jayhetee/dask,blaze/dask,d... |
d9f3e43a05663706b266d60c1f707133b0c3b6a0 | error_proxy.py | error_proxy.py | #!/usr/bin/env python
import sys
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
class ErrorHTTPRequestHandler(BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(420)
if sys.argv[1:]:
port = sys.argv[1:]
else:
port = 8000
httpd = HTTPServer(("localhost", port), ErrorHTTPR... | #!/usr/bin/env python
import sys
import json
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
class ErrorHTTPRequestHandler(BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(420)
if sys.argv[1:]:
config_file = sys.argv[1:]
else:
config_file = "Proxyfile"
with open(config_... | Configure port via a Proxyfile | Configure port via a Proxyfile
| Python | mit | pozorvlak/error_proxy |
a6ce774d11100208d2a65aa71c3cb147a550a906 | dpath/__init__.py | dpath/__init__.py | import sys
# Python version flags for Python 3 support
PY2 = ( sys.version_info.major == 2 )
PY3 = ( sys.version_info.major == 3 )
| import sys
# Python version flags for Python 3 support
python_major_version = 0
if hasattr(sys.version_info, 'major'):
python_major_version = sys.version_info.major
else:
python_major_version = sys.version_info[0]
PY2 = ( python_major_version == 2 )
PY3 = ( python_major_version == 3 )
| Make this work on python2.6 again | Make this work on python2.6 again | Python | mit | akesterson/dpath-python,pombredanne/dpath-python,benthomasson/dpath-python,lexhung/dpath-python,calebcase/dpath-python |
ae84f8224d7ab01e419ff548cd8be28eb4b15804 | examples/image_test.py | examples/image_test.py | import sys
import os
import pyglet.window
from pyglet.gl import *
from pyglet import clock
from pyglet.ext.scene2d import Image2d
from ctypes import *
if len(sys.argv) != 2:
print 'Usage: %s <PNG/JPEG filename>'%sys.argv[0]
sys.exit()
window = pyglet.window.Window(width=400, height=400)
image = Image2d.loa... | import sys
import os
import ctypes
import pyglet.window
from pyglet.gl import *
from pyglet import clock
from pyglet import image
if len(sys.argv) != 2:
print 'Usage: %s <PNG/JPEG filename>'%sys.argv[0]
sys.exit()
window = pyglet.window.Window(width=400, height=400)
image = image.load(sys.argv[1])
imx = imy ... | Use the core, make example more useful. | Use the core, make example more useful.
| Python | bsd-3-clause | gdkar/pyglet,kmonsoor/pyglet,xshotD/pyglet,google-code-export/pyglet,xshotD/pyglet,kmonsoor/pyglet,shaileshgoogler/pyglet,mpasternak/pyglet-fix-issue-518-522,kmonsoor/pyglet,google-code-export/pyglet,Austin503/pyglet,arifgursel/pyglet,Austin503/pyglet,arifgursel/pyglet,cledio66/pyglet,shaileshgoogler/pyglet,odyaka341/p... |
fb4bac2a228a196359317f338c3f1e6643c3837d | nova/tests/unit/compute/fake_resource_tracker.py | nova/tests/unit/compute/fake_resource_tracker.py | # Copyright (c) 2012 OpenStack Foundation
# 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 ... | # Copyright (c) 2012 OpenStack Foundation
# 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 ... | Remove an unused method in FakeResourceTracker | Remove an unused method in FakeResourceTracker
Nothing calls _create and there is no _create in the super class for
this to be overriding.
Change-Id: Ic41f2d249b9aaffb2caaa18dd492924a4ceb3653
| Python | apache-2.0 | gooddata/openstack-nova,Juniper/nova,mikalstill/nova,cernops/nova,cernops/nova,vmturbo/nova,NeCTAR-RC/nova,klmitch/nova,jianghuaw/nova,mikalstill/nova,klmitch/nova,Juniper/nova,cloudbase/nova,cernops/nova,openstack/nova,rahulunair/nova,gooddata/openstack-nova,jianghuaw/nova,klmitch/nova,NeCTAR-RC/nova,mikalstill/nova,h... |
2e406c8cca9e55c9b8e2dcbf33005aa580ef74ea | tests/state/test_in_memory_key_value_store.py | tests/state/test_in_memory_key_value_store.py | from winton_kafka_streams.state.in_memory_key_value_store import InMemoryKeyValueStore
def test_inMemoryKeyValueStore():
store = InMemoryKeyValueStore('teststore')
store['a'] = 1
assert store['a'] == 1
store['a'] = 2
assert store['a'] == 2
| import pytest
from winton_kafka_streams.state.in_memory_key_value_store import InMemoryKeyValueStore
def test_inMemoryKeyValueStore():
store = InMemoryKeyValueStore('teststore')
store['a'] = 1
assert store['a'] == 1
store['a'] = 2
assert store['a'] == 2
del store['a']
assert store.get('... | Test behaviour of key deletion | Test behaviour of key deletion
| Python | apache-2.0 | wintoncode/winton-kafka-streams |
237faf53129e575faafad6cfeecf96c707d50c4b | examples/common.py | examples/common.py |
def print_devices(b):
for device in sorted(b.devices, key=lambda d: len(d.ancestors)):
print(device) # this is a blivet.devices.StorageDevice instance
print()
|
def print_devices(b):
print(b.devicetree)
| Use DeviceTree.__str__ when printing devices in examples. | Use DeviceTree.__str__ when printing devices in examples.
| Python | lgpl-2.1 | AdamWill/blivet,vojtechtrefny/blivet,rhinstaller/blivet,vpodzime/blivet,vojtechtrefny/blivet,AdamWill/blivet,rvykydal/blivet,rvykydal/blivet,jkonecny12/blivet,rhinstaller/blivet,jkonecny12/blivet,vpodzime/blivet |
a51bc09ec5c7c03ce0d76cca443520036d45fa63 | apps/projects/urls.py | apps/projects/urls.py | from django.conf.urls.defaults import patterns, url, include
from surlex.dj import surl
from .api import ProjectResource, ProjectDetailResource
from .views import ProjectListView, ProjectDetailView, ProjectMapView
project_resource = ProjectResource()
projectdetail_resource = ProjectDetailResource()
urlpatterns = p... | from django.conf.urls.defaults import patterns, url, include
from surlex.dj import surl
from .api import ProjectResource, ProjectDetailResource, ProjectSearchFormResource
from .views import ProjectListView, ProjectDetailView, ProjectMapView
project_resource = ProjectResource()
projectdetail_resource = ProjectDetailR... | Enable project search form API. | Enable project search form API.
| Python | bsd-3-clause | onepercentclub/onepercentclub-site,onepercentclub/onepercentclub-site,onepercentclub/onepercentclub-site,onepercentclub/onepercentclub-site,onepercentclub/onepercentclub-site |
6ba28684960b14ecb29b26d63ae4a593337e7fa4 | examples/wordy.py | examples/wordy.py | """
Nodes can contain words
=======================
We here at **Daft** headquarters tend to put symbols (variable
names) in our graph nodes. But you don't have to if you don't
want to.
"""
from matplotlib import rc
rc("font", family="serif", size=12)
rc("text", usetex=True)
import daft
pgm = daft.PGM()
pgm.add_n... | """
Nodes can contain words
=======================
We here at **Daft** headquarters tend to put symbols (variable
names) in our graph nodes. But you don't have to if you don't
want to.
"""
from matplotlib import rc
rc("font", family="serif", size=12)
rc("text", usetex=True)
import daft
pgm = daft.PGM()
pgm.add_n... | Add edge label and rotation. | Add edge label and rotation.
| Python | mit | dfm/daft |
49c83e0ef5ec7390a78e95dbc035b7d2808ec13e | feedback/tests.py | feedback/tests.py | # -*- coding: utf-8 -*-
from django.test import TestCase, client
from .models import Feedback
client = client.Client()
class FeedbackTest(TestCase):
def test_add_feedback(self):
before_add = Feedback.objects.count()
response = client.post('/feedback/add/', {
'name': 'Пандо Пандев',
... | # -*- coding: utf-8 -*-
from django.test import TestCase, client
from .models import Feedback
client = client.Client()
class FeedbackTest(TestCase):
def test_add_feedback(self):
pass
# before_add = Feedback.objects.count()
# response = client.post('/feedback/add/', {
# 'name... | Remove test for adding feedback | Remove test for adding feedback
| Python | mit | Hackfmi/Diaphanum,Hackfmi/Diaphanum |
fc50467212347502792a54397ae6f5477136a32f | pombola/south_africa/urls.py | pombola/south_africa/urls.py | from django.conf.urls import patterns, include, url
from pombola.south_africa.views import LatLonDetailView, SAPlaceDetailSub, \
SAOrganisationDetailView, SAPersonDetail, SANewsletterPage
from pombola.core.urls import organisation_patterns, person_patterns
# Override the organisation url so we can vary it dependi... | from django.conf.urls import patterns, include, url
from pombola.south_africa.views import LatLonDetailView, SAPlaceDetailSub, \
SAOrganisationDetailView, SAPersonDetail, SANewsletterPage
from pombola.core.urls import organisation_patterns, person_patterns
# Override the organisation url so we can vary it dependi... | Add note about needing to create the infopage | Add note about needing to create the infopage
| Python | agpl-3.0 | hzj123/56th,ken-muturi/pombola,hzj123/56th,geoffkilpin/pombola,patricmutwiri/pombola,patricmutwiri/pombola,hzj123/56th,ken-muturi/pombola,patricmutwiri/pombola,ken-muturi/pombola,ken-muturi/pombola,patricmutwiri/pombola,patricmutwiri/pombola,mysociety/pombola,hzj123/56th,geoffkilpin/pombola,geoffkilpin/pombola,mysociet... |
775e0b819e3eac2f84d41900de7bdc2058156389 | backend/blog/types.py | backend/blog/types.py | from typing import Optional
import strawberry
from api.scalars import DateTime
from users.types import UserType
@strawberry.type
class Post:
id: strawberry.ID
author: UserType
title: str
slug: str
excerpt: Optional[str]
content: Optional[str]
published: DateTime
image: Optional[str]
| from typing import Optional
import strawberry
from api.scalars import DateTime
from users.types import UserType
@strawberry.type
class Post:
id: strawberry.ID
author: UserType
title: str
slug: str
excerpt: Optional[str]
content: Optional[str]
published: DateTime
@strawberry.field
... | Return absolute url for blog image | Return absolute url for blog image
| Python | mit | patrick91/pycon,patrick91/pycon |
7387d77a094b7368cf80a1e8c1db41356d92fc38 | calaccess_website/templatetags/calaccess_website_tags.py | calaccess_website/templatetags/calaccess_website_tags.py | import os
from django import template
from django.conf import settings
from django.template.defaultfilters import stringfilter
register = template.Library()
@register.simple_tag
def archive_url(file_path, is_latest=False):
"""
Accepts the relative path to a CAL-ACCESS file in our achive.
Returns a fully-... | import os
from django import template
from django.conf import settings
from django.template.defaultfilters import stringfilter
register = template.Library()
@register.simple_tag
def archive_url(file_path, is_latest=False):
"""
Accepts the relative path to a CAL-ACCESS file in our achive.
Returns a fully-... | Substitute in our download bucket in that template tag now that the two things are separated | Substitute in our download bucket in that template tag now that the two things are separated
| Python | mit | california-civic-data-coalition/django-calaccess-downloads-website,california-civic-data-coalition/django-calaccess-downloads-website,california-civic-data-coalition/django-calaccess-downloads-website |
2b4b71246646db8e28b999d2ff249c3a36aa0c33 | uitools/qt.py | uitools/qt.py | """Convenience to import Qt if it is availible, otherwise provide stubs.
Normally I wouldn't bother with something like this, but due to the
testing contexts that we often run we may import stuff from uitools that
does not have Qt avilaible.
"""
__all__ = ['Qt', 'QtCore', 'QtGui']
try:
from PyQt4 import QtCore,... | """Wrapping the differences between PyQt4 and PySide."""
import sys
__all__ = ['Qt', 'QtCore', 'QtGui']
try:
import PySide
from PySide import QtCore, QtGui
sys.modules.setdefault('PyQt4', PySide)
except ImportError:
try:
import PyQt4
from PyQt4 import QtCore, QtGui
sys.modules... | Check for PySide first, and proxy PyQt4 to it | Check for PySide first, and proxy PyQt4 to it
This allows our other tools, which are rather dumb,
to import the wrong one and generally continue to
work. | Python | bsd-3-clause | westernx/uitools |
a1746483da4e84c004e55ea4d33693a764ac5807 | githubsetupircnotifications.py | githubsetupircnotifications.py | """
github-setup-irc-notifications - Configure all repositories in an organization
with irc notifications
"""
import github3
| """
github-setup-irc-notifications - Configure all repositories in an organization
with irc notifications
"""
import argparse
import github3
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--username'),
parser.add_argument('--password'),
args = parser.parse_args()
| Add username and password args | Add username and password args
| Python | mit | kragniz/github-setup-irc-notifications |
582c445e6ceb781cfb913a4d6a200d8887f66e16 | filters/filters.py | filters/filters.py | import re
import os
def get_emoji_content(filename):
full_filename = os.path.join(os.path.dirname(__file__), 'emojis', filename)
with open(full_filename, 'r') as fp:
return fp.read()
def fix_emoji(value):
"""
Replace some text emojis with pictures
"""
emojis = {
'(+)': get_em... | import re
import os
def get_emoji_content(filename):
full_filename = os.path.join(os.path.dirname(__file__), 'emojis', filename)
with open(full_filename, 'r') as fp:
return fp.read()
def fix_emoji(value):
"""
Replace some text emojis with pictures
"""
emojis = {
'(+)': get_em... | Fix small issue in the cleanup filter. It now supports {/code} closing tag (was only {code}) | Fix small issue in the cleanup filter. It now supports {/code} closing tag (was only {code})
| Python | mit | vv-p/jira-reports,vv-p/jira-reports |
764f7d422da005fd84d9f24c36709442c1b2d51e | blanc_events/admin.py | blanc_events/admin.py | # -*- coding: utf-8 -*-
from django.contrib import admin
from blanc_pages.admin import BlancPageAdminMixin
from .models import Category, Event
@admin.register(Category)
class CategoryAdmin(admin.ModelAdmin):
search_fields = ('title',)
prepopulated_fields = {
'slug': ('title',)
}
@admin.regist... | # -*- coding: utf-8 -*-
from django.contrib import admin
from blanc_pages.admin import BlancPageAdminMixin
from .models import Category, Event
@admin.register(Category)
class CategoryAdmin(admin.ModelAdmin):
search_fields = ('title',)
prepopulated_fields = {
'slug': ('title',)
}
@admin.regist... | Use category, not category title for list_filter | Use category, not category title for list_filter
| Python | bsd-3-clause | blancltd/django-glitter-events,blancltd/django-glitter-events |
e710c6be61f94ff2b82a84339c95a77611b291e8 | fmn/api/distgit.py | fmn/api/distgit.py | import logging
from fastapi import Depends
from httpx import AsyncClient
from ..core.config import Settings, get_settings
log = logging.getLogger(__name__)
class DistGitClient:
def __init__(self, settings):
self.client = AsyncClient(base_url=settings.services.distgit_url, timeout=None)
async def g... | import logging
from fastapi import Depends
from httpx import AsyncClient
from ..core.config import Settings, get_settings
log = logging.getLogger(__name__)
class DistGitClient:
def __init__(self, settings):
self.client = AsyncClient(base_url=settings.services.distgit_url, timeout=None)
async def g... | Fix retrieval of artifact names | Fix retrieval of artifact names
Signed-off-by: Aurélien Bompard <bceb368e7f2cb351af47298f32034f0587bbe4a6@bompard.org>
| Python | lgpl-2.1 | fedora-infra/fmn,fedora-infra/fmn,fedora-infra/fmn,fedora-infra/fmn,fedora-infra/fmn |
221ff606f1c834141dd19d9101ab750733437b95 | make.py | make.py | #!/usr/bin/env python
"""
make.py
A drop-in or mostly drop-in replacement for GNU make.
"""
import sys, os
import pymake.command, pymake.process
pymake.command.main(sys.argv[1:], os.environ, os.getcwd(), cb=sys.exit)
pymake.process.ParallelContext.spin()
assert False, "Not reached"
| #!/usr/bin/env python
"""
make.py
A drop-in or mostly drop-in replacement for GNU make.
"""
import sys, os
import pymake.command, pymake.process
import gc
gc.disable()
pymake.command.main(sys.argv[1:], os.environ, os.getcwd(), cb=sys.exit)
pymake.process.ParallelContext.spin()
assert False, "Not reached"
| Disable GC, since we no longer create cycles anywhere. | Disable GC, since we no longer create cycles anywhere.
| Python | mit | indygreg/pymake,mozilla/pymake,mozilla/pymake,mozilla/pymake |
6466e0fb7c5f7da0048a9ed9e1dd8023ddc5f59a | members/views.py | members/views.py | from django.shortcuts import render
from django.http import HttpResponse
from hackfmi.utils import json_view
from .models import User
def homepage(request):
return render(request, "index.html", {})
@json_view
def search(request, name):
members = User.objects.filter(first_name__icontains=name) or \
... | # -*- coding: utf-8 -*-
from django.shortcuts import render
from django.http import HttpResponse
from hackfmi.utils import json_view
from .models import User
def homepage(request):
return render(request, "index.html", {})
@json_view
def search(request, name):
members = User.objects.filter(first_name__icont... | Add faculty_number to search's json | Add faculty_number to search's json
| Python | mit | Hackfmi/Diaphanum,Hackfmi/Diaphanum |
957513329838474ba8f54c4571ea87c92600caf1 | pyli.py | pyli.py | import parser
import token
import symbol
import sys
from pprint import pprint
tree = parser.st2tuple(parser.suite(sys.argv[1]))
def convert_readable(tree):
return tuple(((token.tok_name[i]
if token.tok_name.get(i) else
symbol.sym_name[i])
if isinstance(i, i... | import parser
import token
import symbol
import sys
from pprint import pprint
tree = parser.st2tuple(parser.suite(sys.argv[1]))
def convert_readable(tree):
return tuple(((token.tok_name[i]
if token.tok_name.get(i) else
symbol.sym_name[i])
if isinstance(i, i... | Write a free/bound token finder | Write a free/bound token finder
| Python | mit | thenoviceoof/pyli |
5841f314636ee534342aa3e4530cc3ee933a052b | src/ezweb/compressor_filters.py | src/ezweb/compressor_filters.py | # -*- coding: utf-8 -*-
from compressor.filters import FilterBase
class JSUseStrictFilter(FilterBase):
def output(self, **kwargs):
return self.remove_use_strict(self.content)
def remove_use_strict(js):
js = js.replace("'use strict';", '')
js = js.replace('"use strict";', '')
... | # -*- coding: utf-8 -*-
from compressor.filters import FilterBase
class JSUseStrictFilter(FilterBase):
def output(self, **kwargs):
return self.remove_use_strict(self.content)
def remove_use_strict(self, js):
# Replacing by a ';' is safer than replacing by ''
js = js.replace("'use st... | Fix a bug while replacing "use strict" JS pragmas | Fix a bug while replacing "use strict" JS pragmas
| Python | agpl-3.0 | jpajuelo/wirecloud,rockneurotiko/wirecloud,jpajuelo/wirecloud,jpajuelo/wirecloud,rockneurotiko/wirecloud,jpajuelo/wirecloud,rockneurotiko/wirecloud,rockneurotiko/wirecloud |
ff67e435ea31680698166e4ae3296ff4211e2b51 | kremlin/__init__.py | kremlin/__init__.py | """
# # #### ##### # # ##### # # # #
# # # # # ## ## # # # ## # #
### #### #### # # # # # # # # #####
# # # # # # # # ## # # #
# # # ##### # # # # # # # #
Kremlin Mag... | """
# # #### ##### # # ##### # # # #
# # # # # ## ## # # # ## # #
### #### #### # # # # # # # # #####
# # # # # # # # ## # # #
# # # ##### # # # # # # # #
Kremlin Mag... | Fix import for new Flask-SQlAlchemy (no longer in flaskext) | Fix import for new Flask-SQlAlchemy (no longer in flaskext)
| Python | bsd-2-clause | glasnost/kremlin,glasnost/kremlin,glasnost/kremlin |
3d51452d466fc733ee782d8e82463588bb9d2418 | handler/base_handler.py | handler/base_handler.py | import os
from serf_master import SerfHandler
from utils import with_payload, truncated_stdout
class BaseHandler(SerfHandler):
def __init__(self, *args, **kwargs):
super(BaseHandler, self).__init__(*args, **kwargs)
self.setup()
def setup(self):
pass
@truncated_stdout
@with_... | import os
import socket
from serf_master import SerfHandler
from utils import with_payload, truncated_stdout
class BaseHandler(SerfHandler):
def __init__(self, *args, **kwargs):
super(BaseHandler, self).__init__(*args, **kwargs)
self.setup()
def setup(self):
pass
@truncated_std... | Improve default for ip in 'where' event | Improve default for ip in 'where' event
| Python | mit | waltermoreira/serfnode,waltermoreira/serfnode,waltermoreira/serfnode |
85b3a68ef93aa18dd176d8804f7f5089d7cf7be9 | helpers/file_helpers.py | helpers/file_helpers.py | import os
def expand_directory(directory_path):
ret = []
for file_path in os.listdir(directory_path):
if os.path.isfile(os.path.join(directory_path, file_path)):
# Append instead of extend or += because those separate the string into its individual characters
# This has to do w... | import os
def expand_directory(directory_path):
"""Recursively create a list of all the files in a directory and its subdirectories
"""
ret = []
for file_path in os.listdir(directory_path):
if os.path.isfile(os.path.join(directory_path, file_path)):
# Append instead of extend or +=... | Add more documentation. Fix the expand_directory function | Add more documentation. Fix the expand_directory function
| Python | mit | PaulOlteanu/PVCS |
1f4bd95d758db4e2388b180f637963e26a033790 | InvenTree/part/migrations/0034_auto_20200404_1238.py | InvenTree/part/migrations/0034_auto_20200404_1238.py | # Generated by Django 2.2.10 on 2020-04-04 12:38
from django.db import migrations
from django.db.utils import OperationalError, ProgrammingError
from part.models import Part
from stdimage.utils import render_variations
def create_thumbnails(apps, schema_editor):
"""
Create thumbnails for all existing Part i... | # Generated by Django 2.2.10 on 2020-04-04 12:38
from django.db import migrations
def create_thumbnails(apps, schema_editor):
"""
Create thumbnails for all existing Part images.
Note: This functionality is now performed in apps.py,
as running the thumbnail script here caused too many database level... | Remove the problematic migration entirely | Remove the problematic migration entirely
- The thumbnail check code is run every time the server is started anyway!
| Python | mit | inventree/InvenTree,SchrodingersGat/InvenTree,SchrodingersGat/InvenTree,inventree/InvenTree,inventree/InvenTree,SchrodingersGat/InvenTree,SchrodingersGat/InvenTree,inventree/InvenTree |
0e7487948fe875d5d077f230b804983b28ca72cb | utils.py | utils.py | from score import score_funcs
from db import conn
curr = conn.cursor()
def process_diff(diffiduser):
try:
diffid, user = diffiduser
except:
return
diff = get_diff_for_diffid(diffid)
zum = 0
for f in score_funcs:
zum += f(diff)
print zum, diffid
def get_diff_for_diffid... | from score import score_funcs
from db import conn
curr = conn.cursor()
def process_diff(diffiduser):
try:
diffid, user = diffiduser
except:
return
diff = get_diff_for_diffid(diffid)
zum = 0
for f in score_funcs:
zum += f(diff)
print zum, diffid
def get_diff_for_diffid... | Add util function for getting diff content | Add util function for getting diff content
| Python | mit | tjcsl/wedge,tjcsl/wedge |
cd4d67ae0796e45ef699e1bab60ee5aeeac91dbb | native_qwebview_example/run.py | native_qwebview_example/run.py | import sys
from browser import BrowserDialog
from PyQt4 import QtGui
from PyQt4.QtCore import QUrl
from PyQt4.QtWebKit import QWebView
class MyBrowser(QtGui.QDialog):
def __init__(self, parent=None):
QtGui.QWidget.__init__(self, parent)
QWebView.__init__(self)
self.ui = BrowserDialog()
... | # Basic example for testing purposes, taken from
# https://pythonspot.com/creating-a-webbrowser-with-python-and-pyqt-tutorial/
import sys
from browser import BrowserDialog
from PyQt4 import QtGui
from PyQt4.QtCore import QUrl
from PyQt4.QtWebKit import QWebView
class MyBrowser(QtGui.QDialog):
def __init__(self, ... | Add a comment about where the basic example was taken [skip CI] | Add a comment about where the basic example was taken
[skip CI]
| Python | agpl-3.0 | gem/oq-svir-qgis,gem/oq-svir-qgis,gem/oq-svir-qgis,gem/oq-svir-qgis |
5a2ff00b3574c8fb187fd87fcda3f79f7dd43b3c | tests/data_test.py | tests/data_test.py | from pork.data import Data
from mock import Mock, patch, mock_open
from StringIO import StringIO
patch.TEST_PREFIX = 'it'
class TestData:
def it_loads_json_data_from_file(self):
with patch("__builtin__.open", mock_open(read_data='{"foo":"bar"}'),
create=True) as m:
data = Data()
... | from pork.data import Data
from mock import Mock, patch, mock_open
from StringIO import StringIO
patch.TEST_PREFIX = 'it'
@patch.object(Data, '_data_path', '/tmp/doesnt_exist')
class TestData:
def it_loads_json_data_from_file(self):
with patch("__builtin__.open", mock_open(read_data='{"foo":"bar"}'),
... | Patch Data._data_path so it doesn't find the real data file. | Patch Data._data_path so it doesn't find the real data file.
| Python | mit | jimmycuadra/pork,jimmycuadra/pork |
c4e1f1c147783a4a735dd943d5d7491302de300e | csunplugged/config/urls.py | csunplugged/config/urls.py | """csunplugged URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.10/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Clas... | """csunplugged URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.10/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Clas... | Remove unused static URL pathing | Remove unused static URL pathing
| Python | mit | uccser/cs-unplugged,uccser/cs-unplugged,uccser/cs-unplugged,uccser/cs-unplugged |
96c20164b3221321f71e12fd7054766a92722e08 | test.py | test.py | from coils import user_input
from sqlalchemy import create_engine
username = user_input('Username', default='root')
password = user_input('Password', password=True)
dbname = user_input('Database name')
engine = create_engine(
'mysql://{:}:{:}@localhost'.format(username, password),
isolation_level='READ UNCOMM... | """Add a timestamp."""
from coils import user_input, Config
from sqlalchemy import create_engine, Column, DateTime, Integer
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
config = Config('wabbit.cfg')
# Connect to database engine and start a session.
dbname = user_inp... | Add timestamp upon each run. | Add timestamp upon each run.
| Python | mit | vmlaker/wabbit,vmlaker/wabbit,vmlaker/wabbit,vmlaker/wabbit |
7cd716635eb0db5f36e8267c312fc462aa16e210 | prerequisites.py | prerequisites.py | #!/usr/bin/env python
import sys
# Check that we are in an activated virtual environment
try:
import os
virtual_env = os.environ['VIRTUAL_ENV']
except KeyError:
print("It doesn't look like you are in an activated virtual environment.")
print("Did you make one?")
print("Did you activate it?")
... | #!/usr/bin/env python
import sys
# Check that we are in an activated virtual environment
try:
import os
virtual_env = os.environ['VIRTUAL_ENV']
except KeyError:
print("It doesn't look like you are in an activated virtual environment.")
print("Did you make one?")
print("Did you activate it?")
... | Use django.get_version in prerequisite checker | Use django.get_version in prerequisite checker
| Python | mit | mpirnat/django-tutorial-v2 |
d53152aedff7777be771124a91ba325f75398739 | test.py | test.py | #! /usr/bin/env python
from theora import Ogg
from numpy import concatenate, zeros_like
from scipy.misc import toimage
f = open("video.ogv")
o = Ogg(f)
Y, Cb, Cr = o.test()
Cb2 = zeros_like(Y)
for i in range(Cb2.shape[0]):
for j in range(Cb2.shape[1]):
Cb2[i, j] = Cb[i/2, j/2]
Cr2 = zeros_like(Y)
for i in... | #! /usr/bin/env python
from theora import Ogg
from numpy import concatenate, zeros_like
from scipy.misc import toimage
f = open("video.ogv")
o = Ogg(f)
Y, Cb, Cr = o.test()
Cb2 = zeros_like(Y)
for i in range(Cb2.shape[0]):
for j in range(Cb2.shape[1]):
Cb2[i, j] = Cb[i/2, j/2]
Cr2 = zeros_like(Y)
for i in... | Save the image to png | Save the image to png
| Python | bsd-3-clause | certik/python-theora,certik/python-theora |
c244f074615765ba26874c2dba820a95984686bb | os_tasklib/neutron/__init__.py | os_tasklib/neutron/__init__.py | # -*- coding: utf-8 -*-
# Copyright 2015 Hewlett-Packard Development Company, L.P.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unle... | # -*- coding: utf-8 -*-
# Copyright 2015 Hewlett-Packard Development Company, L.P.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unle... | Fix imports on Python 3 | Fix imports on Python 3
On Python 3, imports are absolute by default.
Because of these invalid imports, tests don't run anymore on
Python 3, since tests cannot be loaded.
Change-Id: Ib11a09432939df959568de400f60dfe981d0a403
| Python | apache-2.0 | stackforge/cue,stackforge/cue,openstack/cue,stackforge/cue,openstack/cue,openstack/cue |
664c0924ca3a5ba58d0205c2fd733e6ad2e4f5dd | spanky/commands/cmd_users.py | spanky/commands/cmd_users.py | import click
from spanky.cli import pass_context
@click.command('users', short_help='creates users base on /etc/spanky/users')
@pass_context
def cli(ctx):
config = ctx.config.load('users.yml')
| import click
from spanky.cli import pass_context
from spanky.lib.users import UserInit
@click.command('users', short_help='creates users base on /etc/spanky/users')
@pass_context
def cli(ctx):
config = ctx.config.load('users.yml')()
user_init = UserInit(config)
user_init.build()
| Use the config when creating users. | Use the config when creating users.
| Python | bsd-3-clause | pglbutt/spanky,pglbutt/spanky,pglbutt/spanky |
253ea73b37b9295ef0e31c2f1b1bdc7922cb6da5 | spitfire/runtime/repeater.py | spitfire/runtime/repeater.py | class RepeatTracker(object):
def __init__(self):
self.repeater_map = {}
def __setitem__(self, key, value):
try:
self.repeater_map[key].index = value
except KeyError, e:
self.repeater_map[key] = Repeater(value)
def __getitem__(self, key):
return self.repeater_map[key]
class Repeater(... | class RepeatTracker(object):
def __init__(self):
self.repeater_map = {}
def __setitem__(self, key, value):
try:
self.repeater_map[key].index = value
except KeyError, e:
self.repeater_map[key] = Repeater(value)
def __getitem__(self, key):
return self.repeater_map[key]
class Repeater(... | Revert last change (breaks XSPT) | Revert last change (breaks XSPT)
| Python | bsd-3-clause | nicksay/spitfire,spt/spitfire,spt/spitfire,spt/spitfire,nicksay/spitfire,nicksay/spitfire,youtube/spitfire,spt/spitfire,youtube/spitfire,youtube/spitfire,nicksay/spitfire,youtube/spitfire |
abce02dc1a30b869300eee36b29d5e61320d64c5 | test.py | test.py | #!/usr/bin/env python
import os
import subprocess
import time
import glob
import unittest
class ZxSpecTestCase(unittest.TestCase):
def setUp(self):
clean()
def tearDown(self):
clean()
def test_zx_spec_header_displayed(self):
ZX_SPEC_OUTPUT_FILE = "printout.txt"
proc = sub... | #!/usr/bin/env python
import os
import subprocess
import time
import glob
import unittest
class ZxSpecTestCase(unittest.TestCase):
@classmethod
def setUpClass(self):
clean()
self.output = run_zx_spec()
def test_zx_spec_header_displayed(self):
self.assertRegexpMatches(self.output, ... | Add timeout for printout production | Add timeout for printout production
| Python | mit | rhargreaves/zx-spec |
7e98ecd888dba1f5e19b4e1a2f3f9aebd7756c5c | panoptes_client/user.py | panoptes_client/user.py | from panoptes_client.panoptes import PanoptesObject, LinkResolver
class User(PanoptesObject):
_api_slug = 'users'
_link_slug = 'users'
_edit_attributes = ()
LinkResolver.register(User)
LinkResolver.register(User, 'owner')
| from panoptes_client.panoptes import PanoptesObject, LinkResolver
class User(PanoptesObject):
_api_slug = 'users'
_link_slug = 'users'
_edit_attributes = ()
def avatar(self):
return User.http_get('{}/avatar'.format(self.id))[0]
LinkResolver.register(User)
LinkResolver.register(User, 'owner')... | Add method to get User's avatar | Add method to get User's avatar
| Python | apache-2.0 | zooniverse/panoptes-python-client |
bdedbef5a8326705523cd3a7113cadb15d4a59ec | ckanext/wirecloudview/tests/test_plugin.py | ckanext/wirecloudview/tests/test_plugin.py | """Tests for plugin.py."""
import ckanext.wirecloudview.plugin as plugin
from mock import MagicMock, patch
class DataRequestPluginTest(unittest.TestCase):
def test_process_dashboardid_should_strip(self):
self.assertEqual(plugin.process_dashboardid(self, " owner/name ", context), "onwer/name")
def... | # -*- coding: utf-8 -*-
# Copyright (c) 2017 Future Internet Consulting and Development Solutions S.L.
# This file is part of CKAN WireCloud View Extension.
# CKAN WireCloud View Extension is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as publish... | Fix unittest import and add copyright headers | Fix unittest import and add copyright headers
| Python | agpl-3.0 | conwetlab/ckanext-wirecloud_view,conwetlab/ckanext-wirecloud_view,conwetlab/ckanext-wirecloud_view,conwetlab/ckanext-wirecloud_view |
982557f5ad850fb4126bea4adb65aef16291fbd6 | core/forms.py | core/forms.py | from django import forms
from django.utils.translation import ugettext_lazy as _
from .models import Contact
class ContactForm(forms.ModelForm):
class Meta:
exclude = ("created_on",)
model = Contact
class DonateForm(forms.Form):
name = forms.CharField(
max_length=100,
widget... | from django import forms
from django.utils.translation import ugettext_lazy as _
from .models import Contact
class ContactForm(forms.ModelForm):
class Meta:
exclude = ("created_on",)
model = Contact
class DonateForm(forms.Form):
name = forms.CharField(
max_length=100,
widget... | Change to the label name for resident status. | Change to the label name for resident status.
| Python | bsd-3-clause | PARINetwork/pari,PARINetwork/pari,PARINetwork/pari,PARINetwork/pari |
192ba8b2bfa138662cd25f3502fd376187ca3e73 | pagarme/__init__.py | pagarme/__init__.py | # encoding: utf-8
from .pagarme import Pagarme
from .exceptions import *
| # -*- coding: utf-8 -*-
__version__ = '2.0.0-dev'
__description__ = 'Pagar.me Python library'
__long_description__ = ''
from .pagarme import Pagarme
from .exceptions import *
| Set global stats for pagarme-python | Set global stats for pagarme-python
| Python | mit | pbassut/pagarme-python,mbodock/pagarme-python,pagarme/pagarme-python,aroncds/pagarme-python,reginaldojunior/pagarme-python |
a8053bb36cf9cfe292274b79c435ab6eb6fc6633 | urls.py | urls.py | from django.conf.urls.defaults import patterns, include, url
# Uncomment the next two lines to enable the admin:
# from django.contrib import admin
# admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'gnome_developer_network.views.home', name='home'),
# url(r'^gnome_developer_networ... | # vim: tabstop=4 noexpandtab shiftwidth=4 softtabstop=4
from django.conf.urls.defaults import patterns, include, url
# Uncomment the next two lines to enable the admin:
# from django.contrib import admin
# admin.autodiscover()
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'gnome_developer_network.views.... | Fix url include for api app | Fix url include for api app
| Python | agpl-3.0 | aruiz/GDN |
4ec22f8a0fdd549967e3a30096867b87bc458dde | tensorflow_cloud/python/tests/integration/call_run_on_script_with_keras_ctl_test.py | tensorflow_cloud/python/tests/integration/call_run_on_script_with_keras_ctl_test.py | # Copyright 2020 Google LLC. 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 law or a... | # Copyright 2020 Google LLC. 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 law or a... | Add test harness to call_run_on_script_with_keras | Add test harness to call_run_on_script_with_keras
| Python | apache-2.0 | tensorflow/cloud,tensorflow/cloud |
ec0bcd5981cb9349b3cdaa570f843f49650bedd1 | profile_collection/startup/99-bluesky.py | profile_collection/startup/99-bluesky.py |
def detselect(detector_object, suffix="_stats_total1"):
"""Switch the active detector and set some internal state"""
gs.DETS =[detector_object]
gs.PLOT_Y = detector_object.name + suffix
gs.TABLE_COLS = [gs.PLOT_Y]
def chx_plot_motor(scan):
fig = None
if gs.PLOTMODE == 1:
fig = plt.gcf... |
def detselect(detector_object, suffix="_stats_total1"):
"""Switch the active detector and set some internal state"""
gs.DETS =[detector_object]
gs.PLOT_Y = detector_object.name + suffix
gs.TABLE_COLS = [gs.PLOT_Y]
def chx_plot_motor(scan):
fig = None
if gs.PLOTMODE == 1:
fig = plt.gcf... | Customize programmatic Olog entries from bluesky | ENH: Customize programmatic Olog entries from bluesky
| Python | bsd-2-clause | NSLS-II-CHX/ipython_ophyd,NSLS-II-CHX/ipython_ophyd |
2abe71aaf9357bed719dc5e1118ee4fe49c4101e | jjvm.py | jjvm.py | #!/usr/bin/python
import argparse
import struct
import sys
###############
### CLASSES ###
###############
class MyParser(argparse.ArgumentParser):
def error(self, message):
sys.stderr.write('error: %s\n' % message)
self.print_help()
sys.exit(2)
###################
### SUBROUTINES ###
###... | #!/usr/bin/python
import argparse
import os
import struct
import sys
###############
### CLASSES ###
###############
class MyParser(argparse.ArgumentParser):
def error(self, message):
sys.stderr.write('error: %s\n' % message)
self.print_help()
sys.exit(2)
###################
### SUBROUTIN... | Halt on unrecognized constant pool tag | Halt on unrecognized constant pool tag
| Python | apache-2.0 | justinccdev/jjvm |
a7e0d9633f23e25841298d8406dafdfdb664857a | opps/articles/forms.py | opps/articles/forms.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from django import forms
from .models import Post, Album, Link
from opps.core.widgets import OppsEditor
class PostAdminForm(forms.ModelForm):
class Meta:
model = Post
widgets = {'content': OppsEditor()}
class AlbumAdminForm(forms.ModelForm):
cl... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from django import forms
from .models import Post, Album, Link
from opps.core.widgets import OppsEditor
class PostAdminForm(forms.ModelForm):
multiupload_link = '/fileupload/image/'
class Meta:
model = Post
widgets = {'content': OppsEditor()}
c... | Add multiupload_link in post/album form | Add multiupload_link in post/album form
| Python | mit | YACOWS/opps,YACOWS/opps,williamroot/opps,williamroot/opps,YACOWS/opps,YACOWS/opps,opps/opps,opps/opps,jeanmask/opps,jeanmask/opps,williamroot/opps,jeanmask/opps,williamroot/opps,opps/opps,jeanmask/opps,opps/opps |
c74fc42de3f052ac83342ed33afb2865080c8d67 | threema/gateway/__init__.py | threema/gateway/__init__.py | """
This API can be used to send text messages to any Threema user, and to
receive incoming messages and delivery receipts.
There are two main modes of operation:
* Basic mode (server-based encryption)
- The server handles all encryption for you.
- The server needs to know the private key associated with your... | """
This API can be used to send text messages to any Threema user, and to
receive incoming messages and delivery receipts.
There are two main modes of operation:
* Basic mode (server-based encryption)
- The server handles all encryption for you.
- The server needs to know the private key associated with your... | Remove unneeded imports leading to failures | Remove unneeded imports leading to failures
| Python | mit | threema-ch/threema-msgapi-sdk-python,lgrahl/threema-msgapi-sdk-python |
b738e428838e038e88fe78db9680e37c72a88497 | scheduler.py | scheduler.py | import logging
import os
from apscheduler.schedulers.blocking import BlockingScheduler
from raven.base import Client as RavenClient
import warner
import archiver
import announcer
import flagger
raven_client = RavenClient()
# When testing changes, set the "TEST_SCHEDULE" envvar to run more often
if os.getenv("DESTA... | import logging
import os
from apscheduler.schedulers.blocking import BlockingScheduler
from raven.base import Client as RavenClient
import warner
import archiver
import announcer
import flagger
from config import Config
raven_client = RavenClient()
# When testing changes, set the "TEST_SCHEDULE" envvar to run more... | Support old environement variable names | Support old environement variable names
| Python | apache-2.0 | royrapoport/destalinator,randsleadershipslack/destalinator,randsleadershipslack/destalinator,TheConnMan/destalinator,royrapoport/destalinator,TheConnMan/destalinator |
397e185ae225613969ecff11e1cfed1e642daca0 | troposphere/codeartifact.py | troposphere/codeartifact.py | # Copyright (c) 2012-2020, Mark Peek <mark@peek.org>
# All rights reserved.
#
# See LICENSE file for full license.
#
# *** Do not modify - this file is autogenerated ***
# Resource specification version: 18.7.0
from . import AWSObject
class Domain(AWSObject):
resource_type = "AWS::CodeArtifact::Domain"
pro... | # Copyright (c) 2012-2021, Mark Peek <mark@peek.org>
# All rights reserved.
#
# See LICENSE file for full license.
#
# *** Do not modify - this file is autogenerated ***
# Resource specification version: 25.0.0
from . import AWSObject
from troposphere import Tags
class Domain(AWSObject):
resource_type = "AWS::C... | Update CodeArtifact per 2020-11-05 changes | Update CodeArtifact per 2020-11-05 changes
| Python | bsd-2-clause | cloudtools/troposphere,cloudtools/troposphere |
e767d25a5e6c088cac6465ce95706e77149f39ef | tests/integration/states/cmd.py | tests/integration/states/cmd.py | '''
Tests for the file state
'''
# Import python libs
import os
#
# Import salt libs
from saltunittest import TestLoader, TextTestRunner
import integration
from integration import TestDaemon
class CMDTest(integration.ModuleCase):
'''
Validate the cmd state
'''
def test_run(self):
'''
c... | '''
Tests for the file state
'''
# Import python libs
# Import salt libs
import integration
import tempfile
class CMDTest(integration.ModuleCase):
'''
Validate the cmd state
'''
def test_run(self):
'''
cmd.run
'''
ret = self.run_state('cmd.run', name='ls', cwd=tempfil... | Use tempdir to ensure there will always be a directory which can be accessed. | Use tempdir to ensure there will always be a directory which can be accessed.
| Python | apache-2.0 | saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt |
6b971de14fbd987286b02bf6e469a1fbb7ad8695 | graph.py | graph.py | from __future__ import unicode_literals
class Graph(object):
"""A class for a simple graph data structure."""
def __init__(self):
self.nodes = {}
def __repr__(self):
pass
def nodes(self):
"""Return a list of all nodes in the graph."""
return [node for node in self.nod... | from __future__ import unicode_literals
class Graph(object):
"""A class for a simple graph data structure."""
def __init__(self):
self.graph = {}
def __repr__(self):
return repr(self.graph)
def nodes(self):
"""Return a list of all nodes in the graph."""
return [node f... | Change dictionary name to avoid collision; fix dict.values() call | Change dictionary name to avoid collision; fix dict.values() call
| Python | mit | jay-tyler/data-structures,jonathanstallings/data-structures |
3365064f885230020fa7671af2d158d5d46e2e80 | modloader/modconfig.py | modloader/modconfig.py | """This file is free software under the GPLv3 license"""
import sys
import os
import shutil
import renpy
from modloader.modinfo import get_mods
def remove_mod(mod_name):
"""Remove a mod from the game and reload.
Args:
mod_name (str): The internal name of the mod to be removed
"""
mod_class ... | """This file is free software under the GPLv3 license"""
import sys
import os
import shutil
from renpy.display.core import Displayable
from renpy.display.render import Render, render
import renpy
from renpy.audio.music import stop as _stop_music
import renpy.game
from renpy.text.text import Text
from renpy.display.ima... | Add message shown when removing mods. Add function to show some text to the screen - `show_message` | Add message shown when removing mods.
Add function to show some text to the screen - `show_message`
| Python | mit | AWSW-Modding/AWSW-Modtools |
4d1a50b1765cd5da46ac9633b3c91eb5e0a72f3d | tests/toolchains/test_atmel_studio.py | tests/toolchains/test_atmel_studio.py | import sys
import unittest
from asninja.parser import AtmelStudioProject
from asninja.toolchains.atmel_studio import *
class TestAtmelStudioGccToolchain(unittest.TestCase):
def test_constructor(self):
tc = AtmelStudioGccToolchain('arm-')
self.assertEqual('arm-', tc.path)
self.assertEqual(... | import sys
import unittest
from unittest.mock import patch
from asninja.parser import AtmelStudioProject
from asninja.toolchains.atmel_studio import *
class TestAtmelStudioGccToolchain(unittest.TestCase):
def test_constructor(self):
tc = AtmelStudioGccToolchain('arm-')
self.assertEqual('arm-', tc... | Use unittest.mock to mock Windows Registry read. | tests: Use unittest.mock to mock Windows Registry read.
| Python | mit | alunegov/AtmelStudioToNinja |
35d80ac6af0a546f138f6db31511e9dade7aae8e | feder/es_search/queries.py | feder/es_search/queries.py | from elasticsearch_dsl import Search, Index
from elasticsearch_dsl.query import MultiMatch, Match, Q, MoreLikeThis
from elasticsearch_dsl.connections import get_connection, connections
from .documents import LetterDocument
def serialize_document(doc):
return {
"_id": doc.__dict__["meta"]["id"],
"_... | from elasticsearch_dsl import Search, Index
from elasticsearch_dsl.query import MultiMatch, Match, Q, MoreLikeThis
from elasticsearch_dsl.connections import get_connection, connections
from .documents import LetterDocument
def serialize_document(doc):
return {
"_id": doc.__dict__["meta"]["id"],
"_... | Reduce debug logging in more_like_this | Reduce debug logging in more_like_this
| Python | mit | watchdogpolska/feder,watchdogpolska/feder,watchdogpolska/feder,watchdogpolska/feder |
0ac9f362906e6d55d10d4c6ee1e0ce1f288821ee | rst2pdf/sectnumlinks.py | rst2pdf/sectnumlinks.py | import docutils
class SectNumFolder(docutils.nodes.SparseNodeVisitor):
def __init__(self, document):
docutils.nodes.SparseNodeVisitor.__init__(self, document)
self.sectnums = {}
def visit_generated(self, node):
for i in node.parent.parent['ids']:
self.sectnums[i]=node.paren... | import docutils
class SectNumFolder(docutils.nodes.SparseNodeVisitor):
def __init__(self, document):
docutils.nodes.SparseNodeVisitor.__init__(self, document)
self.sectnums = {}
def visit_generated(self, node):
for i in node.parent.parent['ids']:
self.sectnums[i]=node.paren... | Support visiting unknown nodes in SectNumFolder and SectRefExpander | Support visiting unknown nodes in SectNumFolder and SectRefExpander
| Python | mit | rst2pdf/rst2pdf,rst2pdf/rst2pdf |
f350de4b748c8a6e8368a8d4500be92ad14b78c3 | pip/vendor/__init__.py | pip/vendor/__init__.py | """
pip.vendor is for vendoring dependencies of pip to prevent needing pip to
depend on something external.
Files inside of pip.vendor should be considered immutable and should only be
updated to versions from upstream.
"""
from __future__ import absolute_import
# Monkeypatch pip.vendor.six into just six
try:
imp... | """
pip.vendor is for vendoring dependencies of pip to prevent needing pip to
depend on something external.
Files inside of pip.vendor should be considered immutable and should only be
updated to versions from upstream.
"""
from __future__ import absolute_import
# Monkeypatch pip.vendor.six into just six
# This is ... | Document the reasons why we are monkeypatching six into sys.modules | Document the reasons why we are monkeypatching six into sys.modules
| Python | mit | minrk/pip,harrisonfeng/pip,tdsmith/pip,xavfernandez/pip,caosmo/pip,zenlambda/pip,haridsv/pip,Carreau/pip,pjdelport/pip,habnabit/pip,alex/pip,davidovich/pip,luzfcb/pip,alex/pip,jamezpolley/pip,pradyunsg/pip,mujiansu/pip,natefoo/pip,sigmavirus24/pip,luzfcb/pip,patricklaw/pip,h4ck3rm1k3/pip,James-Firth/pip,ChristopherHoga... |
348cff3fef4c1bcbbb091ddae9ac407179e08011 | build.py | build.py | #!/usr/bin/python
import sys
import os
from Scripts.common import get_ini_conf, write_ini_conf
if __name__ == "__main__":
# Python 2 compatibility
if sys.version_info.major > 2:
raw_input = input
config = get_ini_conf("config.ini")
# Find cached module name
if "module_name" not in conf... | #!/usr/bin/python
import sys
import os
from os.path import join, realpath, dirname
from Scripts.common import get_ini_conf, write_ini_conf
if __name__ == "__main__":
# Python 2 compatibility
if sys.version_info.major > 2:
raw_input = input
config_file = join(dirname(realpath(__file__)), "config... | Fix issue when the cwd is not in the config directory | Fix issue when the cwd is not in the config directory
| Python | mit | tobspr/P3DModuleBuilder,tobspr/P3DModuleBuilder,tobspr/P3DModuleBuilder |
20288a2e41c43cde37b14c63d4d0733bffe2dd69 | application.py | application.py | #!/usr/bin/env python
import os
from app import create_app
from flask.ext.script import Manager
application = create_app(os.getenv('FLASH_CONFIG') or 'default')
manager = Manager(application)
if __name__ == '__main__':
manager.run()
| #!/usr/bin/env python
import os
from app import create_app
from flask.ext.script import Manager, Server
application = create_app(os.getenv('FLASH_CONFIG') or 'default')
manager = Manager(application)
manager.add_command("runserver", Server(port=5004))
if __name__ == '__main__':
manager.run()
| Update to run on port 5004 | Update to run on port 5004
For development we will want to run multiple apps, so they should each bind to a different port number.
| Python | mit | mtekel/digitalmarketplace-admin-frontend,mtekel/digitalmarketplace-admin-frontend,alphagov/digitalmarketplace-admin-frontend,alphagov/digitalmarketplace-admin-frontend,mtekel/digitalmarketplace-admin-frontend,alphagov/digitalmarketplace-admin-frontend,alphagov/digitalmarketplace-admin-frontend,mtekel/digitalmarketplace... |
aa12f94327060fb0a34a050e0811a5adbd1c0b2a | wsgiproxy/requests_client.py | wsgiproxy/requests_client.py | # -*- coding: utf-8 -*-
import requests
class HttpClient(object):
"""A HTTP client using requests"""
default_options = dict(verify=False, allow_redirects=False)
def __init__(self, chunk_size=1024 * 24, session=None, **requests_options):
options = self.default_options.copy()
options.updat... | # -*- coding: utf-8 -*-
import requests
from functools import partial
class HttpClient(object):
"""A HTTP client using requests"""
default_options = dict(verify=False, allow_redirects=False)
def __init__(self, chunk_size=1024 * 24, session=None, **requests_options):
options = self.default_option... | Return the data not gzip decoded | Return the data not gzip decoded
Requests does that by default so you need to use the underlying raw data and
let webtest decode it itself instead.
| Python | mit | gawel/WSGIProxy2 |
71513ce192b62f36e1d19e8e90188b79153d5e7c | hodor/models/challenges.py | hodor/models/challenges.py | # -*- coding: utf-8 -*-
from hodor import db
from sqlalchemy import inspect
class Challenges(db.Model):
__tablename__= 'challenges'
#Data variables for each Challenges
chalid=db.Column(db.String(32), primary_key=True,unique=True,nullable=False)
name = db.Column(db.String(32), nullable=False)
poi... | # -*- coding: utf-8 -*-
from hodor import db
from sqlalchemy import inspect
class Challenges(db.Model):
__tablename__= 'challenges'
#Data variables for each challenge
chall_id=db.Column(db.String(32), primary_key=True,unique=True,nullable=False)
name = db.Column(db.String(32), nullable=False)
po... | Add hints column in challenge model | Add hints column in challenge model
| Python | mit | hodorsec/hodor-backend |
79d78e477e8cf64e7d4cd86470df3c251f6d8376 | prequ/locations.py | prequ/locations.py | import os
from shutil import rmtree
from .click import secho
from pip.utils.appdirs import user_cache_dir
# The user_cache_dir helper comes straight from pip itself
CACHE_DIR = user_cache_dir('prequ')
# NOTE
# We used to store the cache dir under ~/.pip-tools, which is not the
# preferred place to store caches for a... | from pip.utils.appdirs import user_cache_dir
# The user_cache_dir helper comes straight from pip itself
CACHE_DIR = user_cache_dir('prequ')
| Remove migration code of pip-tools legacy cache | Remove migration code of pip-tools legacy cache
It's not a responsibility of Prequ to remove legacy cache dir of
pip-tools.
| Python | bsd-2-clause | suutari-ai/prequ,suutari/prequ,suutari/prequ |
1474c74bc65576e1931ff603c63be0d5d1ca803a | dmoj/executors/RKT.py | dmoj/executors/RKT.py | from dmoj.executors.base_executor import CompiledExecutor
from dmoj.executors.mixins import ScriptDirectoryMixin
import os
class Executor(ScriptDirectoryMixin, CompiledExecutor):
ext = '.rkt'
name = 'RKT'
fs = ['/etc/nsswitch.conf$', '/etc/passwd$', os.path.expanduser('~/\.racket/.*?'),
'/etc/ra... | import os
from dmoj.executors.base_executor import CompiledExecutor
from dmoj.executors.mixins import ScriptDirectoryMixin
class Executor(ScriptDirectoryMixin, CompiledExecutor):
ext = '.rkt'
name = 'RKT'
fs = [os.path.expanduser('~/\.racket/.*?'), '/etc/racket/.*?']
command = 'racket'
syscalls... | Remove some more paths from Racket | Remove some more paths from Racket
| Python | agpl-3.0 | DMOJ/judge,DMOJ/judge,DMOJ/judge |
bbc0bd975b78d88b8a3a9372f08c343bb1dd5d21 | hours_slept_time_series.py | hours_slept_time_series.py | import plotly as py
import plotly.graph_objs as go
from sys import argv
import names
from csvparser import parse
data_file = argv[1]
raw_data = parse(data_file)
sleep_durations = []
nap_durations = []
for date, rests in raw_data.items():
sleep_total = nap_total = 0
for r in rests:
rest, wake, is_nap ... | import plotly as py
import plotly.graph_objs as go
from sys import argv
import names
from csvparser import parse
data_file = argv[1]
raw_data = parse(data_file)
sleep_durations = []
nap_durations = []
for date, rests in raw_data.items():
sleep_total = nap_total = 0
for r in rests:
rest, wake, is_nap ... | Add markers to time series | Add markers to time series
| Python | mit | f-jiang/sleep-pattern-grapher |
47c0feaf96969d65e8f3e3652903cc20b353103d | vtwt/util.py | vtwt/util.py |
import re
from htmlentitydefs import name2codepoint
# From http://wiki.python.org/moin/EscapingHtml
_HTMLENT_CODEPOINT_RE = re.compile('&({0}|#\d+);'.format(
'|'.join(name2codepoint.keys())))
def recodeText(text):
def _entToUnichr(match):
ent = match.group(1)
try:
if ent.sta... |
import re
from htmlentitydefs import name2codepoint
# From http://wiki.python.org/moin/EscapingHtml
_HTMLENT_CODEPOINT_RE = re.compile('&({0}|#\d+);'.format(
'|'.join(name2codepoint.keys())))
def recodeText(text):
"""Parses things like & and ὔ into real characters."""
def _entToUnichr(mat... | Add a comment for robin | Add a comment for robin
| Python | bsd-3-clause | olix0r/vtwt |
bf2c3e8553c0cbf0ab863efe1459a1da11b99355 | sigopt/exception.py | sigopt/exception.py | import copy
class SigOptException(Exception):
pass
class ApiException(SigOptException):
def __init__(self, body, status_code):
self.message = body.get('message', None) if body is not None else None
self._body = body
if self.message is not None:
super(ApiException, self).__init__(self.message)
... | import copy
class SigOptException(Exception):
pass
class ApiException(SigOptException):
def __init__(self, body, status_code):
self.message = body.get('message', None) if body is not None else None
self._body = body
if self.message is not None:
super(ApiException, self).__init__(self.message)
... | Add str/repr methods to ApiException | Add str/repr methods to ApiException
| Python | mit | sigopt/sigopt-python,sigopt/sigopt-python |
e85e94d901560cd176883b3522cf0a961759732c | db/Db.py | db/Db.py | import abc
import sqlite3
import Config
class Db(object):
__metaclass__ = abc.ABCMeta
def __init__(self):
self._connection = self.connect()
@abc.abstractmethod
def connect(self, config_file = None):
raise NotImplementedError("Called method is not implemented")
@abc.abstrac... | import abc
import sqlite3
from ebroker.Config import Config
def getDb(config_file = None):
return SQLiteDb(config_file)
class Db(object):
__metaclass__ = abc.ABCMeta
def __init__(self, config_file = None):
self._config_file = config_file
self._connection = None # make sure attribute ... | Fix various small issues in DB support | Fix various small issues in DB support
| Python | mit | vjuranek/e-broker-client |
b175b8a68cd98aa00326747aa66038f9692d8704 | ginga/qtw/Plot.py | ginga/qtw/Plot.py | #
# Plot.py -- Plotting function for Ginga FITS viewer.
#
# Eric Jeschke (eric@naoj.org)
#
# Copyright (c) Eric R. Jeschke. All rights reserved.
# This is open-source software licensed under a BSD license.
# Please see the file LICENSE.txt for details.
#
# GUI imports
from ginga.qtw.QtHelp import QtGui, QtCore
from g... | #
# Plot.py -- Plotting function for Ginga FITS viewer.
#
# Eric Jeschke (eric@naoj.org)
#
# Copyright (c) Eric R. Jeschke. All rights reserved.
# This is open-source software licensed under a BSD license.
# Please see the file LICENSE.txt for details.
#
# GUI imports
from ginga.qtw.QtHelp import QtGui, QtCore
from g... | Fix for Qt5 in plugins that use matplotlib | Fix for Qt5 in plugins that use matplotlib
| Python | bsd-3-clause | rupak0577/ginga,eteq/ginga,eteq/ginga,naojsoft/ginga,stscieisenhamer/ginga,eteq/ginga,Cadair/ginga,sosey/ginga,rajul/ginga,ejeschke/ginga,naojsoft/ginga,pllim/ginga,rajul/ginga,Cadair/ginga,rajul/ginga,Cadair/ginga,sosey/ginga,sosey/ginga,stscieisenhamer/ginga,pllim/ginga,rupak0577/ginga,pllim/ginga,rupak0577/ginga,eje... |
72115876305387bcbc79f5bd6dff69e7ad0cbf8e | Models/LogNormal.py | Models/LogNormal.py | from __future__ import division
import sys
import numpy as np
from random import randrange, choice
import matplotlib.pyplot as plt
from matplotlib import patches, path
import scipy.stats
'''This script codes the LogNormal Models'''
# To code the LogNormal...each division is ... | from __future__ import division
import sys
import numpy as np
from random import randrange, choice
import matplotlib.pyplot as plt
from matplotlib import patches, path
import scipy.stats
'''This script codes the LogNormal Models'''
# To code the LogNormal...each division is ... | Work on Log Normal. Not ready yet. | Work on Log Normal. Not ready yet.
| Python | mit | nhhillis/SADModels |
40bb2b8aaff899f847211273f6631547b6bac978 | pyhessian/data_types.py | pyhessian/data_types.py | __all__ = ['long']
if hasattr(__builtins__, 'long'):
long = long
else:
class long(int):
pass
| __all__ = ['long']
if 'long' in __builtins__:
long = __builtins__['long']
else:
class long(int):
pass
| Fix bug encoding long type in python 2.x | Fix bug encoding long type in python 2.x
| Python | bsd-3-clause | cyrusmg/python-hessian,cyrusmg/python-hessian,cyrusmg/python-hessian |
2aa19e8b039b202ea3cf59e4ce95d8f16f4bc284 | generate-key.py | generate-key.py | #!/usr/bin/python
import os
import sqlite3
import sys
import time
db = sqlite3.connect('/var/lib/zon-api/data.db')
if len(sys.argv) < 3:
print('Usage: %s "Firstname Lastname" email@example.com' % sys.argv[0])
print('\nLast keys:')
query = 'SELECT * FROM client ORDER by reset DESC'
for client in db.ex... | #!/usr/bin/python
from datetime import datetime
import os
import sqlite3
import sys
import time
db = sqlite3.connect('/var/lib/zon-api/data.db')
if len(sys.argv) < 3:
print('Usage: %s "Firstname Lastname" email@example.com' % sys.argv[0])
print('\nLast keys:')
query = 'SELECT * FROM client ORDER by reset... | Include 'reset' date when listing keys | MAINT: Include 'reset' date when listing keys
Note that this has been changed long ago and only committed now to catch
up with the currently deployed state.
| Python | bsd-3-clause | ZeitOnline/content-api,ZeitOnline/content-api |
b172c997ef6b295b0367afb381ab818a254ce59b | geodj/models.py | geodj/models.py | from django.db import models
class Country(models.Model):
name = models.TextField()
iso_code = models.CharField(max_length=2, unique=True)
def __unicode__(self):
return self.name
class Artist(models.Model):
name = models.TextField()
mbid = models.TextField(unique=True)
country = model... | from django.db import models
class Country(models.Model):
name = models.TextField()
iso_code = models.CharField(max_length=2, unique=True)
def __unicode__(self):
return self.name
@staticmethod
def with_artists():
return Country.objects.annotate(number_of_artists=models.Count('arti... | Add Country.with_artists() to filter out countries without artists | Add Country.with_artists() to filter out countries without artists
| Python | mit | 6/GeoDJ,6/GeoDJ |
211091ed92e8bafcac1e9b1c523d392b609fca73 | saleor/core/tracing.py | saleor/core/tracing.py | from functools import partial
from graphene.types.resolver import default_resolver
from graphql import ResolveInfo
def should_trace(info: ResolveInfo) -> bool:
if info.field_name not in info.parent_type.fields:
return False
resolver = info.parent_type.fields[info.field_name].resolver
return not ... | from functools import partial
from graphene.types.resolver import default_resolver
from graphql import ResolveInfo
def should_trace(info: ResolveInfo) -> bool:
if info.field_name not in info.parent_type.fields:
return False
resolver = info.parent_type.fields[info.field_name].resolver
return not ... | Fix mypy error in introspection check | Fix mypy error in introspection check
| Python | bsd-3-clause | mociepka/saleor,mociepka/saleor,mociepka/saleor |
657b9cd09b3d4c7c07f53bc8f2d995d3b08b63c5 | wsgi.py | wsgi.py | #!/usr/bin/python
import os
virtenv = os.path.join(os.environ.get('OPENSHIFT_PYTHON_DIR', '.'), 'virtenv')
virtualenv = os.path.join(virtenv, 'bin/activate_this.py')
try:
exec_namespace = dict(__file__=virtualenv)
with open(virtualenv, 'rb') as exec_file:
file_contents = exec_file.read()
compiled... | #!/usr/bin/python
import os
virtenv = os.path.join(os.environ.get('OPENSHIFT_PYTHON_DIR', '.'), 'virtenv')
virtualenv = os.path.join(virtenv, 'bin/activate_this.py')
try:
exec_namespace = dict(__file__=virtualenv)
with open(virtualenv, 'rb') as exec_file:
file_contents = exec_file.read()
compiled... | Use `0.0.0.0` instead of `localhost` | Use `0.0.0.0` instead of `localhost`
| Python | mit | avinassh/slackipy,avinassh/slackipy,avinassh/slackipy |
62a20e28a5f0bc9b6a9eab67891c875562337c94 | rwt/tests/test_deps.py | rwt/tests/test_deps.py | import pkg_resources
from rwt import deps
def test_entry_points():
"""
Ensure entry points are visible after making packages visible
"""
with deps.on_sys_path('jaraco.mongodb'):
eps = pkg_resources.iter_entry_points('pytest11')
assert list(eps), "Entry points not found"
class TestInstallCheck:
def test_in... | import copy
import pkg_resources
from rwt import deps
def test_entry_points():
"""
Ensure entry points are visible after making packages visible
"""
with deps.on_sys_path('jaraco.mongodb'):
eps = pkg_resources.iter_entry_points('pytest11')
assert list(eps), "Entry points not found"
class TestInstallCheck:... | Fix test failure on Python 2 | Fix test failure on Python 2
| Python | mit | jaraco/rwt |
507be5c8923b05304b223785cdba79ae7513f48a | openedx/stanford/djangoapps/register_cme/admin.py | openedx/stanford/djangoapps/register_cme/admin.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.contrib import admin
from .models import ExtraInfo
class ExtraInfoAdmin(admin.ModelAdmin):
""" Admin interface for ExtraInfo model. """
list_display = ('user', 'get_email', 'last_name', 'first_name',)
search_fields = ('user__user... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.contrib import admin
from .models import ExtraInfo
admin.site.register(ExtraInfo)
| Revert "Change `ExtraInfo` to user fields, add search" | Revert "Change `ExtraInfo` to user fields, add search"
This reverts commit f5984fbd4187f4af65fb39b070f91870203d869b.
| Python | agpl-3.0 | caesar2164/edx-platform,caesar2164/edx-platform,caesar2164/edx-platform,Stanford-Online/edx-platform,Stanford-Online/edx-platform,Stanford-Online/edx-platform,caesar2164/edx-platform,Stanford-Online/edx-platform |
83c0e33db27bc2b9aa7e06e125230e6c159439bb | address_book/address_book.py | address_book/address_book.py | __all__ = ['AddressBook']
class AddressBook(object):
pass | __all__ = ['AddressBook']
class AddressBook(object):
def __init__(self):
self.persons = []
def add_person(self, person):
self.persons.append(person)
| Add persons storage and `add_person` method to `AddressBook` class | Add persons storage and `add_person` method to `AddressBook` class
| Python | mit | dizpers/python-address-book-assignment |
d27b2d71a0e5f834d4758c67fa6e8ed342001a88 | salt/output/__init__.py | salt/output/__init__.py | '''
Used to manage the outputter system. This package is the modular system used
for managing outputters.
'''
import salt.loader
def display_output(data, out, opts=None):
'''
Print the passed data using the desired output
'''
if opts is None:
opts = {}
outputters = salt.loader.outputters(o... | '''
Used to manage the outputter system. This package is the modular system used
for managing outputters.
'''
# Import salt utils
import salt.loader
def display_output(data, out, opts=None):
'''
Print the passed data using the desired output
'''
if opts is None:
opts = {}
outputters = salt... | Add some checks to output module | Add some checks to output module
| Python | apache-2.0 | saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt |
f1afc32efaf0df2a2f8a0b474dc367c1eba8681d | salt/renderers/jinja.py | salt/renderers/jinja.py | from __future__ import absolute_import
# Import python libs
from StringIO import StringIO
# Import salt libs
from salt.exceptions import SaltRenderError
import salt.utils.templates
def render(template_file, env='', sls='', argline='',
context=None, tmplpath=None, **kws):
'''
Render... | from __future__ import absolute_import
# Import python libs
from StringIO import StringIO
# Import salt libs
from salt.exceptions import SaltRenderError
import salt.utils.templates
def render(template_file, env='', sls='', argline='',
context=None, tmplpath=None, **kws):
'''
Render... | Clean up some PEP8 stuff | Clean up some PEP8 stuff
| Python | apache-2.0 | saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt |
3706700e4725d23752269c2e833adfa736d0ce96 | worker/jobs/session/__init__.py | worker/jobs/session/__init__.py | import os
from typing import Optional, List
from jobs.base.job import Job
# If on a K8s cluster then use the K8s-based sessions
# otherwise use the subsprocess-based session
if "KUBERNETES_SERVICE_HOST" in os.environ:
from .kubernetes_session import KubernetesSession
Session = KubernetesSession # type: igno... | from typing import Type, Union
from .kubernetes_session import api_instance, KubernetesSession
from .subprocess_session import SubprocessSession
# If on a K8s is available then use that
# otherwise use the subsprocess-based session
Session: Type[Union[KubernetesSession, SubprocessSession]]
if api_instance is not None... | Improve switching between session types | fix(Worker): Improve switching between session types
| Python | apache-2.0 | stencila/hub,stencila/hub,stencila/hub,stencila/hub,stencila/hub |
713b1292019fef93e5ff2d11a22e775a59f3b3a8 | south/signals.py | south/signals.py | """
South-specific signals
"""
from django.dispatch import Signal
from django.conf import settings
# Sent at the start of the migration of an app
pre_migrate = Signal(providing_args=["app"])
# Sent after each successful migration of an app
post_migrate = Signal(providing_args=["app"])
# Sent after each run of a par... | """
South-specific signals
"""
from django.dispatch import Signal
from django.conf import settings
# Sent at the start of the migration of an app
pre_migrate = Signal(providing_args=["app"])
# Sent after each successful migration of an app
post_migrate = Signal(providing_args=["app"])
# Sent after each run of a par... | Remove the auth contenttypes thing for now, needs improvement | Remove the auth contenttypes thing for now, needs improvement
| Python | apache-2.0 | theatlantic/django-south,theatlantic/django-south |
c39faa36f2f81198ed9aaaf7e43096a454feaa0e | molly/molly/wurfl/views.py | molly/molly/wurfl/views.py | from pywurfl.algorithms import DeviceNotFound
from django.http import Http404
from molly.utils.views import BaseView
from molly.utils.breadcrumbs import NullBreadcrumb
from molly.wurfl.vsm import vsa
from molly.wurfl import device_parents
from molly.wurfl.wurfl_data import devices
class IndexView(BaseView):
bre... | from pywurfl.algorithms import DeviceNotFound
from django.http import Http404
from molly.utils.views import BaseView
from molly.utils.breadcrumbs import NullBreadcrumb
from molly.wurfl.vsm import vsa
from molly.wurfl import device_parents
from molly.wurfl.wurfl_data import devices
class IndexView(BaseView):
bre... | Add UA and matched UA to device-detection view output. | Add UA and matched UA to device-detection view output.
| Python | apache-2.0 | mollyproject/mollyproject,mollyproject/mollyproject,mollyproject/mollyproject |
fbbc42fd0c023f6f5f603f9dfcc961d87ca6d645 | zou/app/blueprints/crud/custom_action.py | zou/app/blueprints/crud/custom_action.py | from zou.app.models.custom_action import CustomAction
from .base import BaseModelsResource, BaseModelResource
class CustomActionsResource(BaseModelsResource):
def __init__(self):
BaseModelsResource.__init__(self, CustomAction)
class CustomActionResource(BaseModelResource):
def __init__(self):
... | from zou.app.models.custom_action import CustomAction
from .base import BaseModelsResource, BaseModelResource
class CustomActionsResource(BaseModelsResource):
def __init__(self):
BaseModelsResource.__init__(self, CustomAction)
def check_permissions(self):
return True
class CustomActionRes... | Allow anyone to read custom actions | Allow anyone to read custom actions
| Python | agpl-3.0 | cgwire/zou |
c677df5f5f39afbf3aef3ceb1e83f3a97fb53f6b | bonspy/utils.py | bonspy/utils.py | def compare_vectors(x, y):
for x_i, y_i in zip(x, y):
comparison = _compare(x_i, y_i)
if comparison == 0:
continue
else:
return comparison
return 0
def _compare(x, y):
if x is not None and y is not None:
return int(x > y) - int(x < y)
elif x is n... | def compare_vectors(x, y):
for x_i, y_i in zip(x, y):
comparison = _compare(x_i, y_i)
if comparison == 0:
continue
else:
return comparison
return 0
def _compare(x, y):
if x is not None and y is not None:
return int(x > y) - int(x < y)
elif x is n... | Fix bugs in new class | Fix bugs in new class
| Python | bsd-3-clause | markovianhq/bonspy |
8b399d6ede630b785b51fb9e32fda811328e163e | test.py | test.py | import unittest
from enigma import Enigma, Umkehrwalze, Walzen
class EnigmaTestCase(unittest.TestCase):
def setUp(self):
# Rotors go from right to left, so I reverse the tuple to make Rotor
# I be the leftmost. I may change this behavior in the future.
rotors = (
Walzen(wiring... | import unittest
from enigma import Enigma, Umkehrwalze, Walzen
class EnigmaTestCase(unittest.TestCase):
def setUp(self):
# Rotors go from right to left, so I reverse the tuple to make Rotor
# I be the leftmost. I may change this behavior in the future.
rotors = (
Walzen(wiring... | Test if ciphering is bidirectional | Test if ciphering is bidirectional
| Python | mit | ranisalt/enigma |
fafedf1cfdcd6c6b06dd4093a44db7429bd553eb | issues/views.py | issues/views.py | # Create your views here.
| # Python Imports
import datetime
import md5
import os
# Django Imports
from django.http import HttpResponse, HttpResponseRedirect
from django.conf import settings
from django.core import serializers
from django.contrib.auth.decorators import login_required
from django.utils.translation import gettext as _
from django.... | Add basic issue view, list, create. | [ISSUES] Add basic issue view, list, create.
| Python | bsd-3-clause | clsdaniel/iridium |
28baf3a2568f8e1b67a19740ecd7ccfc90d36514 | swift/dedupe/killall.py | swift/dedupe/killall.py | #!/usr/bin/python
__author__ = 'mjwtom'
import os
os.system('ps -aux | grep swift-proxy-server | grep -v grep | cut -c 9-15 | xargs kill -s 9')
os.system('ps -aux | grep swift-account-server | grep -v grep | cut -c 9-15 | xargs kill -s 9')
os.system('ps -aux | grep swift-container-server | grep -v grep | cut -c 9-15... | #!/usr/bin/python
__author__ = 'mjwtom'
import os
os.system('ps -aux | grep swift-proxy-server | grep -v grep | cut -c 9-15 | xargs kill -s 9')
os.system('ps -aux | grep swift-account-server | grep -v grep | cut -c 9-15 | xargs kill -s 9')
os.system('ps -aux | grep swift-container-server | grep -v grep | cut -c 9-15... | Change the position. use proxy-server to do dedupe instead of object-server | Change the position. use proxy-server to do dedupe instead of object-server
| Python | apache-2.0 | mjwtom/swift,mjwtom/swift |
6dd04ed490c49c85bf91db2cb0bf2bed82b5967b | fasttsne/__init__.py | fasttsne/__init__.py | import scipy.linalg as la
import numpy as np
from py_bh_tsne import _TSNE as TSNE
def fast_tsne(data, pca_d=50, d=2, perplexity=30., theta=0.5):
"""
Run Barnes-Hut T-SNE on _data_.
@param data The data.
@param pca_d The dimensionality of data is reduced via PCA
... | import scipy.linalg as la
import numpy as np
from fasttsne import _TSNE as TSNE
def fast_tsne(data, pca_d=None, d=2, perplexity=30., theta=0.5):
"""
Run Barnes-Hut T-SNE on _data_.
@param data The data.
@param pca_d The dimensionality of data is reduced via PCA
... | FIX (from Justin Bayer): avoid memory segfault when pca_d is choosen too big. | FIX (from Justin Bayer): avoid memory segfault when pca_d is choosen too big.
| Python | bsd-3-clause | pryvkin10x/tsne,douglasbagnall/py_bh_tsne,douglasbagnall/py_bh_tsne,pryvkin10x/tsne,pryvkin10x/tsne |
e1a54c7d08f33601e48aec485ac72d9d81730186 | spec/helper.py | spec/helper.py | from expects import *
from pygametemplate import Game
import datetime
class TestGame(Game):
"""An altered Game class for testing purposes."""
def __init__(self, resolution):
super(TestGame, self).__init__(resolution)
def log(self, *error_message):
"""Altered log function which just rais... | from expects import *
from example_view import ExampleView
from pygametemplate import Game
import datetime
class TestGame(Game):
"""An altered Game class for testing purposes."""
def __init__(self, StartingView, resolution):
super(TestGame, self).__init__(StartingView, resolution)
def log(self,... | Fix TestGame class to match the View update to Game | Fix TestGame class to match the View update to Game
| Python | mit | AndyDeany/pygame-template |
9cca5d4ce1c5097e48e55ad3a48b09a01cc0aa6b | lumberjack/config/__init__.py | lumberjack/config/__init__.py | # -*- coding: utf-8 -*-
"""
Module to allow quick configuration.
"""
from six.moves import configparser
from six import StringIO
import pkg_resources
import logging.config
def configure(mode, disable_existing_loggers=False):
"""Configure from predefined useful default modes."""
cfg = configparser.ConfigParser... | # -*- coding: utf-8 -*-
"""
Module to allow quick configuration.
"""
from six.moves import configparser
from six import StringIO
import pkg_resources
import logging.config
def configure(mode, disable_existing_loggers=False):
"""Configure from predefined useful default modes."""
cfg = configparser.ConfigParser... | Read a custom lumberjack.cfg on startup if necessary. | Read a custom lumberjack.cfg on startup if necessary.
| Python | mit | alexrudy/lumberjack |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.