commit stringlengths 40 40 | old_file stringlengths 4 150 | new_file stringlengths 4 150 | old_contents stringlengths 0 3.26k | new_contents stringlengths 1 4.43k | subject stringlengths 15 501 | message stringlengths 15 4.06k | lang stringclasses 4
values | license stringclasses 13
values | repos stringlengths 5 91.5k | diff stringlengths 0 4.35k |
|---|---|---|---|---|---|---|---|---|---|---|
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... | ---
+++
@@ -17,5 +17,8 @@
urlpatterns = patterns('pombola.south_africa.views',
url(r'^place/latlon/(?P<lat>[0-9\.-]+),(?P<lon>[0-9\.-]+)/', LatLonDetailView.as_view(), name='latlon'),
url(r'^place/(?P<slug>[-\w]+)/places/', SAPlaceDetailSub.as_view(), {'sub_page': 'places'}, name='place_places'),
+
+ # ... |
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 | ---
+++
@@ -14,4 +14,10 @@
excerpt: Optional[str]
content: Optional[str]
published: DateTime
- image: Optional[str]
+
+ @strawberry.field
+ def image(self, info) -> Optional[str]:
+ if not self.image:
+ return None
+
+ return info.context.build_absolute_uri(self.image.... |
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 | ---
+++
@@ -21,13 +21,13 @@
filepath = "clean.zip"
# Concoct the latest URL
path = os.path.join(
- settings.AWS_STORAGE_BUCKET_NAME,
+ "calaccess.download",
'latest',
filepath
)
# If not we can just join it to the subject nam... |
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 | ---
+++
@@ -1,18 +1,18 @@
-"""Convenience to import Qt if it is availible, otherwise provide stubs.
+"""Wrapping the differences between PyQt4 and PySide."""
-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 ... |
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 | ---
+++
@@ -3,4 +3,13 @@
with irc notifications
"""
+import argparse
+
import github3
+
+
+def main():
+ parser = argparse.ArgumentParser()
+ parser.add_argument('--username'),
+ parser.add_argument('--password'),
+ args = parser.parse_args() |
d384781d77521f6e4b97b783737be09a7a99423e | glance_registry_local_check.py | glance_registry_local_check.py | #!/usr/bin/env python
from maas_common import (status_ok, status_err, metric, get_keystone_client,
get_auth_ref)
from requests import Session
from requests import exceptions as exc
def check(auth_ref):
keystone = get_keystone_client(auth_ref)
tenant_id = keystone.tenant_id
auth_t... | #!/usr/bin/env python
from maas_common import (status_ok, status_err, metric, get_keystone_client,
get_auth_ref)
from requests import Session
from requests import exceptions as exc
def check(auth_ref):
keystone = get_keystone_client(auth_ref)
tenant_id = keystone.tenant_id
auth_t... | Change metric type to int32 | Change metric type to int32
This was done as we may now send a -1 to indicate that we could not
obtain response timing from request.
| Python | apache-2.0 | mattt416/rpc-openstack,xeregin/rpc-openstack,darrenchan/rpc-openstack,major/rpc-openstack,byronmccollum/rpc-openstack,shannonmitchell/rpc-openstack,cloudnull/rpc-maas,npawelek/rpc-maas,miguelgrinberg/rpc-openstack,robb-romans/rpc-openstack,rcbops/rpc-openstack,BjoernT/rpc-openstack,nrb/rpc-openstack,git-harry/rpc-opens... | ---
+++
@@ -37,7 +37,7 @@
status_ok()
metric('glance_registry_local_status', 'uint32', api_status)
- metric('glance_registry_local_response_time', 'uint32', milliseconds)
+ metric('glance_registry_local_response_time', 'int32', milliseconds)
def main(): |
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 | ---
+++
@@ -25,5 +25,10 @@
def cleanup(value):
- value = re.sub('\{code.*?\}.*?\{code\}', ' ', value, 0, re.S)
+ """
+ Remove {code}...{/code} and {noformat}...{noformat} fragments from worklog comment
+ :param value: worklog comment text
+ :return: cleaned worklog comment text
+ """
+ value... |
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 | ---
+++
@@ -17,7 +17,6 @@
@admin.register(Event)
class EventAdmin(BlancPageAdminMixin, admin.ModelAdmin):
- pass
fieldsets = (
('Event', {
'fields': (
@@ -30,7 +29,7 @@
)
date_hierarchy = 'start'
list_display = ('title', 'start', 'end', 'category',)
- list_filter = ... |
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 | ---
+++
@@ -23,8 +23,7 @@
)
response.raise_for_status()
result = response.json()
-
- return [project["name"] for project in result["projects"]]
+ return result["projects"]
def get_distgit_client(settings: Settings = Depends(get_settings)): |
6e76c9af0a4bdd6696b918913af73559c6dcd3c3 | main.py | main.py | #!/usr/bin/env python3
from flask import Flask
from flask import request
from flask import jsonify
from utils import download_file, is_video_json_valid
from annotations import sort_annotations_by_time, is_annotation_json_valid
from videoeditor import bake_annotations
app = Flask(__name__)
@app.route("/", methods=["... | #!/usr/bin/env python3
from flask import Flask
from flask import request
from flask import jsonify
from utils import download_file, is_video_json_valid
from annotations import sort_annotations_by_time, is_annotation_json_valid
from videoeditor import bake_annotations
app = Flask(__name__)
@app.route("/", methods=["... | Add a bunch more JSON payload validation related funcionality | Add a bunch more JSON payload validation related funcionality
| Python | mit | melonmanchan/achso-video-exporter,melonmanchan/achso-video-exporter | ---
+++
@@ -19,8 +19,13 @@
request_json = [request_json]
for video_json in request_json:
- if not is_video_json_valid(video_json) or not is_annotation_json_valid(video_json["annotations"]):
- return jsonify({"message": "Annotation json was malformed"}), 400
+ if not is_video_j... |
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 | ---
+++
@@ -9,6 +9,9 @@
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" |
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 | ---
+++
@@ -1,3 +1,4 @@
+# -*- coding: utf-8 -*-
from django.shortcuts import render
from django.http import HttpResponse
@@ -17,6 +18,7 @@
json_data = [dict(
id=member.id,
+ faculty_number=member.faculty_number,
full_name=' '.join([member.first_name, member.last_name]))
... |
87ce10a94bdbedd97dae19989a7382b2bfa8ecde | snactor/utils/__init__.py | snactor/utils/__init__.py |
def get_chan(channels, chan):
channels.setdefault(chan['name'], {'producers': [], 'consumers': [], 'data': chan})
|
def get_chan(channels, chan):
return channels.setdefault(chan['name'], {'producers': [], 'consumers': [], 'data': chan})
| Fix get_chan (which should return the channel) | Fix get_chan (which should return the channel)
| Python | apache-2.0 | leapp-to/snactor | ---
+++
@@ -1,3 +1,3 @@
def get_chan(channels, chan):
- channels.setdefault(chan['name'], {'producers': [], 'consumers': [], 'data': chan})
+ return channels.setdefault(chan['name'], {'producers': [], 'consumers': [], 'data': chan}) |
fdb1931b7cac6f0c7968829efb81ea677d2b5390 | linux/user/srwrapper.py | linux/user/srwrapper.py | #!/usr/bin/env python
import subprocess
import sys
import time
SRHOME = '/home/stoneridge'
SRPYTHON = '%s/stoneridge' % (SRHOME,)
SRRUN = '%s/srrun.py' % (SRPYTHON,)
SRWORKER = '%s/srworker.py' % (SRPYTHON,)
SRINI = '%s/stoneridge.ini' % (SRHOME,)
LOG = '%s/srworker.log' % (SRHOME,)
cli = [sys.executable, SRRUN, SRW... | #!/usr/bin/env python
import subprocess
import sys
import time
SRHOME = '/home/stoneridge'
SRPYTHON = '%s/stoneridge' % (SRHOME,)
SRRUN = '%s/srrun.py' % (SRPYTHON,)
SRWORKER = '%s/srworker.py' % (SRPYTHON,)
SRINI = '%s/stoneridge.ini' % (SRHOME,)
LOG = '%s/logs/srworker.log' % (SRHOME,)
cli = [sys.executable, SRRUN... | Fix path to worker log on linux | Fix path to worker log on linux
| Python | mpl-2.0 | mozilla/stoneridge,mozilla/stoneridge,mozilla/stoneridge,mozilla/stoneridge,mozilla/stoneridge,mozilla/stoneridge,mozilla/stoneridge,mozilla/stoneridge | ---
+++
@@ -9,7 +9,7 @@
SRRUN = '%s/srrun.py' % (SRPYTHON,)
SRWORKER = '%s/srworker.py' % (SRPYTHON,)
SRINI = '%s/stoneridge.ini' % (SRHOME,)
-LOG = '%s/srworker.log' % (SRHOME,)
+LOG = '%s/logs/srworker.log' % (SRHOME,)
cli = [sys.executable, SRRUN, SRWORKER, '--config', SRINI, '--log', LOG]
|
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 | ---
+++
@@ -15,5 +15,26 @@
(i if isinstance(i, str) else convert_readable(i)))
for i in tree)
+def find_tokens(tree):
+ if isinstance(tree, str):
+ return tuple(), tuple()
+ if tree[0] == 'NAME':
+ return (tree[1],), tuple()
+ if tree[0] == 'import_name':
... |
a65d86ea92d6b3de2d8585650595677efc18d3c2 | test.py | test.py | import time
import urllib
import RPi.GPIO as GPIO
# GPIO input pin to use
LPR_PIN = 3
# URL to get image from
SOURCE = 'http://192.168.0.13:8080/photoaf.jpg'
# Path to save image locally
FILE = 'img.jpg'
# Use GPIO pin numbers
GPIO.setmode(GPIO.BCM)
# Disable "Ports already in use" warning
GPIO.setwarnings(False)
# ... | import time
import urllib
import RPi.GPIO as GPIO
# GPIO input pin to use
LPR_PIN = 3
# URL to get image from
SOURCE = 'http://192.168.0.13:8080/photoaf.jpg'
# Path to save image locally
FILE = 'img.jpg'
# Use GPIO pin numbers
GPIO.setmode(GPIO.BCM)
# Disable "Ports already in use" warning
GPIO.setwarnings(False)
# ... | Adjust loop delay to take into account switch undecidedness (Step one in presentation) | Adjust loop delay to take into account switch undecidedness (Step one in presentation)
| Python | mit | adampiskorski/lpr_poc | ---
+++
@@ -34,4 +34,4 @@
print "The gate has now closed!"
captured = False
- time.sleep(0.1)
+ time.sleep(1) |
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 | ---
+++
@@ -8,7 +8,8 @@
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";', '')
+ def remove_use_strict(self, js):
+ # Replacing by a ';' is safer than ... |
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 | ---
+++
@@ -11,8 +11,8 @@
"""
from flask import Flask
-from flaskext.sqlalchemy import SQLAlchemy
from flaskext.uploads import configure_uploads, UploadSet, IMAGES
+from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__)
|
b09424edf37989c3868eb63badfc65897d41f410 | kremlin/__init__.py | kremlin/__init__.py | """
# # #### ##### # # ##### # # # #
# # # # # ## ## # # # ## # #
### #### #### # # # # # # # # #####
# # # # # # # # ## # # #
# # # ##### # # # # # # # #
Kremlin Mag... | """
# # #### ##### # # ##### # # # #
# # # # # ## ## # # # ## # #
### #### #### # # # # # # # # #####
# # # # # # # # ## # # #
# # # ##### # # # # # # # #
Kremlin Mag... | Fix legacy import for Flask-Uploads | Fix legacy import for Flask-Uploads
| Python | bsd-2-clause | glasnost/kremlin,glasnost/kremlin,glasnost/kremlin | ---
+++
@@ -11,7 +11,7 @@
"""
from flask import Flask
-from flaskext.uploads import configure_uploads, UploadSet, IMAGES
+from flask_uploads import configure_uploads, UploadSet, IMAGES
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__) |
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 | ---
+++
@@ -1,4 +1,5 @@
import os
+import socket
from serf_master import SerfHandler
from utils import with_payload, truncated_stdout
@@ -21,6 +22,6 @@
print(self.my_info())
def my_info(self):
- return {
- 'ip': os.environ.get('ADVERTISE', None)
- }
+ ip = (os.... |
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 | ---
+++
@@ -1,6 +1,8 @@
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):
@@ -8,11 +10,18 @@
# Append instead of extend or += because those... |
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 | ---
+++
@@ -1,32 +1,20 @@
# 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):
"""
C... |
1f598e3752d18ecf4f022588531093d711ac6c01 | lemur/authorizations/models.py | lemur/authorizations/models.py | """
.. module: lemur.authorizations.models
:platform: unix
:copyright: (c) 2018 by Netflix Inc., see AUTHORS for more
:license: Apache, see LICENSE for more details.
.. moduleauthor:: Netflix Secops <secops@netflix.com>
"""
from sqlalchemy import Column, Integer, String
from sqlalchemy_utils import JSONType... | """
.. module: lemur.authorizations.models
:platform: unix
:copyright: (c) 2018 by Netflix Inc., see AUTHORS for more
:license: Apache, see LICENSE for more details.
.. moduleauthor:: Netflix Secops <secops@netflix.com>
"""
from sqlalchemy import Column, Integer, String
from sqlalchemy_utils import JSONType... | Fix unmatched field in Authorization | Fix unmatched field in Authorization
The field in the formatted string was not matching the args | Python | apache-2.0 | Netflix/lemur,Netflix/lemur,Netflix/lemur,Netflix/lemur | ---
+++
@@ -25,7 +25,7 @@
return plugins.get(self.plugin_name)
def __repr__(self):
- return "Authorization(id={id})".format(label=self.id)
+ return "Authorization(id={id})".format(id=self.id)
def __init__(self, account_number, domains, dns_provider_type, options=None):
se... |
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 | ---
+++
@@ -16,7 +16,28 @@
def get_diff_for_diffid(diffid):
- return "This is a test diff"
+ rev = urlopen("http://en.wikipedia.org/w/api.php?action=query&prop=revisions&format=json&rvdiffto=prev&revids=%s" % diffid).read()
+ rev = json.loads(rev)
+ pages = rev["query"]["pages"]
+ diff = pages.val... |
4ca1fdddfa7b76ecd515473d102867868f8d7204 | pywikibot/families/wikidata_family.py | pywikibot/families/wikidata_family.py | # -*- coding: utf-8 -*-
__version__ = '$Id$'
from pywikibot import family
# The wikidata family
class Family(family.WikimediaFamily):
def __init__(self):
super(Family, self).__init__()
self.name = 'wikidata'
self.langs = {
'wikidata': 'wikidata.org',
'repo': 'wik... | # -*- coding: utf-8 -*-
__version__ = '$Id$'
from pywikibot import family
# The wikidata family
class Family(family.WikimediaFamily):
def __init__(self):
super(Family, self).__init__()
self.name = 'wikidata'
self.langs = {
'wikidata': 'www.wikidata.org',
'repo': ... | Use www.wikidata.org instead of wikidata.org Rewrite-followup to r11105 | Use www.wikidata.org instead of wikidata.org
Rewrite-followup to r11105
Patch #3605769 by Legoktm
Because of various issues [1], using wikidata.org may cause random problems.
Using www.wikidata.org will fix these.
[1] https://bugzilla.wikimedia.org/show_bug.cgi?id=45005
| Python | mit | pywikibot/core-migration-example | ---
+++
@@ -11,7 +11,7 @@
super(Family, self).__init__()
self.name = 'wikidata'
self.langs = {
- 'wikidata': 'wikidata.org',
+ 'wikidata': 'www.wikidata.org',
'repo': 'wikidata-test-repo.wikimedia.de',
'client': 'wikidata-test-client.wikimedia... |
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 | ---
+++
@@ -1,3 +1,6 @@
+# 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 |
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 | ---
+++
@@ -5,6 +5,7 @@
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"}'), |
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 | ---
+++
@@ -16,8 +16,6 @@
from django.conf.urls import include, url
from django.conf.urls.i18n import i18n_patterns
from django.contrib import admin
-from django.conf import settings
-from django.conf.urls.static import static
urlpatterns = i18n_patterns(
url(r'', include('general.urls', namespace='general... |
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 | ---
+++
@@ -1,14 +1,48 @@
-from coils import user_input
-from sqlalchemy import create_engine
+"""Add a timestamp."""
-username = user_input('Username', default='root')
-password = user_input('Password', password=True)
-dbname = user_input('Database name')
+from coils import user_input, Config
+from sqlalchemy impo... |
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 | ---
+++
@@ -25,13 +25,14 @@
# Check that we have the expected version of Django
-expected_version = (1, 7, 1)
+expected_version = '1.7.1'
+installed_version = django.get_version()
try:
- assert django.VERSION[:3] == expected_version
+ assert installed_version == expected_version
except AssertionError:
... |
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 | ---
+++
@@ -22,7 +22,7 @@
Cr = Cr2.reshape((1, w, h))
A = concatenate((Y, Cb, Cr))
img = toimage(A, mode="YCbCr", channel_axis=0)
-print img
+img.convert("RGB").save("frame.png")
from pylab import imshow, show
from matplotlib import cm |
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 | ---
+++
@@ -14,6 +14,6 @@
# under the License.
-from create_port import CreatePort # noqa
-from delete_ports import DeletePorts # noqa
-from show_network import ShowNetwork # noqa
+from os_tasklib.neutron.create_port import CreatePort # noqa
+from os_tasklib.neutron.delete_ports import DeletePorts # noqa
+f... |
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 | ---
+++
@@ -1,8 +1,11 @@
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')
+ config = ctx.config.load('users.yml')()
+ ... |
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 | ---
+++
@@ -12,8 +12,9 @@
return self.repeater_map[key]
class Repeater(object):
- def __init__(self, index=0, length=None):
+ def __init__(self, index=0, item=None, length=None):
self.index = index
+ self.item = item
self.length = length
@property
@@ -36,14 +37,22 @@
def last(self):
... |
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 | ---
+++
@@ -6,35 +6,46 @@
import unittest
class ZxSpecTestCase(unittest.TestCase):
- def setUp(self):
+
+ @classmethod
+ def setUpClass(self):
clean()
-
- def tearDown(self):
- clean()
+ self.output = run_zx_spec()
def test_zx_spec_header_displayed(self):
- ZX_SPEC... |
e8775f0f64bcae6b0789df6d4a2a5aca9f5cf4ac | telemetry/telemetry/internal/platform/power_monitor/msr_power_monitor_unittest.py | telemetry/telemetry/internal/platform/power_monitor/msr_power_monitor_unittest.py | # Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import logging
import time
import unittest
from telemetry import decorators
from telemetry.internal.platform.power_monitor import msr_power_monitor
from tel... | # Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import logging
import time
import unittest
from telemetry import decorators
from telemetry.internal.platform.power_monitor import msr_power_monitor
from tel... | Disable flaky MSR power monitor unit test. | [Telemetry] Disable flaky MSR power monitor unit test.
BUG=chromium:712486
Review-Url: https://codereview.chromium.org/2827723002
| Python | bsd-3-clause | catapult-project/catapult-csm,benschmaus/catapult,benschmaus/catapult,catapult-project/catapult,catapult-project/catapult,benschmaus/catapult,benschmaus/catapult,catapult-project/catapult-csm,catapult-project/catapult-csm,benschmaus/catapult,catapult-project/catapult-csm,catapult-project/catapult-csm,catapult-project/c... | ---
+++
@@ -12,7 +12,8 @@
class MsrPowerMonitorTest(unittest.TestCase):
- @decorators.Enabled('xp', 'win7', 'win8') # http://crbug.com/479337
+ @decorators.Disabled('all') # http://crbug.com/712486
+ #@decorators.Enabled('xp', 'win7', 'win8') # http://crbug.com/479337
def testMsrRuns(self):
platform... |
262cdf05ae4f53e1eab184e23791daa4d6422c51 | orges/optimizer/base.py | orges/optimizer/base.py | """
Abstract optimizer defining the API of optimizer implementations.
"""
from __future__ import division, print_function, with_statement
from abc import abstractmethod, ABCMeta # Abstract Base Class
class BaseOptimizer(object):
"""
Abstract optimizer, a systematic way to call a function with arguments.
... | """
This module provides an abstract base class for implementing optimizer
"""
from __future__ import division, print_function, with_statement
from abc import abstractmethod, ABCMeta # Abstract Base Class
class BaseOptimizer(object):
"""
Abstract base class for objects optimizing objective functions.
"... | Add documentation to BaseCaller and BaseOptimizer class | Add documentation to BaseCaller and BaseOptimizer class
| Python | bsd-3-clause | cigroup-ol/metaopt,cigroup-ol/metaopt,cigroup-ol/metaopt | ---
+++
@@ -1,6 +1,7 @@
"""
-Abstract optimizer defining the API of optimizer implementations.
+This module provides an abstract base class for implementing optimizer
"""
+
from __future__ import division, print_function, with_statement
from abc import abstractmethod, ABCMeta # Abstract Base Class
@@ -8,7 +9,7... |
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 | ---
+++
@@ -6,5 +6,8 @@
_link_slug = 'users'
_edit_attributes = ()
+ def avatar(self):
+ return User.http_get('{}/avatar'.format(self.id))[0]
+
LinkResolver.register(User)
LinkResolver.register(User, 'owner') |
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 | ---
+++
@@ -1,7 +1,28 @@
-"""Tests for plugin.py."""
-import ckanext.wirecloudview.plugin as plugin
+# -*- 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: y... |
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 | ---
+++
@@ -32,7 +32,7 @@
)
is_indian = forms.BooleanField(
initial = False,
- label=_("I hereby declare that I am an Indian"),
+ label=_("I declare that I am an Indian citizen"),
widget=forms.CheckboxInput(),
help_text=_("At this moment, we can accept donations from... |
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 | ---
+++
@@ -1,4 +1,8 @@
-# encoding: utf-8
+# -*- coding: utf-8 -*-
+
+__version__ = '2.0.0-dev'
+__description__ = 'Pagar.me Python library'
+__long_description__ = ''
from .pagarme import Pagarme
from .exceptions import * |
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 | ---
+++
@@ -1,3 +1,4 @@
+# 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:
@@ -8,7 +9,7 @@
# Examples:
# url(r'^$', 'gnome_developer_network.views.home', name='home'),
# url(r'^gno... |
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 | ---
+++
@@ -11,14 +11,37 @@
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
+"""Integration tests for calling tfc.run on script with keras."""
+import os
+import sys
+from unittest im... |
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 | ---
+++
@@ -16,8 +16,41 @@
fig = plt.figure()
return LivePlot(gs.PLOT_Y, scan.motor._name, fig=fig)
+# this changes the default plotter for *all* classes that
+# inherit from bluesky.simple_scans._StepScan
dscan.default_sub_factories['all'][1] = chx_plot_motor
gs.PLOTMODE = 1
-from bluesky.glob... |
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 | ---
+++
@@ -1,6 +1,7 @@
#!/usr/bin/python
import argparse
+import os
import struct
import sys
@@ -16,7 +17,7 @@
###################
### SUBROUTINES ###
###################
-def lenCpItem(tag):
+def lenCpStruct(tag):
if tag == 0xa:
return 3
else:
@@ -31,11 +32,21 @@
with open(args.path, "rb") ... |
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 | ---
+++
@@ -8,12 +8,14 @@
class PostAdminForm(forms.ModelForm):
+ multiupload_link = '/fileupload/image/'
class Meta:
model = Post
widgets = {'content': OppsEditor()}
class AlbumAdminForm(forms.ModelForm):
+ multiupload_link = '/fileupload/image/'
class Meta:
model... |
16bf1a3b096159604928cdcc99cab671347bb244 | contentstore/urls.py | contentstore/urls.py | from django.conf.urls import url, include
from rest_framework import routers
import views
router = routers.DefaultRouter()
router.register(r'schedule', views.ScheduleViewSet)
router.register(r'messageset', views.MessageSetViewSet)
router.register(r'message', views.MessageViewSet)
router.register(r'binarycontent', view... | from django.conf.urls import url, include
from rest_framework import routers
from . import views
router = routers.DefaultRouter()
router.register(r'schedule', views.ScheduleViewSet)
router.register(r'messageset', views.MessageSetViewSet)
router.register(r'message', views.MessageViewSet)
router.register(r'binarycontent... | Fix imports for py 3 | Fix imports for py 3
| Python | bsd-3-clause | praekelt/django-messaging-contentstore,praekelt/django-messaging-contentstore | ---
+++
@@ -1,6 +1,6 @@
from django.conf.urls import url, include
from rest_framework import routers
-import views
+from . import views
router = routers.DefaultRouter()
router.register(r'schedule', views.ScheduleViewSet) |
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 | ---
+++
@@ -27,8 +27,6 @@
from ._gateway import * # noqa
# noinspection PyUnresolvedReferences
from .exception import * # noqa
-# noinspection PyUnresolvedReferences
-from . import bin, simple, e2e, key, util # noqa
__author__ = 'Lennart Grahl <lennart.grahl@threema.ch>'
__status__ = 'Production'
@@ -37,7 +... |
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 | ---
+++
@@ -8,6 +8,7 @@
import archiver
import announcer
import flagger
+from config import Config
raven_client = RavenClient()
@@ -24,8 +25,12 @@
@sched.scheduled_job("cron", **schedule_kwargs)
def destalinate_job():
logging.info("Destalinating")
- if "SB_TOKEN" not in os.environ or "API_TOKEN" not... |
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 | ---
+++
@@ -1,13 +1,14 @@
-# Copyright (c) 2012-2020, Mark Peek <mark@peek.org>
+# 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: 18.7.0
+# Resource specific... |
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 | ---
+++
@@ -2,12 +2,10 @@
Tests for the file state
'''
# Import python libs
-import os
-#
+
# Import salt libs
-from saltunittest import TestLoader, TextTestRunner
import integration
-from integration import TestDaemon
+import tempfile
class CMDTest(integration.ModuleCase):
@@ -18,7 +16,8 @@
'''
... |
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 | ---
+++
@@ -4,14 +4,14 @@
class Graph(object):
"""A class for a simple graph data structure."""
def __init__(self):
- self.nodes = {}
+ self.graph = {}
def __repr__(self):
- pass
+ return repr(self.graph)
def nodes(self):
"""Return a list of all nodes in t... |
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 | ---
+++
@@ -3,9 +3,41 @@
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.imagelike import Solid
from mod... |
a26a57e44bbca6bbb5c7078c724552aaf5a6dda4 | takeyourmeds/utils/checks.py | takeyourmeds/utils/checks.py | import re
import os
from django.core import checks
from django.conf import settings
re_url = re.compile(r'\shref="(?P<url>/[^"]*)"')
@checks.register()
def hardcoded_urls(app_configs, **kwargs):
for x in settings.TEMPLATES:
for y in x['DIRS']:
for root, _, filenames in os.walk(y):
... | import re
import os
from django.core import checks
from django.conf import settings
re_url = re.compile(r'\shref="(?P<url>/[^"]*)"')
@checks.register()
def hardcoded_urls(app_configs, **kwargs):
for x in settings.TEMPLATES:
for y in x['DIRS']:
for root, _, filenames in os.walk(y):
... | Use repr so it's more obvious what the problem is | Use repr so it's more obvious what the problem is
| Python | mit | takeyourmeds/takeyourmeds-web,takeyourmeds/takeyourmeds-web,takeyourmeds/takeyourmeds-web,takeyourmeds/takeyourmeds-web | ---
+++
@@ -18,7 +18,7 @@
html = f.read()
for m in re_url.finditer(html):
- yield checks.Error("%s contains hardcoded URL %s" % (
+ yield checks.Error("%s contains hardcoded URL %r" % (
fullpath,... |
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 | ---
+++
@@ -1,5 +1,6 @@
import sys
import unittest
+from unittest.mock import patch
from asninja.parser import AtmelStudioProject
from asninja.toolchains.atmel_studio import *
@@ -11,13 +12,12 @@
self.assertEqual('arm-', tc.path)
self.assertEqual('arm', tc.tool_type)
- @unittest.skipUnles... |
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 | ---
+++
@@ -20,7 +20,5 @@
like = serialize_document(doc)
q = MoreLikeThis(like=like, fields=["title", "body"],)
query = LetterDocument.search().query(q)
- print(query.to_dict())
- x = query.execute()
- print(x)
- return x
+ # print(query.to_dict())
+ return query.execute() |
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 | ---
+++
@@ -9,6 +9,9 @@
for i in node.parent.parent['ids']:
self.sectnums[i]=node.parent.astext().replace(u'\xa0\xa0\xa0',' ')
+ def unknown_visit(self, node):
+ pass
+
class SectRefExpander(docutils.nodes.SparseNodeVisitor):
def __init__(self, document, sectnums):
doc... |
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... | ---
+++
@@ -8,6 +8,20 @@
from __future__ import absolute_import
# Monkeypatch pip.vendor.six into just six
+# This is kind of terrible, however it is the least bad of 3 bad options
+# #1 Ship pip with ``six`` such that it gets installed as a regular module
+# #2 Modify pip.vendor.html5lib so that instead of... |
29da3abba1a8ddb37bce77d1226faa371f3650b3 | docs/moosedocs.py | docs/moosedocs.py | #!/usr/bin/env python
import sys
import os
# Locate MOOSE directory
MOOSE_DIR = os.getenv('MOOSE_DIR', os.path.join(os.getcwd(), 'moose'))
if not os.path.exists(MOOSE_DIR):
MOOSE_DIR = os.path.join(os.getenv('HOME'), 'projects', 'moose')
if not os.path.exists(MOOSE_DIR):
raise Exception('Failed to locate MOOSE... | #!/usr/bin/env python
import sys
import os
# Locate MOOSE directory
MOOSE_DIR = os.getenv('MOOSE_DIR', os.path.join(os.getcwd(), 'moose'))
if not os.path.exists(MOOSE_DIR):
MOOSE_DIR = os.path.join(os.getenv('HOME'), 'projects', 'moose')
if not os.path.exists(MOOSE_DIR):
raise Exception('Failed to locate MOOSE, sp... | Correct spacing in docs python | Correct spacing in docs python
(refs #6699)
| Python | lgpl-2.1 | jessecarterMOOSE/moose,liuwenf/moose,yipenggao/moose,lindsayad/moose,idaholab/moose,yipenggao/moose,bwspenc/moose,YaqiWang/moose,joshua-cogliati-inl/moose,Chuban/moose,yipenggao/moose,bwspenc/moose,sapitts/moose,SudiptaBiswas/moose,SudiptaBiswas/moose,friedmud/moose,stimpsonsg/moose,Chuban/moose,lindsayad/moose,idahola... | ---
+++
@@ -5,16 +5,16 @@
# Locate MOOSE directory
MOOSE_DIR = os.getenv('MOOSE_DIR', os.path.join(os.getcwd(), 'moose'))
if not os.path.exists(MOOSE_DIR):
- MOOSE_DIR = os.path.join(os.getenv('HOME'), 'projects', 'moose')
+ MOOSE_DIR = os.path.join(os.getenv('HOME'), 'projects', 'moose')
if not os.path.exist... |
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 | ---
+++
@@ -2,6 +2,7 @@
import sys
import os
+from os.path import join, realpath, dirname
from Scripts.common import get_ini_conf, write_ini_conf
@@ -11,7 +12,8 @@
if sys.version_info.major > 2:
raw_input = input
- config = get_ini_conf("config.ini")
+ config_file = join(dirname(realpat... |
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... | ---
+++
@@ -2,10 +2,11 @@
import os
from app import create_app
-from flask.ext.script import Manager
+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__... |
5f6c55d8399c63893b8e5b4a432349e14cd5331d | thefuck/specific/archlinux.py | thefuck/specific/archlinux.py | """ This file provide some utility functions for Arch Linux specific rules."""
import subprocess
from .. import utils
@utils.memoize
def get_pkgfile(command):
""" Gets the packages that provide the given command using `pkgfile`.
If the command is of the form `sudo foo`, searches for the `foo` command
ins... | """ This file provide some utility functions for Arch Linux specific rules."""
import subprocess
from .. import utils
@utils.memoize
def get_pkgfile(command):
""" Gets the packages that provide the given command using `pkgfile`.
If the command is of the form `sudo foo`, searches for the `foo` command
ins... | Fix issue with attempting to scroll through options when not-found package has no packages with matching names causing crash. | Fix issue with attempting to scroll through options when not-found package has no packages with matching names causing crash.
| Python | mit | nvbn/thefuck,mlk/thefuck,SimenB/thefuck,Clpsplug/thefuck,scorphus/thefuck,nvbn/thefuck,scorphus/thefuck,Clpsplug/thefuck,mlk/thefuck,SimenB/thefuck | ---
+++
@@ -25,7 +25,7 @@
return [package.split()[0] for package in packages]
except subprocess.CalledProcessError:
- return None
+ return []
def archlinux_env(): |
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 | ---
+++
@@ -1,5 +1,6 @@
# -*- coding: utf-8 -*-
import requests
+from functools import partial
class HttpClient(object):
@@ -21,6 +22,7 @@
del headers['Transfer-Encoding']
if headers.get('Content-Length'):
kwargs['data'] = body.read(int(headers['Content-Length']))
+ kw... |
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 | ---
+++
@@ -7,11 +7,12 @@
class Challenges(db.Model):
__tablename__= 'challenges'
- #Data variables for each Challenges
- chalid=db.Column(db.String(32), primary_key=True,unique=True,nullable=False)
+ #Data variables for each challenge
+ chall_id=db.Column(db.String(32), primary_key=True,unique=Tr... |
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 | ---
+++
@@ -1,19 +1,4 @@
-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
-... |
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 | ---
+++
@@ -1,13 +1,13 @@
+import os
+
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.pat... |
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 | ---
+++
@@ -25,8 +25,8 @@
dates = list(raw_data.keys())
-sleep_trace = go.Scatter(x=dates, y=sleep_durations, name='Sleep Duration')
-nap_trace = go.Scatter(x=dates, y=nap_durations, name='Nap Duration')
+sleep_trace = go.Scatter(x=dates, y=sleep_durations, name='Sleep Duration', mode='lines+markers')
+nap_trace... |
b594c8fd213989e52b08f7bab7f4bf53b8772f3a | filer/__init__.py | filer/__init__.py | #-*- coding: utf-8 -*-
# version string following pep-0396 and pep-0386
__version__ = '0.9pbs.23' # pragma: nocover
| #-*- coding: utf-8 -*-
# version string following pep-0396 and pep-0386
__version__ = '0.9pbs.24' # pragma: nocover
| Bump version as instructed by bamboo. | Bump version as instructed by bamboo. | Python | bsd-3-clause | pbs/django-filer,pbs/django-filer,pbs/django-filer,pbs/django-filer,pbs/django-filer | ---
+++
@@ -1,3 +1,3 @@
#-*- coding: utf-8 -*-
# version string following pep-0396 and pep-0386
-__version__ = '0.9pbs.23' # pragma: nocover
+__version__ = '0.9pbs.24' # pragma: nocover |
7dd683be3df9d8e6ad9c67baa19dbaf5663bdd64 | pwnableapp/__init__.py | pwnableapp/__init__.py | import logging
import flask
import sys
class Flask(flask.Flask):
def __init__(self, *args, **kwargs):
super(Flask, self).__init__(*args, **kwargs)
# Set error handlers
self.register_error_handler(500, self.internal_error_handler)
for error in (400, 403, 404):
self.register_error_handler(error,... | import logging
import flask
import os
import sys
class Flask(flask.Flask):
def __init__(self, *args, **kwargs):
super(Flask, self).__init__(*args, **kwargs)
# Set error handlers
self.register_error_handler(500, self.internal_error_handler)
for error in (400, 403, 404):
self.register_error_hand... | Set umask before starting logging. | Set umask before starting logging.
| Python | apache-2.0 | Matir/pwnableweb,Matir/pwnableweb,Matir/pwnableweb,Matir/pwnableweb | ---
+++
@@ -1,5 +1,6 @@
import logging
import flask
+import os
import sys
class Flask(flask.Flask):
@@ -14,12 +15,15 @@
def init_logging(self):
"""Must be called after config setup."""
if not self.debug:
+ old_umask = os.umask(0077)
handler = logging.FileHandler(
self.config.... |
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 | ---
+++
@@ -8,6 +8,7 @@
'|'.join(name2codepoint.keys())))
def recodeText(text):
+ """Parses things like & and ὔ into real characters."""
def _entToUnichr(match):
ent = match.group(1)
try: |
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 | ---
+++
@@ -15,5 +15,19 @@
super(ApiException, self).__init__()
self.status_code = status_code
+ def __repr__(self):
+ return u'{0}({1}, {2}, {3})'.format(
+ self.__class__.__name__,
+ self.message,
+ self.status_code,
+ self._body,
+ )
+
+ def __str__(self):
+ return 'Api... |
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 | ---
+++
@@ -2,17 +2,23 @@
import sqlite3
-import Config
+from ebroker.Config import Config
+
+
+def getDb(config_file = None):
+ return SQLiteDb(config_file)
+
class Db(object):
__metaclass__ = abc.ABCMeta
- def __init__(self):
- self._connection = self.connect()
+ def __init__(self, ... |
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... | ---
+++
@@ -10,9 +10,16 @@
# GUI imports
from ginga.qtw.QtHelp import QtGui, QtCore
from ginga.qtw import QtHelp
+from ginga.toolkit import toolkit
import matplotlib
-from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
+if toolkit == 'qt4':
+ from matplotlib.backends.backend_qt4a... |
b35b8935b8f7f429e93c2989add837cc3a1bf1ef | releases/models.py | releases/models.py | from docutils import nodes
# Issue type list (keys) + color values
ISSUE_TYPES = {
'bug': 'A04040',
'feature': '40A056',
'support': '4070A0',
}
class Issue(nodes.Element):
@property
def type(self):
return self['type_']
@property
def backported(self):
return self.get('bac... | from docutils import nodes
# Issue type list (keys) + color values
ISSUE_TYPES = {
'bug': 'A04040',
'feature': '40A056',
'support': '4070A0',
}
class Issue(nodes.Element):
@property
def type(self):
return self['type_']
@property
def backported(self):
return self.get('bac... | Add Python 2.6 fix for model reprs. | Add Python 2.6 fix for model reprs.
| Python | bsd-2-clause | bitprophet/releases | ---
+++
@@ -39,8 +39,9 @@
elif self.line:
flag = self.line + '+'
if flag:
- flag = ' ({})'.format(flag)
- return '<{issue.type} #{issue.number}{flag}>'.format(issue=self, flag=flag)
+ flag = ' ({0})'.format(flag)
+ return '<{issue.type} #{issue.number... |
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 | ---
+++
@@ -11,24 +11,30 @@
# Still working on this...numbers are not properly summing to N yet
# Getting proper number of divisions but whole thing is yet to come together
+
def SimLogNorm(N, S, sample_size):
for i in range(sample_size):
sample = []
- RAC = [N*.75,N*.25]
+ ... |
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 | ---
+++
@@ -1,8 +1,8 @@
__all__ = ['long']
-if hasattr(__builtins__, 'long'):
- long = long
+if 'long' in __builtins__:
+ long = __builtins__['long']
else:
class long(int):
pass |
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 | ---
+++
@@ -1,5 +1,6 @@
#!/usr/bin/python
+from datetime import datetime
import os
import sqlite3
import sys
@@ -12,7 +13,8 @@
print('\nLast keys:')
query = 'SELECT * FROM client ORDER by reset DESC'
for client in db.execute(query):
- print(u'{0}: "{2}" {3}'.format(*client).encode('utf8'))... |
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 | ---
+++
@@ -7,6 +7,10 @@
def __unicode__(self):
return self.name
+ @staticmethod
+ def with_artists():
+ return Country.objects.annotate(number_of_artists=models.Count('artist')).filter(number_of_artists__gte=1)
+
class Artist(models.Model):
name = models.TextField()
mbid = mod... |
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 | ---
+++
@@ -17,9 +17,10 @@
def is_introspection_field(info: ResolveInfo):
- for path in info.path:
- if isinstance(path, str) and path.startswith("__"):
- return True
+ if info.path is not None:
+ for path in info.path:
+ if isinstance(path, str) and path.startswith("__"... |
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 | ---
+++
@@ -25,6 +25,5 @@
# Below for testing locally only
if __name__ == '__main__':
from wsgiref.simple_server import make_server
- httpd = make_server('localhost', 8051, application)
- # Wait for a single request, serve it and quit.
+ httpd = make_server('0.0.0.0', 8051, application)
httpd.ser... |
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 | ---
+++
@@ -1,3 +1,5 @@
+import copy
+
import pkg_resources
from rwt import deps
@@ -30,7 +32,7 @@
'not_a_package',
'rwt==0.0',
]
- expected = args.copy()
+ expected = copy.copy(args)
expected.remove('rwt')
filtered = deps.not_installed(args)
assert list(filtered) == expected |
0e26572466bbee071adb62cdb716e5d377774166 | src/zeit/content/volume/browser/admin.py | src/zeit/content/volume/browser/admin.py | # -*- coding: utf-8 -*-
from zeit.solr import query
import zeit.content.article.article
import zeit.content.infobox.infobox
import zeit.cms.admin.browser.admin
class VolumeAdminForm(zeit.cms.admin.browser.admin.EditFormCI):
"""
Admin View with the publish button.
Check out the normal Admin View.
/zei... | # -*- coding: utf-8 -*-
from zeit.solr import query
import zeit.content.article.article
import zeit.content.infobox.infobox
import zeit.cms.admin.browser.admin
import zope.formlib.form as form
class VolumeAdminForm(zeit.cms.admin.browser.admin.EditFormCI):
"""
Admin View with the publish button.
Check ou... | Add additional Form action for publish | Add additional Form action for publish
| Python | bsd-3-clause | ZeitOnline/zeit.content.volume,ZeitOnline/zeit.content.volume | ---
+++
@@ -3,6 +3,7 @@
import zeit.content.article.article
import zeit.content.infobox.infobox
import zeit.cms.admin.browser.admin
+import zope.formlib.form as form
class VolumeAdminForm(zeit.cms.admin.browser.admin.EditFormCI):
@@ -13,19 +14,33 @@
/zeit.cms/src/zeit/cms/admin/browser/admin.py.
"""... |
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 | ---
+++
@@ -5,16 +5,4 @@
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__username', 'user__email', 'last_name', 'first_name',)
-
- def get... |
febd9213aaa5cc65dbe724cf12f93cda9444f163 | mysite/search/tasks/__init__.py | mysite/search/tasks/__init__.py | from datetime import timedelta
from mysite.search.models import Project
from celery.task import PeriodicTask
from celery.registry import tasks
from mysite.search.launchpad_crawl import grab_lp_bugs, lpproj2ohproj
from mysite.search import controllers
import mysite.customs.miro
class GrabLaunchpadBugs(PeriodicTask):
... | from datetime import timedelta
from mysite.search.models import Project
from celery.task import PeriodicTask
from celery.registry import tasks
from mysite.search.launchpad_crawl import grab_lp_bugs, lpproj2ohproj
from mysite.search import controllers
import mysite.customs.miro
class GrabLaunchpadBugs(PeriodicTask):
... | Stop manually specifying name of task. | Stop manually specifying name of task.
| Python | agpl-3.0 | vipul-sharma20/oh-mainline,Changaco/oh-mainline,mzdaniel/oh-mainline,ojengwa/oh-mainline,jledbetter/openhatch,mzdaniel/oh-mainline,eeshangarg/oh-mainline,openhatch/oh-mainline,openhatch/oh-mainline,campbe13/openhatch,ehashman/oh-mainline,heeraj123/oh-mainline,nirmeshk/oh-mainline,campbe13/openhatch,SnappleCap/oh-mainli... | ---
+++
@@ -7,7 +7,6 @@
import mysite.customs.miro
class GrabLaunchpadBugs(PeriodicTask):
- name = "search.GrabLaunchpadBugs"
run_every = timedelta(days=1)
def run(self, **kwargs):
logger = self.get_logger(**kwargs)
@@ -20,7 +19,6 @@
class GrabMiroBugs(PeriodicTask):
- name = "search... |
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 | ---
+++
@@ -2,4 +2,9 @@
class AddressBook(object):
- pass
+
+ def __init__(self):
+ self.persons = []
+
+ def add_person(self, person):
+ self.persons.append(person) |
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 | ---
+++
@@ -3,6 +3,7 @@
for managing outputters.
'''
+# Import salt utils
import salt.loader
def display_output(data, out, opts=None): |
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 | ---
+++
@@ -16,23 +16,24 @@
:rtype: string
'''
- from_str = argline=='-s'
+ from_str = argline == '-s'
if not from_str and argline:
raise SaltRenderError(
- 'Unknown renderer option: {opt}'.format(opt=argline)
- )
- tmp_data = salt.utils.templates.JINJA... |
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 | ---
+++
@@ -1,17 +1,14 @@
-import os
-from typing import Optional, List
+from typing import Type, Union
-from jobs.base.job import Job
+from .kubernetes_session import api_instance, KubernetesSession
+from .subprocess_session import SubprocessSession
-# If on a K8s cluster then use the K8s-based sessions
+# If on... |
2acca2ea2ae2dc86d4b09ce21c88d578bbea6ea3 | setup.py | setup.py | #!/usr/bin/env python
from setuptools import setup, find_packages
__about__ = {}
with open("warehouse/__about__.py") as fp:
exec(fp, None, __about__)
setup(
name=__about__["__title__"],
version=__about__["__version__"],
description=__about__["__summary__"],
long_description=open("README.rst").re... | #!/usr/bin/env python
from setuptools import setup, find_packages
__about__ = {}
with open("warehouse/__about__.py") as fp:
exec(fp, None, __about__)
setup(
name=__about__["__title__"],
version=__about__["__version__"],
description=__about__["__summary__"],
long_description=open("README.rst").re... | Remove no longer needed package_data | Remove no longer needed package_data
| Python | bsd-2-clause | davidfischer/warehouse | ---
+++
@@ -39,7 +39,6 @@
packages=find_packages(exclude=["tests"]),
package_data={
- "": ["LICENSE"],
"warehouse": [
"simple/templates/*.html",
"synchronize/*.crt", |
e0883db2bfe5b32bdd73f44a9288fa8483bca08c | setup.py | setup.py | import versioneer
from setuptools import setup, find_packages
setup(
name='domain-event-broker',
version=versioneer.get_version(),
cmdclass=versioneer.get_cmdclass(),
description='Send and receive domain events via RabbitMQ',
author='Ableton AG',
author_email='webteam@ableton.com',
url='ht... | import versioneer
from setuptools import setup, find_packages
# Add README as description
from os import path
this_directory = path.abspath(path.dirname(__file__))
with open(path.join(this_directory, 'README.md'), encoding='utf-8') as f:
long_description = f.read()
setup(
name='domain-event-broker',
vers... | Add project description for PyPI | Add project description for PyPI
| Python | mit | AbletonAG/domain-events | ---
+++
@@ -1,12 +1,20 @@
import versioneer
from setuptools import setup, find_packages
+
+# Add README as description
+from os import path
+this_directory = path.abspath(path.dirname(__file__))
+with open(path.join(this_directory, 'README.md'), encoding='utf-8') as f:
+ long_description = f.read()
setup(
... |
316a17402aca8ca99a90f151de7535a1033b3e24 | tests/network/__init__.py | tests/network/__init__.py | from . file_transfer import * # NOQA
#from . node import * # NOQA
from . message import * # NOQA
from . file_handshake import * # NOQA
from . queued_file_transfer import * # NOQA
from . process_transfers import * # NOQA
from . bandwidth_test import * # NOQA
if __name__ == "__main__":
unittest.main()
| from . file_transfer import * # NOQA
from . node import * # NOQA
from . message import * # NOQA
from . file_handshake import * # NOQA
from . queued_file_transfer import * # NOQA
from . process_transfers import * # NOQA
from . bandwidth_test import * # NOQA
if __name__ == "__main__":
unittest.main()
| Fix pep8. Renable all tests. | Fix pep8. Renable all tests.
| Python | mit | Storj/storjnode | ---
+++
@@ -1,5 +1,5 @@
from . file_transfer import * # NOQA
-#from . node import * # NOQA
+from . node import * # NOQA
from . message import * # NOQA
from . file_handshake import * # NOQA
from . queued_file_transfer import * # NOQA |
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 | ---
+++
@@ -15,9 +15,10 @@
ran_migration = Signal(providing_args=["app","migration","method"])
# Compatibility code for django.contrib.auth
-if 'django.contrib.auth' in settings.INSTALLED_APPS:
- def create_permissions_compat(app, **kwargs):
- from django.db.models import get_app
- from django.co... |
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 | ---
+++
@@ -31,6 +31,8 @@
'is_mobile': not 'generic_web_browser' in device_parents[device.devid],
'brand_name': device.brand_name,
'model_name': device.model_name,
+ 'ua': ua,
+ 'matched_ua': device.devua,
}
if request.GET.get('capabilit... |
57eaefa2f85522b7b9e596779df3d5dc2763e295 | backend/rbac.py | backend/rbac.py | import urllib
from flask import request, redirect, abort
from flask.ext.security import current_user
class RBACMixin(object):
""" Role-based access control for views. """
# if False, we don't require authentication at all
require_authentication = True
# user must have all of these roles
required_... | import urllib
from flask import request, redirect, abort
from flask.ext.security import current_user
class RBACMixin(object):
""" Role-based access control for views. """
# if False, we don't require authentication at all
require_authentication = True
# user must have all of these roles
required_... | Include GET parameters in Admin login redirect. | Include GET parameters in Admin login redirect.
| Python | apache-2.0 | Code4SA/pmg-cms-2,Code4SA/pmg-cms-2,Code4SA/pmg-cms-2 | ---
+++
@@ -33,5 +33,5 @@
abort(403)
else:
# login
- tmp = '/security/login?next=' + urllib.quote_plus(request.base_url)
+ tmp = '/security/login?next=' + urllib.quote_plus(request.url)
return redirect(tmp) |
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 | ---
+++
@@ -8,6 +8,9 @@
def __init__(self):
BaseModelsResource.__init__(self, CustomAction)
+ def check_permissions(self):
+ return True
+
class CustomActionResource(BaseModelResource):
|
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 | ---
+++
@@ -23,20 +23,27 @@
def __init__(self, constant):
super(ConstantDict, self).__init__()
self.constant = constant
+ self.deleted_keys = set()
+
+ def update(self, E=None, **F):
+ super(ConstantDict, self).update(E, **F)
+
+ if type(E) is type(self):
+ se... |
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 | ---
+++
@@ -23,6 +23,10 @@
encoded = self.machine.cipher('AAAAA')
self.assertEqual('BDZGO', encoded)
+ def test_decode_message(self):
+ decoded = self.machine.cipher('BDZGO')
+ self.assertEqual('AAAAA', decoded)
+
def run_tests():
runner = unittest.TextTestRunner() |
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 | ---
+++
@@ -1 +1,73 @@
-# 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
... |
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 | ---
+++
@@ -11,4 +11,5 @@
# remove the database file
os.system('rm ~/*.db -rf')
+os.system('rm /etc/swift/*.db -rf')
|
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 | ---
+++
@@ -2,10 +2,10 @@
import numpy as np
-from py_bh_tsne import _TSNE as TSNE
+from fasttsne import _TSNE as TSNE
-def fast_tsne(data, pca_d=50, d=2, perplexity=30., theta=0.5):
+def fast_tsne(data, pca_d=None, d=2, perplexity=30., theta=0.5):
"""
Run Barnes-Hut T-SNE on _data_.
@@ -26,15 +2... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.