commit
stringlengths
40
40
old_file
stringlengths
4
236
new_file
stringlengths
4
236
old_contents
stringlengths
1
3.26k
new_contents
stringlengths
16
4.43k
subject
stringlengths
16
624
message
stringlengths
17
3.29k
lang
stringclasses
5 values
license
stringclasses
13 values
repos
stringlengths
5
91.5k
2aa415cae1cb7ed0bb2b7fdaf51d9d5eaceaa768
sweettooth/extensions/admin.py
sweettooth/extensions/admin.py
from django.contrib import admin from extensions.models import Extension, ExtensionVersion from extensions.models import STATUS_ACTIVE, STATUS_REJECTED from review.models import CodeReview class CodeReviewAdmin(admin.TabularInline): model = CodeReview fields = 'reviewer', 'comments', class ExtensionVersionA...
from django.contrib import admin from extensions.models import Extension, ExtensionVersion from extensions.models import STATUS_ACTIVE, STATUS_REJECTED from review.models import CodeReview class CodeReviewAdmin(admin.TabularInline): model = CodeReview fields = 'reviewer', 'comments', class ExtensionVersionA...
Make the user field into a raw field
extensions: Make the user field into a raw field It's a bit annoying having to navigate through a 20,000 line combobox.
Python
agpl-3.0
GNOME/extensions-web,GNOME/extensions-web,GNOME/extensions-web,GNOME/extensions-web,magcius/sweettooth,magcius/sweettooth
f1e50c1caeeec5b8e443f634534bfed46f26dbdf
2017/async-socket-server/simple-client.py
2017/async-socket-server/simple-client.py
import sys, time import socket def make_new_connection(name, host, port): sockobj = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sockobj.connect((host, port)) sockobj.send(b'foo^1234$jo') sockobj.send(b'sdfsdfsdfsdf^a') sockobj.send(b'fkfkf0000$dfk^$sdf^a$^kk$') buf = b'' while True...
import sys, time import socket import threading class ReadThread(threading.Thread): def __init__(self, sockobj): super().__init__() self.sockobj = sockobj self.bufsize = 8 * 1024 def run(self): while True: buf = self.sockobj.recv(self.bufsize) print('Re...
Modify client to read the socket concurrently
Modify client to read the socket concurrently
Python
unlicense
eliben/code-for-blog,eliben/code-for-blog,eliben/code-for-blog,eliben/code-for-blog,eliben/code-for-blog,eliben/code-for-blog,eliben/code-for-blog,eliben/code-for-blog,eliben/code-for-blog,eliben/code-for-blog,eliben/code-for-blog
c17dc4a9876ac45b88307d2ab741655bae6c5dc7
inboxen/tests/settings.py
inboxen/tests/settings.py
from __future__ import absolute_import import os os.environ['INBOX_TESTING'] = '1' os.environ["INBOXEN_ADMIN_ACCESS"] = '1' from settings import * CACHES = { "default": { "BACKEND": "django.core.cache.backends.locmem.LocMemCache" } } db = os.environ.get('DB') SECRET_KEY = "This is a test, you don't ...
from __future__ import absolute_import import os os.environ['INBOX_TESTING'] = '1' os.environ["INBOXEN_ADMIN_ACCESS"] = '1' from settings import * CACHES = { "default": { "BACKEND": "django.core.cache.backends.locmem.LocMemCache" } } db = os.environ.get('DB') postgres_user = os.environ.get('PG_USER',...
Allow setting of postgres user via an environment variable
Allow setting of postgres user via an environment variable Touch #73
Python
agpl-3.0
Inboxen/Inboxen,Inboxen/Inboxen,Inboxen/Inboxen,Inboxen/Inboxen
aecc14ea11cae2bb27ee2534a229e7af8453053e
readthedocs/rtd_tests/tests/test_hacks.py
readthedocs/rtd_tests/tests/test_hacks.py
from django.test import TestCase from readthedocs.core import hacks class TestHacks(TestCase): fixtures = ['eric.json', 'test_data.json'] def setUp(self): hacks.patch_meta_path() def tearDown(self): hacks.unpatch_meta_path() def test_hack_failed_import(self): import boogy ...
from django.test import TestCase from core import hacks class TestHacks(TestCase): fixtures = ['eric.json', 'test_data.json'] def setUp(self): hacks.patch_meta_path() def tearDown(self): hacks.unpatch_meta_path() def test_hack_failed_import(self): import boogy self.as...
Fix import to not include project.
Fix import to not include project.
Python
mit
agjohnson/readthedocs.org,pombredanne/readthedocs.org,wijerasa/readthedocs.org,atsuyim/readthedocs.org,CedarLogic/readthedocs.org,safwanrahman/readthedocs.org,nyergler/pythonslides,sunnyzwh/readthedocs.org,raven47git/readthedocs.org,CedarLogic/readthedocs.org,michaelmcandrew/readthedocs.org,fujita-shintaro/readthedocs....
ada4e94fb4b6de1303d4c4ad47d239bbf0699f3e
dev_settings.py
dev_settings.py
""" This is a home for shared dev settings. Feel free to add anything that all devs should have set. Add `from dev_settings import *` to the top of your localsettings file to use. You can then override or append to any of these settings there. """ import os LOCAL_APPS = ( 'django_extensions', ) ####### Django E...
""" This is a home for shared dev settings. Feel free to add anything that all devs should have set. Add `from dev_settings import *` to the top of your localsettings file to use. You can then override or append to any of these settings there. """ import os LOCAL_APPS = ( 'django_extensions', ) ####### Django E...
Add dummy cache setting so code can be loaded
Add dummy cache setting so code can be loaded I mimic what will happen on ReadTheDocs locally by doing the following: * Don't start my hq environment (no couch, pillowtop, redis, etc) * Enter my hq virtualenv * Move or rename `localsettings.py` so it won't be found * `$ cd docs/` * `$ make html` Basically it ne...
Python
bsd-3-clause
qedsoftware/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,qedsoftware/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,qedsoftware/commcare-hq,qedsoftware/commcare-hq,qedsoftware/commcare-hq
09f1a21fd3a59e31468470e0f5de7eec7c8f3507
ynr/apps/popolo/serializers.py
ynr/apps/popolo/serializers.py
from rest_framework import serializers from popolo import models as popolo_models from parties.serializers import MinimalPartySerializer class MinimalPostSerializer(serializers.ModelSerializer): class Meta: model = popolo_models.Post fields = ("id", "label", "slug") id = serializers.ReadOnly...
from rest_framework import serializers from popolo import models as popolo_models from parties.serializers import MinimalPartySerializer class MinimalPostSerializer(serializers.ModelSerializer): class Meta: model = popolo_models.Post fields = ("id", "label", "slug") id = serializers.ReadOnly...
Remove membership internal ID and change person to name
Remove membership internal ID and change person to name
Python
agpl-3.0
DemocracyClub/yournextrepresentative,DemocracyClub/yournextrepresentative,DemocracyClub/yournextrepresentative
b1106407aa9695d0ca007b53af593e25e9bb1769
saleor/plugins/migrations/0004_drop_support_for_env_vatlayer_access_key.py
saleor/plugins/migrations/0004_drop_support_for_env_vatlayer_access_key.py
from django.db import migrations def assign_access_key(apps, schema): vatlayer_configuration = ( apps.get_model("plugins", "PluginConfiguration") .objects.filter(identifier="mirumee.taxes.vatlayer") .first() ) if vatlayer_configuration: vatlayer_configuration.active = Fals...
from django.db import migrations def deactivate_vatlayer(apps, schema): vatlayer_configuration = ( apps.get_model("plugins", "PluginConfiguration") .objects.filter(identifier="mirumee.taxes.vatlayer") .first() ) if vatlayer_configuration: vatlayer_configuration.active = Fa...
Change migration name to more proper
Change migration name to more proper
Python
bsd-3-clause
mociepka/saleor,mociepka/saleor,mociepka/saleor
e0c926667a32031b5d43ec1701fe7577282176ca
rest_flex_fields/utils.py
rest_flex_fields/utils.py
def is_expanded(request, key): """ Examines request object to return boolean of whether passed field is expanded. """ expand = request.query_params.get("expand", "") expand_fields = [] for e in expand.split(","): expand_fields.extend([e for e in e.split(".")]) return "~all" in ...
try: # Python 3 from collections.abc import Iterable string_types = (str,) except ImportError: # Python 2 from collections import Iterable string_types = (str, unicode) def is_expanded(request, key): """ Examines request object to return boolean of whether passed field is expanded....
Handle other iterable types gracefully in split_level utility function
Handle other iterable types gracefully in split_level utility function
Python
mit
rsinger86/drf-flex-fields
defb736895d5f58133b9632c85d8064669ee897a
blueLed.py
blueLed.py
''' Dr Who Box: Blue Effects LED ''' from __future__ import print_function import RPi.GPIO as GPIO import time from multiprocessing import Process import math # Define PINS LED = 18 # Use numbering based on P1 header GPIO.setmode(GPIO.BOARD) GPIO.setwarnings(False) GPIO.setup(LED, GPIO.OUT, GPIO.LOW) def pulsate...
''' Dr Who Box: Blue Effects LED ''' from __future__ import print_function import RPi.GPIO as GPIO import time from multiprocessing import Process import math # Define PINS LED = 18 # Use numbering based on P1 header GPIO.setmode(GPIO.BOARD) GPIO.setwarnings(False) GPIO.setup(LED, GPIO.OUT, GPIO.LOW) def pulsate...
Tidy up and apply PEP8 guidelines.
Tidy up and apply PEP8 guidelines.
Python
mit
davidb24v/drwho
b68e609b746af6211a85493246242ba00a26f306
bin/hand_test_lib_main.py
bin/hand_test_lib_main.py
#!/usr/bin/env python import csv import sys from gwaith import get_rates, processors only = ('PLN', 'GBP') for data in get_rates(processor=processors.to_json, only=only): print(data) for data in get_rates(processor=processors.raw, only=only): print(data) for data in get_rates(processor=processors.raw_pytho...
#!/usr/bin/env python import csv import sys from gwaith import get_rates, processors only = ('PLN', 'GBP') def header(msg): print('=' * 80 + '\r\t\t\t ' + msg + ' ') header('to_json') for data in get_rates(processor=processors.to_json, only=only): print(data) header('raw') for data in get_rates(processor...
Improve output of the manual testing command adding headers
Improve output of the manual testing command adding headers
Python
mit
bartekbrak/gwaith,bartekbrak/gwaith,bartekbrak/gwaith
0498e1575f59880b4f7667f0d99bfbd993f2fcd5
profiles/backends.py
profiles/backends.py
from django.contrib.auth import get_user_model from django.contrib.auth.backends import ModelBackend class CaseInsensitiveModelBackend(ModelBackend): def authenticate(email=None, password=None, **kwargs): """ Created by LNguyen( Date: 14Dec2017 Description: Method to handle backen...
from django.contrib.auth import get_user_model from django.contrib.auth.backends import ModelBackend class CaseInsensitiveModelBackend(ModelBackend): def authenticate(email=None, password=None, **kwargs): """ Created by LNguyen( Date: 14Dec2017 Description: Method to handle backen...
Fix issues with changing passwords
Fix issues with changing passwords
Python
mit
gdit-cnd/RAPID,LindaTNguyen/RAPID,LindaTNguyen/RAPID,gdit-cnd/RAPID,gdit-cnd/RAPID,gdit-cnd/RAPID,gdit-cnd/RAPID,LindaTNguyen/RAPID,LindaTNguyen/RAPID,LindaTNguyen/RAPID
fc830b0caf29fe1424bc8fe30afcf7e21d8ecd72
inbound.py
inbound.py
import logging, email, yaml from django.utils import simplejson as json from google.appengine.ext import webapp, deferred from google.appengine.ext.webapp.mail_handlers import InboundMailHandler from google.appengine.api.urlfetch import fetch settings = yaml.load(open('settings.yaml')) def callback(raw): result = {...
import logging, email, yaml from django.utils import simplejson as json from google.appengine.ext import webapp, deferred from google.appengine.ext.webapp.mail_handlers import InboundMailHandler from google.appengine.api.urlfetch import fetch from google.appengine.api.urlfetch import Error as FetchError settings = yam...
Raise if response is not 200
Raise if response is not 200
Python
mit
maccman/remail-engine
47ea7ebce827727bef5ad49e5df84fa0e5f6e4b9
pycloudflare/services.py
pycloudflare/services.py
from itertools import count from demands import HTTPServiceClient from yoconfig import get_config class CloudFlareService(HTTPServiceClient): def __init__(self, **kwargs): config = get_config('cloudflare') headers = { 'Content-Type': 'application/json', 'X-Auth-Key': confi...
from itertools import count from demands import HTTPServiceClient from yoconfig import get_config class CloudFlareService(HTTPServiceClient): def __init__(self, **kwargs): config = get_config('cloudflare') headers = { 'Content-Type': 'application/json', 'X-Auth-Key': confi...
Use an iterator to get pages
Use an iterator to get pages
Python
mit
gnowxilef/pycloudflare,yola/pycloudflare
c496be720461722ce482c981b4915365dd0df8ab
events/views.py
events/views.py
from django.contrib import messages from django.contrib.auth.decorators import login_required from django.views.generic.list import ListView from django.views.generic.detail import DetailView from base.util import class_view_decorator from base.views import RedirectBackView from .models import Event, EventUserRegistr...
from django.contrib import messages from django.contrib.auth.decorators import login_required from django.utils.translation import ugettext_lazy as _ from django.views.generic.list import ListView from django.views.generic.detail import DetailView from base.util import class_view_decorator from base.views import Redir...
Raise error when user is registering to the event multiple times
events: Raise error when user is registering to the event multiple times
Python
mit
matus-stehlik/roots,rtrembecky/roots,tbabej/roots,rtrembecky/roots,matus-stehlik/roots,rtrembecky/roots,tbabej/roots,tbabej/roots,matus-stehlik/roots
3fe4f1788d82719eac70ffe0fbbbae4dbe85f00b
evexml/forms.py
evexml/forms.py
from django import forms from django.forms.fields import IntegerField, CharField import evelink.account class AddAPIForm(forms.Form): key_id = IntegerField() v_code = CharField(max_length=64, min_length=1) def clean(self): self._clean() return super(AddAPIForm, self).clean() def _cl...
from django import forms from django.forms.fields import IntegerField, CharField import evelink.account class AddAPIForm(forms.Form): key_id = IntegerField() v_code = CharField(max_length=64, min_length=1) def clean(self): self._clean() return super(AddAPIForm, self).clean() def _cl...
Implement checks to pass tests
Implement checks to pass tests
Python
mit
randomic/aniauth-tdd,randomic/aniauth-tdd
f31ab02d9a409e31acf339db2b950216472b8e9e
salesforce/backend/operations.py
salesforce/backend/operations.py
# django-salesforce # # by Phil Christensen # (c) 2012-2013 Freelancers Union (http://www.freelancersunion.org) # See LICENSE.md for details # import re from django.db.backends import BaseDatabaseOperations """ Default database operations, with unquoted names. """ class DatabaseOperations(BaseDatabaseOperations): ...
# django-salesforce # # by Phil Christensen # (c) 2012-2013 Freelancers Union (http://www.freelancersunion.org) # See LICENSE.md for details # import re from django.db.backends import BaseDatabaseOperations """ Default database operations, with unquoted names. """ class DatabaseOperations(BaseDatabaseOperations): ...
Fix bug with Date fields and SOQL.
Fix bug with Date fields and SOQL. Fixes https://github.com/freelancersunion/django-salesforce/issues/10
Python
mit
django-salesforce/django-salesforce,chromakey/django-salesforce,philchristensen/django-salesforce,hynekcer/django-salesforce,chromakey/django-salesforce,hynekcer/django-salesforce,hynekcer/django-salesforce,chromakey/django-salesforce,django-salesforce/django-salesforce,philchristensen/django-salesforce,django-salesfor...
805e86c0cd69f49863d2ca4c37e094a344d79c64
lib/jasy/core/MetaData.py
lib/jasy/core/MetaData.py
# # Jasy - JavaScript Tooling Refined # Copyright 2010 Sebastian Werner # class MetaData: """ Data structure to hold all dependency information Hint: Must be a clean data class without links to other systems for optiomal cachability using Pickle """ def __init__(self, tree): se...
# # Jasy - JavaScript Tooling Refined # Copyright 2010 Sebastian Werner # class MetaData: """ Data structure to hold all dependency information Hint: Must be a clean data class without links to other systems for optiomal cachability using Pickle """ __slots__ = ["provides", "requires",...
Make use of slots to reduce in-memory size
Make use of slots to reduce in-memory size
Python
mit
zynga/jasy,zynga/jasy,sebastian-software/jasy,sebastian-software/jasy
c73de73aca304d347e9faffa77eab417cec0b4b5
app/util.py
app/util.py
# Various utility functions import os SHOULD_CACHE = os.environ['ENV'] == 'production' def cached_function(func): data = {} def wrapper(*args): if not SHOULD_CACHE: return func(*args) cache_key = ' '.join([str(x) for x in args]) if cache_key not in data: data...
# Various utility functions import os SHOULD_CACHE = os.environ['ENV'] == 'production' def cached_function(func): data = {} def wrapper(*args): if not SHOULD_CACHE: return func(*args) cache_key = ' '.join([str(x) for x in args]) if cache_key not in data: data...
Make cached_function not modify function name
Make cached_function not modify function name
Python
mit
albertyw/albertyw.com,albertyw/albertyw.com,albertyw/albertyw.com,albertyw/albertyw.com,albertyw/albertyw.com
267a7cb5c3947697df341cb25f962da1fa791805
cubex/calltree.py
cubex/calltree.py
class CallTree(object): def __init__(self, node): self.call_id = node.get('id') self.region_id = node.get('calleeId') self.children = [] self.metrics = {} #cube.cindex[int(node.get('id'))] = self #for child_node in node.findall('cnode'): # child_tree = ...
class CallTree(object): def __init__(self, node): self.call_id = int(node.get('id')) self.region_id = int(node.get('calleeId')) self.children = [] self.metrics = {} #cube.cindex[int(node.get('id'))] = self #for child_node in node.findall('cnode'): # chi...
Save call tree indices as integers
Save call tree indices as integers
Python
apache-2.0
marshallward/cubex
29f727f5391bb3fc40270b58a798f146cc202a3d
modules/pipeurlbuilder.py
modules/pipeurlbuilder.py
# pipeurlbuilder.py # import urllib from pipe2py import util def pipe_urlbuilder(context, _INPUT, conf, **kwargs): """This source builds a url and yields it forever. Keyword arguments: context -- pipeline context _INPUT -- not used conf: BASE -- base PATH -- path elements ...
# pipeurlbuilder.py # import urllib from pipe2py import util def pipe_urlbuilder(context, _INPUT, conf, **kwargs): """This source builds a url and yields it forever. Keyword arguments: context -- pipeline context _INPUT -- not used conf: BASE -- base PATH -- path elements ...
Handle single param definition (following Yahoo! changes)
Handle single param definition (following Yahoo! changes)
Python
mit
nerevu/riko,nerevu/riko
d5229fcae9481ff6666eeb076825f4ddd3929b02
asyncio/__init__.py
asyncio/__init__.py
"""The asyncio package, tracking PEP 3156.""" import sys # The selectors module is in the stdlib in Python 3.4 but not in 3.3. # Do this first, so the other submodules can use "from . import selectors". # Prefer asyncio/selectors.py over the stdlib one, as ours may be newer. try: from . import selectors except Im...
"""The asyncio package, tracking PEP 3156.""" import sys # The selectors module is in the stdlib in Python 3.4 but not in 3.3. # Do this first, so the other submodules can use "from . import selectors". # Prefer asyncio/selectors.py over the stdlib one, as ours may be newer. try: from . import selectors except Im...
Fix asyncio.__all__: export also unix_events and windows_events symbols
Fix asyncio.__all__: export also unix_events and windows_events symbols For example, on Windows, it was not possible to get ProactorEventLoop or DefaultEventLoopPolicy using "from asyncio import *".
Python
apache-2.0
overcastcloud/trollius,overcastcloud/trollius,overcastcloud/trollius
e642716c0815c989b994d436921b0fb1a4f3dfa1
djangae/checks.py
djangae/checks.py
import os from django.core import checks from google.appengine.tools.devappserver2.application_configuration import ModuleConfiguration from djangae.environment import get_application_root def check_deferred_builtin(app_configs=None, **kwargs): """ Check that the deferred builtin is switched off, as it'll o...
import os from django.core import checks from djangae.environment import get_application_root def check_deferred_builtin(app_configs=None, **kwargs): """ Check that the deferred builtin is switched off, as it'll override Djangae's deferred handler """ from google.appengine.tools.devappserver2.applic...
Move import that depends on devserver
Move import that depends on devserver
Python
bsd-3-clause
potatolondon/djangae,grzes/djangae,potatolondon/djangae,grzes/djangae,grzes/djangae
6eb8ad49e25039ad61470e30e42c8ab352ab9b1c
sep/sep_search_result.py
sep/sep_search_result.py
from lxml import html import re import requests from constants import SEP_URL class SEPSearchResult(): query = None results = None def __init__(self, query): self.set_query(query) def set_query(self, query): pattern = re.compile('[^a-zA-Z\d\s]') stripped_query = re.sub(patte...
from lxml import html import re import requests from constants import SEP_URL class SEPSearchResult(): query = None results = None def __init__(self, query): self.set_query(query) def set_query(self, query): pattern = re.compile('[^a-zA-Z\d\s]') stripped_query = re.sub(patte...
Print SEP urls for debug
New: Print SEP urls for debug
Python
mit
AFFogarty/SEP-Bot,AFFogarty/SEP-Bot
7fdbe50d113a78fd02101056b56d44d917c5571c
joins/models.py
joins/models.py
from django.db import models # Create your models here. class Join(models.Model): email = models.EmailField() ip_address = models.CharField(max_length=120, default='ABC') timestamp = models.DateTimeField(auto_now_add = True, auto_now=False) updated = models.DateTimeField(auto_now_add = False, auto_now=True) def...
from django.db import models # Create your models here. class Join(models.Model): email = models.EmailField() ip_address = models.CharField(max_length=120, default='ABC') timestamp = models.DateTimeField(auto_now_add = True, auto_now=False) updated = models.DateTimeField(auto_now_add = False, auto_now=True) def...
Add South Guide, made message for it
Add South Guide, made message for it
Python
mit
codingforentrepreneurs/launch-with-code,codingforentrepreneurs/launch-with-code,krishnazure/launch-with-code,krishnazure/launch-with-code,krishnazure/launch-with-code
e43ea9602c272119f18e270a0ee138401ee0b02a
digit_guesser.py
digit_guesser.py
import matplotlib.pyplot as plt from sklearn import datasets from sklearn import svm digits = datasets.load_digits() clf = svm.SVC(gamma=0.0001, C=100) training_set = digits.data[:-10] labels = digits.target[:-10] x, y = training_set, labels clf.fit(x, y) for i in range(10): print("Prediction: {}".format(clf....
from sklearn import datasets from sklearn import svm digits = datasets.load_digits() clf = svm.SVC(gamma=0.0001, C=100) training_set = digits.data[:-10] training_labels = digits.target[:-10] testing_set = digits.data[-10:] testing_labels = digits.target[-10:] x, y = training_set, training_labels clf.fit(x, y) for...
Make variables self descriptive and create a testing set.
Make variables self descriptive and create a testing set.
Python
mit
jeancsil/machine-learning
86b889049ef1ee1c896e4ab44185fc54ef87a2c0
IPython/consoleapp.py
IPython/consoleapp.py
""" Shim to maintain backwards compatibility with old IPython.consoleapp imports. """ # Copyright (c) IPython Development Team. # Distributed under the terms of the Modified BSD License. from warnings import warn warn("The `IPython.consoleapp` package has been deprecated. " "You should import from jupyter_client...
""" Shim to maintain backwards compatibility with old IPython.consoleapp imports. """ # Copyright (c) IPython Development Team. # Distributed under the terms of the Modified BSD License. from warnings import warn warn("The `IPython.consoleapp` package has been deprecated since IPython 4.0." "You should import fr...
Remove Deprecation Warning, add since when things were deprecated.
Remove Deprecation Warning, add since when things were deprecated.
Python
bsd-3-clause
ipython/ipython,ipython/ipython
c974a2fe075accdf58148fceb3f722b144e0b8d8
diylang/types.py
diylang/types.py
# -*- coding: utf-8 -*- """ This module holds some types we'll have use for along the way. It's your job to implement the Closure and Environment types. The DiyLangError class you can have for free :) """ class DiyLangError(Exception): """General DIY Lang error class.""" pass class Closure: def __ini...
# -*- coding: utf-8 -*- """ This module holds some types we'll have use for along the way. It's your job to implement the Closure and Environment types. The DiyLangError class you can have for free :) """ class DiyLangError(Exception): """General DIY Lang error class.""" pass class Closure(object): d...
Fix Old-style class, subclass object explicitly.
Fix Old-style class, subclass object explicitly.
Python
bsd-3-clause
kvalle/diy-lisp,kvalle/diy-lisp,kvalle/diy-lang,kvalle/diy-lang
87d4e604ef72fbe0513c725a7fdf0d421e633257
changes/api/project_index.py
changes/api/project_index.py
from __future__ import absolute_import, division, unicode_literals from sqlalchemy.orm import joinedload from changes.api.base import APIView from changes.constants import Status from changes.models import Project, Build class ProjectIndexAPIView(APIView): def get(self): queryset = Project.query.order_b...
from __future__ import absolute_import, division, unicode_literals from sqlalchemy.orm import joinedload from changes.api.base import APIView from changes.constants import Status from changes.models import Project, Build class ProjectIndexAPIView(APIView): def get(self): queryset = Project.query.order_b...
Remove numActiveBuilds as its unused
Remove numActiveBuilds as its unused
Python
apache-2.0
dropbox/changes,wfxiang08/changes,bowlofstew/changes,bowlofstew/changes,bowlofstew/changes,bowlofstew/changes,wfxiang08/changes,dropbox/changes,dropbox/changes,dropbox/changes,wfxiang08/changes,wfxiang08/changes
194e6a34744963e2a7b17b846ee2913e6e01ae11
pyblish_starter/plugins/validate_rig_members.py
pyblish_starter/plugins/validate_rig_members.py
import pyblish.api class ValidateStarterRigFormat(pyblish.api.InstancePlugin): """A rig must have a certain hierarchy and members - Must reside within `rig_GRP` transform - controls_SEL - cache_SEL - resources_SEL (optional) """ label = "Rig Format" order = pyblish.api.ValidatorOrde...
import pyblish.api class ValidateStarterRigFormat(pyblish.api.InstancePlugin): """A rig must have a certain hierarchy and members - Must reside within `rig_GRP` transform - out_SEL - controls_SEL - in_SEL (optional) - resources_SEL (optional) """ label = "Rig Format" order = pyb...
Update interface for rigs - in/out versus None/cache
Update interface for rigs - in/out versus None/cache
Python
mit
pyblish/pyblish-starter,pyblish/pyblish-mindbender,mindbender-studio/core,MoonShineVFX/core,getavalon/core,MoonShineVFX/core,mindbender-studio/core,getavalon/core
42c76c83e76439e5d8377bed2f159cfe988f05b1
src/icalendar/__init__.py
src/icalendar/__init__.py
from icalendar.cal import ( Calendar, Event, Todo, Journal, Timezone, TimezoneStandard, TimezoneDaylight, FreeBusy, Alarm, ComponentFactory, ) # Property Data Value Types from icalendar.prop import ( vBinary, vBoolean, vCalAddress, vDatetime, vDate, vDDDTy...
from icalendar.cal import ( Calendar, Event, Todo, Journal, Timezone, TimezoneStandard, TimezoneDaylight, FreeBusy, Alarm, ComponentFactory, ) # Property Data Value Types from icalendar.prop import ( vBinary, vBoolean, vCalAddress, vDatetime, vDate, vDDDTy...
Remove incorrect use of __all__
Remove incorrect use of __all__
Python
bsd-2-clause
untitaker/icalendar,nylas/icalendar,geier/icalendar
59cd76a166a46756977440f46b858efa276c0aa0
fireplace/cards/utils.py
fireplace/cards/utils.py
import random import fireplace.cards from ..actions import * from ..enums import CardType, GameTag, Race, Rarity, Zone from ..targeting import * def hand(func): """ @hand helper decorator The decorated event listener will only listen while in the HAND Zone """ func.zone = Zone.HAND return func drawCard = lambd...
import random import fireplace.cards from ..actions import * from ..enums import CardType, GameTag, Race, Rarity, Zone from ..targeting import * def hand(func): """ @hand helper decorator The decorated event listener will only listen while in the HAND Zone """ func.zone = Zone.HAND return func drawCard = lambd...
Implement a RandomCard helper for definitions
Implement a RandomCard helper for definitions
Python
agpl-3.0
jleclanche/fireplace,Meerkov/fireplace,amw2104/fireplace,NightKev/fireplace,oftc-ftw/fireplace,butozerca/fireplace,liujimj/fireplace,liujimj/fireplace,Meerkov/fireplace,smallnamespace/fireplace,Ragowit/fireplace,amw2104/fireplace,oftc-ftw/fireplace,beheh/fireplace,smallnamespace/fireplace,butozerca/fireplace,Ragowit/fi...
a0d10e419b504dc2e7f4ba45a5d10a2d9d47019c
knights/base.py
knights/base.py
import ast from . import parse class Template: def __init__(self, raw): self.raw = raw self.root = parse.parse(raw) code = ast.Expression( body=ast.ListComp( elt=ast.Call( func=ast.Name(id='str', ctx=ast.Load()), args=[...
import ast from . import parse class Template: def __init__(self, raw): self.raw = raw self.nodelist = parse.parse(raw) code = ast.Expression( body=ast.GeneratorExp( elt=ast.Call( func=ast.Name(id='str', ctx=ast.Load()), ...
Use a generator for rendering, and pass nodelist unwrapped
Use a generator for rendering, and pass nodelist unwrapped
Python
mit
funkybob/knights-templater,funkybob/knights-templater
16811d4f379974fb94c98b56b398a4d555e3e4cd
jasy/item/Doc.py
jasy/item/Doc.py
# # Jasy - Web Tooling Framework # Copyright 2010-2012 Zynga Inc. # Copyright 2013-2014 Sebastian Werner # import os import jasy.js.api.Data as Data import jasy.core.Text as Text import jasy.item.Abstract as Abstract from jasy import UserError class DocItem(Abstract.AbstractItem): kind = "doc" def generat...
# # Jasy - Web Tooling Framework # Copyright 2010-2012 Zynga Inc. # Copyright 2013-2014 Sebastian Werner # import os import jasy.js.api.Data as Data import jasy.core.Text as Text import jasy.item.Abstract as Abstract from jasy import UserError class DocItem(Abstract.AbstractItem): kind = "doc" def generat...
Fix ID generation for js package documentation
Fix ID generation for js package documentation
Python
mit
sebastian-software/jasy,sebastian-software/jasy
6593645ace6efdc0e7b79dbdf5a5b5f76396c693
cli/cli.py
cli/cli.py
import argparse parser = argparse.ArgumentParser(prog='moocx', description='EdX MOOC Data Anaylysis') parser.add_argument('-v', '--version', action='version', version='0.1.0') parser.parse_args()
import argparse parser = argparse.ArgumentParser(prog='moocx', description='EdX MOOC Data Anaylysis') parser.add_argument('-v', '--version', action='version', version='0.1.0') subparsers = parser.add_subparsers(help='commands') # A list command list_parser = subparsers.add_parser('list', help='List commands') list_p...
Add commands for listing available analytics commadns
Add commands for listing available analytics commadns
Python
mit
McGillX/edx_data_research,McGillX/edx_data_research,McGillX/edx_data_research
808413e56eb14568eae98791581c0f5870f46cd2
example/config.py
example/config.py
# pyinfra # File: pyinfra/example/config.py # Desc: entirely optional config file for the CLI deploy # see: pyinfra/api/config.py for defaults from pyinfra import hook, local # These can be here or in deploy.py TIMEOUT = 5 FAIL_PERCENT = 81 # Add hooks to be triggered throughout the deploy - separate to the ...
# pyinfra # File: pyinfra/example/config.py # Desc: entirely optional config file for the CLI deploy # see: pyinfra/api/config.py for defaults from pyinfra import hook # These can be here or in deploy.py TIMEOUT = 5 FAIL_PERCENT = 81 # Add hooks to be triggered throughout the deploy - separate to the operati...
Make it possible to run examples on any branch!
Make it possible to run examples on any branch!
Python
mit
Fizzadar/pyinfra,Fizzadar/pyinfra
e8bb04f0084e0c722c21fc9c5950cb1b5370dd22
Tools/scripts/byteyears.py
Tools/scripts/byteyears.py
#! /usr/local/python # byteyears file ... # # Print a number representing the product of age and size of each file, # in suitable units. import sys, posix, time from stat import * secs_per_year = 365.0 * 24.0 * 3600.0 now = time.time() status = 0 for file in sys.argv[1:]: try: st = posix.stat(file) except posix...
#! /usr/local/python # Print the product of age and size of each file, in suitable units. # # Usage: byteyears [ -a | -m | -c ] file ... # # Options -[amc] select atime, mtime (default) or ctime as age. import sys, posix, time import string from stat import * # Use lstat() to stat files if it exists, else stat() try...
Add options -amc; do lstat if possible; columnize properly.
Add options -amc; do lstat if possible; columnize properly.
Python
mit
sk-/python2.7-type-annotator,sk-/python2.7-type-annotator,sk-/python2.7-type-annotator
298dc9be1d9e85e79cdbaa95ef9cab1986fe87a7
saleor/product/migrations/0026_auto_20170102_0927.py
saleor/product/migrations/0026_auto_20170102_0927.py
# -*- coding: utf-8 -*- # Generated by Django 1.10.3 on 2017-01-02 15:27 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('product', '0025_auto_20161219_0517'), ] operations = [ migrations.CreateMod...
# -*- coding: utf-8 -*- # Generated by Django 1.10.3 on 2017-01-02 15:27 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('product', '0025_auto_20161219_0517'), ] operations = [ migrations.CreateMod...
Remove unrelated thing from migration
Remove unrelated thing from migration
Python
bsd-3-clause
UITools/saleor,mociepka/saleor,mociepka/saleor,mociepka/saleor,UITools/saleor,UITools/saleor,maferelo/saleor,UITools/saleor,maferelo/saleor,UITools/saleor,maferelo/saleor
3d42553ae6acd452e122a1a89851e4693a89abde
build.py
build.py
import os from flask.ext.frozen import Freezer import webassets from content import app, assets bundle_files = [] for bundle in assets: assert isinstance(bundle, webassets.Bundle) print("Building bundle {}".format(bundle.output)) bundle.build(force=True, disable_cache=True) bundle_files.append(bundle...
import os from flask.ext.frozen import Freezer import webassets from content import app, assets bundle_files = [] for bundle in assets: assert isinstance(bundle, webassets.Bundle) print("Building bundle {}".format(bundle.output)) bundle.build(force=True, disable_cache=True) bundle_files.append(bundle...
Add workaround for frozen-flask generating static pages for dynamic api pages like /oauth/.
Add workaround for frozen-flask generating static pages for dynamic api pages like /oauth/.
Python
apache-2.0
daboross/dabo.guru,daboross/dabo.guru,daboross/dabo.guru,daboross/dabo.guru
c1a4e9c83aa20ad333c4d6a1c9e53a732540ea39
jump_to_file.py
jump_to_file.py
import sublime import sublime_plugin import os class JumpToFile(sublime_plugin.TextCommand): def run(self, edit = None): view = self.view for region in view.sel(): if view.score_selector(region.begin(), "parameter.url, string.quoted"): # The scope includes the quote char...
import sublime import sublime_plugin import os class JumpToFile(sublime_plugin.TextCommand): def _try_open(self, try_file, path=None): if path: try_file = os.path.join(path, try_file) if not os.path.isfile(try_file): try_file += '.rb' if os.path.isfile(try_file): ...
Add support for paths relative to project folders
Add support for paths relative to project folders
Python
mit
russelldavis/sublimerc
a1b47d442290ea9ce19e25cd03c1aa5e39ad2ec5
scikits/learn/tests/test_pca.py
scikits/learn/tests/test_pca.py
from nose.tools import assert_equals from .. import datasets from ..pca import PCA iris = datasets.load_iris() X = iris.data def test_pca(): """ PCA """ pca = PCA(k=2) X_r = pca.fit(X).transform(X) assert_equals(X_r.shape[1], 2) pca = PCA() pca.fit(X) assert_equals(pca.explaine...
import numpy as np from .. import datasets from ..pca import PCA iris = datasets.load_iris() X = iris.data def test_pca(): """ PCA """ pca = PCA(k=2) X_r = pca.fit(X).transform(X) np.testing.assert_equal(X_r.shape[1], 2) pca = PCA() pca.fit(X) np.testing.assert_almost_equal(pca...
Fix tests to be moroe robust
BUG: Fix tests to be moroe robust
Python
bsd-3-clause
nvoron23/scikit-learn,B3AU/waveTree,sumspr/scikit-learn,frank-tancf/scikit-learn,madjelan/scikit-learn,mattilyra/scikit-learn,xzh86/scikit-learn,mwv/scikit-learn,yunfeilu/scikit-learn,JsNoNo/scikit-learn,scikit-learn/scikit-learn,Fireblend/scikit-learn,btabibian/scikit-learn,davidgbe/scikit-learn,arabenjamin/scikit-lea...
aeec346bf49f9f297802a4c6c50cf28de20a70f8
examples/load.py
examples/load.py
# coding: utf-8 import os import requests ROOT = os.path.dirname(os.path.realpath(__file__)) ENDPOINT = os.environ.get('ES_ENDPOINT_EXTERNAL', 'localhost:9200') INDEX = 'gsiCrawler' eid = 0 with open(os.path.join(ROOT, 'blogPosting.txt'), 'r') as f: for line in f: url = 'http://{}/{}/{}/{}'.format(ENDP...
# coding: utf-8 import os import requests ROOT = os.path.dirname(os.path.realpath(__file__)) ENDPOINT = os.environ.get('ES_ENDPOINT_EXTERNAL', 'localhost:9200') INDEX = 'gsiCrawler' eid = 0 with open(os.path.join(ROOT, 'blogPosting.txt'), 'r') as f: for line in f: url = 'http://{}/{}/{}/{}'.format(ENDP...
Add content-type to requests in example
Add content-type to requests in example
Python
apache-2.0
gsi-upm/gsicrawler,gsi-upm/gsicrawler,gsi-upm/gsicrawler,gsi-upm/gsicrawler
4ca6d139139a08151f7cdf89993ded3440287a4a
keyform/urls.py
keyform/urls.py
from django.conf.urls import url, include from django.contrib import admin from django.contrib.auth.views import login, logout_then_login from keyform import views urlpatterns = [ url(r'^$', views.HomeView.as_view(), name='home'), url(r'^contact$', views.ContactView.as_view(), name='contact'), url(r'^edit-...
from django.conf.urls import url, include from django.contrib import admin from django.views.generic import RedirectView from django.contrib.auth.views import login, logout_then_login from keyform import views urlpatterns = [ url(r'^$', views.HomeView.as_view(), name='home'), url(r'^table.php$', RedirectView.a...
Add redirect for old hotlinks
Add redirect for old hotlinks
Python
mit
mostateresnet/keyformproject,mostateresnet/keyformproject,mostateresnet/keyformproject
1f1c8eed6a60945a404aa0efd6169687431c87d5
exec_thread_1.py
exec_thread_1.py
import spam #Convert the LTA file to the UVFITS format spam.convert_lta_to_uvfits('Name of the file') spam.precalibrate_targets('Name of UVFITS output file') spam.process_target()
import spam #Convert the LTA file to the UVFITS format #Generates UVFITS file with same basename as LTA file spam.convert_lta_to_uvfits('Name of the file') #Take generated UVFITS file as input and precalibrate targets #Generates files (RRLL with the name of the source (can be obtained using ltahdr) spam.precalibrate...
Add pipeline flow (in comments) to thread template
Add pipeline flow (in comments) to thread template
Python
mit
NCRA-TIFR/gadpu,NCRA-TIFR/gadpu
89a0edf7e5e00de68615574b2044f593e0339f2e
jsonrpc/views.py
jsonrpc/views.py
from _json import dumps from django.http import HttpResponse from django.shortcuts import render_to_response from jsonrpc.site import jsonrpc_site from jsonrpc import mochikit def browse(request): if (request.GET.get('f', None) == 'mochikit.js'): return HttpResponse(mochikit.mochikit, content_type='application/x...
from _json import dumps from django.http import HttpResponse from django.shortcuts import render_to_response from jsonrpc.site import jsonrpc_site from jsonrpc import mochikit def browse(request, site=jsonrpc_site): if (request.GET.get('f', None) == 'mochikit.js'): return HttpResponse(mochikit.mochikit, content_...
Make browse work with non-default sites
Make browse work with non-default sites
Python
mit
palfrey/django-json-rpc
b0916a35dc0049105acb3b2b62a579353e57d33a
erpnext/accounts/doctype/bank/bank_dashboard.py
erpnext/accounts/doctype/bank/bank_dashboard.py
from __future__ import unicode_literals from frappe import _ def get_data(): return { 'fieldname': 'bank', 'transactions': [ { 'label': _('Bank Deatils'), 'items': ['Bank Account', 'Bank Guarantee'] }, { 'items': ['Payment Order'] } ] }
from __future__ import unicode_literals from frappe import _ def get_data(): return { 'fieldname': 'bank', 'transactions': [ { 'label': _('Bank Deatils'), 'items': ['Bank Account', 'Bank Guarantee'] } ] }
Remove payment order from bank dashboard
fix: Remove payment order from bank dashboard
Python
agpl-3.0
gsnbng/erpnext,gsnbng/erpnext,gsnbng/erpnext,gsnbng/erpnext
bf66f0f267b6bca16241ed4920199dfa4128bd5c
social_core/backends/surveymonkey.py
social_core/backends/surveymonkey.py
""" SurveyMonkey OAuth2 backend, docs at: https://developer.surveymonkey.com/api/v3/#authentication """ from .oauth import BaseOAuth2 class SurveyMonkeyOAuth2(BaseOAuth2): """SurveyMonkey OAuth2 authentication backend""" name = 'surveymonkey' AUTHORIZATION_URL = 'https://api.surveymonkey.com/oauth/aut...
""" SurveyMonkey OAuth2 backend, docs at: https://developer.surveymonkey.com/api/v3/#authentication """ from .oauth import BaseOAuth2 class SurveyMonkeyOAuth2(BaseOAuth2): """SurveyMonkey OAuth2 authentication backend""" name = 'surveymonkey' AUTHORIZATION_URL = 'https://api.surveymonkey.com/oauth/aut...
Disable the STATE parameter - it doesn't play nice with the SurveyMonkey App Directory links
Disable the STATE parameter - it doesn't play nice with the SurveyMonkey App Directory links
Python
bsd-3-clause
python-social-auth/social-core,python-social-auth/social-core
49602d0abfe93a0c98f55d932e7b86ddf2a59d38
connect.py
connect.py
import ConfigParser import threading import time import chatbot def runbot(t): config = ConfigParser.ConfigParser() config.readfp(open('./config.ini')) ws = chatbot.Chatbot(config.get('Chatbot', 'server'), protocols=['http-only', 'chat']) try: ws.connect() ws...
import ConfigParser import threading import time import chatbot def runbot(t): config = ConfigParser.ConfigParser() config.readfp(open('./config.ini')) ws = chatbot.Chatbot(config.get('Chatbot', 'server'), protocols=['http-only', 'chat']) try: ws.connect() ws...
Add sleep before new Chatbot instance is created on crash
Add sleep before new Chatbot instance is created on crash
Python
mit
ScottehMax/pyMon,ScottehMax/pyMon,lc-guy/pyMon,lc-guy/pyMon
ee81f71d7c6b311ee760b42ca5c9b7e80f44a8d7
src/pip/_internal/metadata/importlib/_compat.py
src/pip/_internal/metadata/importlib/_compat.py
import importlib.metadata from typing import Optional, Protocol class BasePath(Protocol): """A protocol that various path objects conform. This exists because importlib.metadata uses both ``pathlib.Path`` and ``zipfile.Path``, and we need a common base for type hints (Union does not work well since `...
import importlib.metadata from typing import Any, Optional, Protocol, cast class BasePath(Protocol): """A protocol that various path objects conform. This exists because importlib.metadata uses both ``pathlib.Path`` and ``zipfile.Path``, and we need a common base for type hints (Union does not work w...
Make version hack more reliable
Make version hack more reliable
Python
mit
pradyunsg/pip,pypa/pip,pradyunsg/pip,pypa/pip,sbidoul/pip,sbidoul/pip,pfmoore/pip,pfmoore/pip
2625b539a05156fe3baea1ebf195d242740b599d
osfclient/models/storage.py
osfclient/models/storage.py
from .core import OSFCore from .file import File class Storage(OSFCore): def _update_attributes(self, storage): if not storage: return # XXX does this happen? if 'data' in storage: storage = storage['data'] self.id = self._get_attribute(storage, 'id') ...
from .core import OSFCore from .file import File class Storage(OSFCore): def _update_attributes(self, storage): if not storage: return # XXX does this happen? if 'data' in storage: storage = storage['data'] self.id = self._get_attribute(storage, 'id') ...
Refactor key to access files from a folder's JSON
Refactor key to access files from a folder's JSON
Python
bsd-3-clause
betatim/osf-cli,betatim/osf-cli
173b4f39433aa27970955173e63f99f58cfeecb1
custom/enikshay/urls.py
custom/enikshay/urls.py
from django.conf.urls import patterns, include urlpatterns = patterns( 'custom.enikshay.integrations.ninetyninedots.views', (r'^99dots/', include("custom.enikshay.integrations.ninetyninedots.urls")), )
from django.conf.urls import patterns, include urlpatterns = patterns( '', (r'^99dots/', include("custom.enikshay.integrations.ninetyninedots.urls")), )
Remove reference to wrong view
Remove reference to wrong view
Python
bsd-3-clause
dimagi/commcare-hq,qedsoftware/commcare-hq,qedsoftware/commcare-hq,qedsoftware/commcare-hq,dimagi/commcare-hq,qedsoftware/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,qedsoftware/commcare-hq
5bc2ce310cfb13b966b022573255c0042fc03791
application/page/models.py
application/page/models.py
import datetime from sqlalchemy import desc from application import db class Page(db.Model): __tablename__ = 'page' id = db.Column(db.Integer, primary_key=True) path = db.Column(db.String(256), unique=True) revisions = db.relationship('PageRevision', backref='page', lazy='dynamic') def __init__(self, path): ...
import datetime from sqlalchemy import desc from application import db class Page(db.Model): __tablename__ = 'page' id = db.Column(db.Integer, primary_key=True) path = db.Column(db.String(256), unique=True) revisions = db.relationship('PageRevision', backref='page', lazy='dynamic') def __init__(self, path): ...
Fix navigition links a bit again
Fix navigition links a bit again
Python
mit
viaict/viaduct,viaict/viaduct,viaict/viaduct,viaict/viaduct,viaict/viaduct
0f5fcca49bc22b8a481ba86e9421757ac373a932
bin/example_game_programmatic.py
bin/example_game_programmatic.py
from vengeance.game import Direction from vengeance.game import Game from vengeance.game import Location go_up = Direction('up') go_down = Direction('down') go_up.opposite = go_down go_in = Direction('in') go_out = Direction('out') go_in.opposite = go_out go_west = Direction('west') go_east = Direction('east') go_we...
from vengeance.game import Direction from vengeance.game import Game from vengeance.game import Location go_up = Direction('up') go_down = Direction('down') go_up.opposite = go_down go_in = Direction('in') go_out = Direction('out') go_in.opposite = go_out go_west = Direction('west') go_east = Direction('east') go_we...
Add use of Game.character.current_location to example
Add use of Game.character.current_location to example
Python
unlicense
mmurdoch/Vengeance,mmurdoch/Vengeance
ceebd0b345fe7221577bfcfe18632267897871e8
test/helpers/xnat_test_helper.py
test/helpers/xnat_test_helper.py
import os, re from base64 import b64encode as encode from qipipe.staging import airc_collection as airc from qipipe.staging.staging_helper import SUBJECT_FMT from qipipe.helpers import xnat_helper import logging logger = logging.getLogger(__name__) def generate_subject_name(name): """ Makes a subject name tha...
import os, re from base64 import b64encode as encode from qipipe.staging import airc_collection as airc from qipipe.staging.staging_helper import SUBJECT_FMT from qipipe.helpers import xnat_helper import logging logger = logging.getLogger(__name__) def generate_subject_name(name): """ Makes a subject name tha...
Move get_subjects and delete_subjects to qipipe helpers.
Move get_subjects and delete_subjects to qipipe helpers.
Python
bsd-2-clause
ohsu-qin/qipipe
457cbeaa66fa504442c1303bec4df25e83ee35c3
froide/document/models.py
froide/document/models.py
from django.db import models from filingcabinet.models import ( AbstractDocument, AbstractDocumentCollection, ) class Document(AbstractDocument): original = models.ForeignKey( 'foirequest.FoiAttachment', null=True, blank=True, on_delete=models.SET_NULL, related_name='original_document' ...
from django.db import models from filingcabinet.models import ( AbstractDocument, AbstractDocumentCollection, ) class Document(AbstractDocument): original = models.ForeignKey( 'foirequest.FoiAttachment', null=True, blank=True, on_delete=models.SET_NULL, related_name='original_document' ...
Add get_serializer_class to document model
Add get_serializer_class to document model
Python
mit
fin/froide,stefanw/froide,stefanw/froide,fin/froide,fin/froide,fin/froide,stefanw/froide,stefanw/froide,stefanw/froide
da0dc08d8fdd18a64ecc883404553c86de6a726c
test/functional/feature_shutdown.py
test/functional/feature_shutdown.py
#!/usr/bin/env python3 # Copyright (c) 2018 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test bitcoind shutdown.""" from test_framework.test_framework import BitcoinTestFramework from test_framewo...
#!/usr/bin/env python3 # Copyright (c) 2018 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test bitcoind shutdown.""" from test_framework.test_framework import BitcoinTestFramework from test_framewo...
Remove race between connecting and shutdown on separate connections
qa: Remove race between connecting and shutdown on separate connections
Python
mit
DigitalPandacoin/pandacoin,DigitalPandacoin/pandacoin,peercoin/peercoin,peercoin/peercoin,DigitalPandacoin/pandacoin,peercoin/peercoin,peercoin/peercoin,DigitalPandacoin/pandacoin,DigitalPandacoin/pandacoin,peercoin/peercoin,DigitalPandacoin/pandacoin,peercoin/peercoin
8fb421831bb562a80edf5c3de84d71bf2a3eec4b
tools/scrub_database.py
tools/scrub_database.py
import os import sys import django sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) os.environ.setdefault("DJANGO_SETTINGS_MODULE", "museum.settings") django.setup() from museum_site.models import * # noqa: E402 from museum_site.constants import REMOVED_ARTICLE, DETAIL_REMOVED # noqa: E...
import datetime import os import sys import django sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) os.environ.setdefault("DJANGO_SETTINGS_MODULE", "museum.settings") django.setup() from django.contrib.sessions.models import Session from django.contrib.auth.models import User from museu...
Remove sessions when scrubbing DB for public release
Remove sessions when scrubbing DB for public release
Python
mit
DrDos0016/z2,DrDos0016/z2,DrDos0016/z2
3aabe40ba9d65f730763a604d1869c3114886273
odin/compatibility.py
odin/compatibility.py
""" This module is to include utils for managing compatibility between Python and Odin releases. """ import inspect import warnings def deprecated(message, category=DeprecationWarning): """ Decorator for marking classes/functions as being deprecated and are to be removed in the future. :param message: Me...
""" This module is to include utils for managing compatibility between Python and Odin releases. """ import inspect import warnings def deprecated(message, category=DeprecationWarning): """ Decorator for marking classes/functions as being deprecated and are to be removed in the future. :param message: Me...
Support kwargs along with args for functions
Support kwargs along with args for functions
Python
bsd-3-clause
python-odin/odin
39104d9b098a32ee6aa68eba9cb8d12127d3eb74
direlog.py
direlog.py
#!/usr/bin/env python # encoding: utf-8 import sys import re import argparse from patterns import pre_patterns def prepare(infile): """ Apply pre_patterns from patterns to infile :infile: input file """ try: for line in infile: result = line for pattern in pre_p...
#!/usr/bin/env python # encoding: utf-8 import sys import re import argparse from argparse import RawDescriptionHelpFormatter from patterns import pre_patterns def prepare(infile, outfile=sys.stdout): """ Apply pre_patterns from patterns to infile :infile: input file """ try: for line ...
Add some info and outfile to prepare function
Add some info and outfile to prepare function
Python
mit
abcdw/direlog,abcdw/direlog
27acd078d04222e345a7939d5f74c6d43069832e
fabfile.py
fabfile.py
from fabric.api import * # noqa env.hosts = [ '104.131.30.135', ] env.user = "root" env.directory = "/home/django/freemusic.ninja/django" def deploy(): with cd(env.directory): run("git pull --rebase") run("pip3 install -r requirements.txt") run("python3 manage.py collectstatic --noi...
from fabric.api import * # noqa env.hosts = [ '104.131.30.135', ] env.user = "root" env.directory = "/home/django/freemusic.ninja/django" def deploy(): with cd(env.directory): run("git pull --rebase") sudo("pip3 install -r requirements.txt", user='django') sudo("python3 manage.py co...
Add more fabric commands and fix deploy command
Add more fabric commands and fix deploy command
Python
bsd-3-clause
FreeMusicNinja/freemusic.ninja,FreeMusicNinja/freemusic.ninja
5d5f8e02efa6854bef0813e0e8383a3760cf93d2
os_brick/privileged/__init__.py
os_brick/privileged/__init__.py
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # d...
# Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # d...
Fix os-brick in virtual environments
Fix os-brick in virtual environments When running os-brick in a virtual environment created by a non root user, we get the following error: ModuleNotFoundError: No module named 'os_brick.privileged.rootwrap' This happens because the privsep daemon drops all the privileged except those defined in the context, and o...
Python
apache-2.0
openstack/os-brick,openstack/os-brick
5aa48facaf77d8fb6919c960659dfa41f3f1ad78
fabfile.py
fabfile.py
import os from fabric.api import * def unit(): current_dir = os.path.dirname(__file__) command = " ".join(["PYTHONPATH=$PYTHONPATH:%s/videolog" % current_dir, "nosetests", "-s", "--verbose", "--with-coverage", "--cover-package=videolog", "tests/unit/*"]) local(command)
import os from fabric.api import * def clean(): current_dir = os.path.dirname(__file__) local("find %s -name '*.pyc' -exec rm -f {} \;" % current_dir) local("rm -rf %s/build" % current_dir) def unit(): clean() current_dir = os.path.dirname(__file__) command = " ".join(["PYTHONPATH=$PYTHONPATH...
Add task clean() to remove *.pyc files
Add task clean() to remove *.pyc files
Python
mit
rcmachado/pyvideolog
63c2bdcf6cc3dae59f78abb59b14ca3e52789852
src/rlib/string_stream.py
src/rlib/string_stream.py
from rpython.rlib.streamio import Stream, StreamError class StringStream(Stream): def __init__(self, string): self._string = string self.pos = 0 self.max = len(string) - 1 def write(self, data): raise StreamError("StringStream is not writable") def truncate(self, si...
from rpython.rlib.streamio import Stream, StreamError class StringStream(Stream): def __init__(self, string): self._string = string self.pos = 0 self.max = len(string) - 1 def write(self, data): raise StreamError("StringStream is not writable") def truncate(self, ...
Fix StringStream to conform to latest pypy
Fix StringStream to conform to latest pypy Signed-off-by: Stefan Marr <46f1a0bd5592a2f9244ca321b129902a06b53e03@stefan-marr.de>
Python
mit
smarr/PySOM,smarr/PySOM,SOM-st/RPySOM,SOM-st/RPySOM,SOM-st/PySOM,SOM-st/PySOM
cc379cb3e68ddf5a110eef139282c83dc8b8e9d1
tests/test_queue/test_queue.py
tests/test_queue/test_queue.py
import unittest from aids.queue.queue import Queue class QueueTestCase(unittest.TestCase): ''' Unit tests for the Queue data structure ''' def setUp(self): self.test_queue = Queue() def test_queue_initialization(self): self.assertTrue(isinstance(self.test_queue, Queue)) def test_queue...
import unittest from aids.queue.queue import Queue class QueueTestCase(unittest.TestCase): ''' Unit tests for the Queue data structure ''' def setUp(self): self.test_queue = Queue() def test_queue_initialization(self): self.assertTrue(isinstance(self.test_queue, Queue)) def test_queue...
Add unit tests for enqueue, dequeue and length for Queue
Add unit tests for enqueue, dequeue and length for Queue
Python
mit
ueg1990/aids
b5fa8ff1d86485c7f00ddecaef040ca66a817dfc
setup.py
setup.py
#!/usr/bin/env python from distutils.core import setup setup( name='freki', version='0.3.0-develop', description='PDF-Extraction helper for RiPLEs pipeline.', author='Michael Goodman, Ryan Georgi', author_email='goodmami@uw.edu, rgeorgi@uw.edu', url='https://github.com/xigt/freki', license=...
#!/usr/bin/env python from distutils.core import setup setup( name='freki', version='0.3.0-develop', description='PDF-Extraction helper for RiPLEs pipeline.', author='Michael Goodman, Ryan Georgi', author_email='goodmami@uw.edu, rgeorgi@uw.edu', url='https://github.com/xigt/freki', license=...
Add Chardet as installation dependency
Add Chardet as installation dependency
Python
mit
xigt/freki,xigt/freki
9646c595068f9c996f05de51d7216cb0443a9809
setup.py
setup.py
from distutils.core import setup from dyn import __version__ with open('README.rst') as f: readme = f.read() with open('HISTORY.rst') as f: history = f.read() setup( name='dyn', version=__version__, keywords=['dyn', 'api', 'dns', 'email', 'dyndns', 'dynemail'], long_description='\n\n'.join([re...
from distutils.core import setup from dyn import __version__ with open('README.rst') as f: readme = f.read() with open('HISTORY.rst') as f: history = f.read() setup( name='dyn', version=__version__, keywords=['dyn', 'api', 'dns', 'email', 'dyndns', 'dynemail'], long_description='\n\n'.join([re...
Fix for incorrect project url
Fix for incorrect project url
Python
bsd-3-clause
Marchowes/dyn-python,dyninc/dyn-python,mjhennig/dyn-python
ff029b3cd79ab3f68ed5fc56be069e29580d5b46
setup.py
setup.py
#!/usr/bin/env python import os from numpy.distutils.core import setup, Extension # Utility function to read the README file. def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() wrapper = Extension('fortran_routines', sources=['src/fortran_routines.f90'], ...
#!/usr/bin/env python import os from numpy.distutils.core import setup, Extension # Utility function to read the README file. def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() wrapper = Extension('fortran_routines', sources=['src/fortran_routines.f90'], ...
Add a dependency on healpy
Add a dependency on healpy
Python
mit
ziotom78/stripeline,ziotom78/stripeline
472b0a0ba90054f151a60e200902b67223fbf6d9
setup.py
setup.py
from distutils.core import setup from setuptools.command.install import install try: description = open('README.txt').read() except: description = open('README.md').read() setup( name='python-ldap-test', version='0.2.2', author='Adrian Gruntkowski', author_email='adrian.gruntkowski@gmail.com...
import codecs from distutils.core import setup def read(fname): ''' Read a file from the directory where setup.py resides ''' with codecs.open(fname, encoding='utf-8') as rfh: return rfh.read() try: description = read('README.txt') except: description = read('README.md') setup( ...
Fix installation on systems where locales are not properly configured
Fix installation on systems where locales are not properly configured
Python
mit
zoldar/python-ldap-test,zoldar/python-ldap-test
674dd25bebb21919c27cb78bef2cee2f59f0c922
setup.py
setup.py
#!/usr/bin/env python from distutils.core import setup import py2exe setup(console=['CryptoUnLocker.py'])
#!/usr/bin/env python import sys from cx_Freeze import setup, Executable setup( name="CryptoUnLocker", version="1.0", Description="Detection and Decryption tool for CryptoLocker files", executables= [Executable("CryptoUnLocker.py")] )
Switch from py2exe to cx_Freeze
Switch from py2exe to cx_Freeze py2exe had issues with pycrypto. cx_Freeze seems to work.
Python
mit
kyrus/crypto-un-locker,thecocce/crypto-un-locker
3e689dc769bd4859b4ed73e98d8d559710aa2e14
tools/perf/profile_creators/small_profile_creator.py
tools/perf/profile_creators/small_profile_creator.py
# Copyright (c) 2013 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 os from telemetry.core import util from telemetry.page import page_set from telemetry.page import profile_creator class SmallProfileCreator(pro...
# Copyright (c) 2013 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 os from telemetry.core import util from telemetry.page import page_set from telemetry.page import profile_creator class SmallProfileCreator(pro...
Make profile generator wait for pages to load completely.
[Telemetry] Make profile generator wait for pages to load completely. The bug that causes this not to work is fixed. It is possible that this non-determinism in the profile could lead to flakiness in the session_restore benchmark. BUG=375979 Review URL: https://codereview.chromium.org/318733002 git-svn-id: de016e52...
Python
bsd-3-clause
hgl888/chromium-crosswalk-efl,littlstar/chromium.src,bright-sparks/chromium-spacewalk,dushu1203/chromium.src,mohamed--abdel-maksoud/chromium.src,axinging/chromium-crosswalk,Jonekee/chromium.src,Jonekee/chromium.src,markYoungH/chromium.src,Chilledheart/chromium,jaruba/chromium.src,dushu1203/chromium.src,Chilledheart/chr...
a61363b23c2fee99c7420cf2371a2711b3bc1eaa
indra/java_vm.py
indra/java_vm.py
"""Handles all imports from jnius to prevent conflicts resulting from attempts to set JVM options while the VM is already running.""" import os import warnings import jnius_config if '-Xmx4g' not in jnius_config.get_options(): if not jnius_config.vm_running: jnius_config.add_options('-Xmx4g') else: ...
"""Handles all imports from jnius to prevent conflicts resulting from attempts to set JVM options while the VM is already running.""" import os import warnings import jnius_config if '-Xmx4g' not in jnius_config.get_options(): if not jnius_config.vm_running: jnius_config.add_options('-Xmx4g') else: ...
Include current classpath when starting java VM
Include current classpath when starting java VM
Python
bsd-2-clause
johnbachman/indra,johnbachman/belpy,sorgerlab/indra,jmuhlich/indra,sorgerlab/indra,sorgerlab/belpy,jmuhlich/indra,johnbachman/belpy,sorgerlab/indra,bgyori/indra,bgyori/indra,johnbachman/indra,johnbachman/belpy,johnbachman/indra,bgyori/indra,sorgerlab/belpy,pvtodorov/indra,pvtodorov/indra,pvtodorov/indra,sorgerlab/belpy...
bdde8bb3ee9a79dc0ae777bb6e226dbc2be18dfb
manuscript/urls.py
manuscript/urls.py
# Copyright (C) 2011 by Christopher Adams # Released under MIT License. See LICENSE.txt in the root of this # distribution for details. from django.conf.urls.defaults import * urlpatterns = patterns('', url(r'^$', 'manuscript.views.all_works', name="all-works"), url(r'^(?P<title>[-\w]+)/$', 'manuscript.views.whole_...
# Copyright (C) 2011 by Christopher Adams # Released under MIT License. See LICENSE.txt in the root of this # distribution for details. from django.conf.urls.defaults import * urlpatterns = patterns('', url(r'^$', 'manuscript.views.all_works', name="all-works"), url(r'^(?P<title>[-\w]+)/$', 'manuscript.views.whole_...
Add sample url patterns to views for management functions.
Add sample url patterns to views for management functions.
Python
mit
adamsc64/django-manuscript,adamsc64/django-manuscript
e5db0a11634dc442f77f5550efd5cbf687ea6526
lionschool/core/admin.py
lionschool/core/admin.py
from django.contrib import admin from .models import Grade, Group, Pupil, Teacher, Warden for model in {Grade, Group, Pupil, Teacher, Warden}: admin.site.register(model)
from django.contrib import admin from .models import Grade, Group, Pupil, Teacher, Warden, Course for model in Grade, Group, Pupil, Teacher, Warden, Course: admin.site.register(model)
Add Course field to Admin
Add Course field to Admin Oops! forgot..
Python
bsd-3-clause
Leo2807/lioncore
fda50fb75b0b0e1d571c825e0a364573b93461bc
mbuild/__init__.py
mbuild/__init__.py
from mbuild.box import Box from mbuild.coarse_graining import coarse_grain from mbuild.coordinate_transform import * from mbuild.compound import * from mbuild.pattern import * from mbuild.packing import * from mbuild.port import Port from mbuild.recipes import * from mbuild.lattice import Lattice from mbuild.recipes im...
from mbuild.box import Box from mbuild.coarse_graining import coarse_grain from mbuild.coordinate_transform import * from mbuild.compound import * from mbuild.pattern import * from mbuild.packing import * from mbuild.port import Port from mbuild.lattice import Lattice from mbuild.recipes import recipes from mbuild.vers...
Remove a troubling import *
Remove a troubling import *
Python
mit
iModels/mbuild,iModels/mbuild
6f968a4aa4048163dd55f927a32da2477cd8c1ff
tx_salaries/search_indexes.py
tx_salaries/search_indexes.py
from haystack import indexes from tx_people.models import Organization from tx_salaries.models import Employee class EmployeeIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.CharField(document=True, use_template=True) content_auto = indexes.EdgeNgramField(model_attr='position__person__name') ...
from haystack import indexes from tx_salaries.models import Employee class EmployeeIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.CharField(document=True, use_template=True) content_auto = indexes.EdgeNgramField(model_attr='position__person__name') compensation = indexes.FloatField(model_at...
Index slugs to reduce search page queries
Index slugs to reduce search page queries
Python
apache-2.0
texastribune/tx_salaries,texastribune/tx_salaries
42c7496beefea0e5d10cbd6e356335efae27a5ec
taiga/projects/migrations/0043_auto_20160530_1004.py
taiga/projects/migrations/0043_auto_20160530_1004.py
# -*- coding: utf-8 -*- # Generated by Django 1.9.2 on 2016-05-30 10:04 from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('projects', '0042_auto_20160...
# -*- coding: utf-8 -*- # Generated by Django 1.9.2 on 2016-05-30 10:04 from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('projects', '0040_remove_mem...
Fix a problem with a migration between master and stable branch
Fix a problem with a migration between master and stable branch
Python
agpl-3.0
dayatz/taiga-back,taigaio/taiga-back,xdevelsistemas/taiga-back-community,taigaio/taiga-back,xdevelsistemas/taiga-back-community,dayatz/taiga-back,dayatz/taiga-back,xdevelsistemas/taiga-back-community,taigaio/taiga-back
e43b91412ee0899bb6b851a760dd06bce263d099
Instanssi/ext_blog/templatetags/blog_tags.py
Instanssi/ext_blog/templatetags/blog_tags.py
# -*- coding: utf-8 -*- from django import template from django.conf import settings from Instanssi.ext_blog.models import BlogEntry register = template.Library() @register.inclusion_tag('ext_blog/blog_messages.html') def render_blog(event_id): entries = BlogEntry.objects.filter(event_id__lte=int(event_id), publ...
# -*- coding: utf-8 -*- from django import template from django.conf import settings from Instanssi.ext_blog.models import BlogEntry register = template.Library() @register.inclusion_tag('ext_blog/blog_messages.html') def render_blog(event_id, max_posts=10): entries = BlogEntry.objects.filter(event_id__lte=int(e...
Allow customizing number of posts displayed
ext_blog: Allow customizing number of posts displayed
Python
mit
Instanssi/Instanssi.org,Instanssi/Instanssi.org,Instanssi/Instanssi.org,Instanssi/Instanssi.org
c8cc85f0d10093ae9cd42ee4cc7dabef46718645
ood/controllers/simple.py
ood/controllers/simple.py
import socket from ood.minecraft import Client from ood.models import SimpleServerState class SimpleServerController(object): def __init__(self, ood_instance): self.state = SimpleServerState.objects.get(ood=ood_instance) self.mcc = Client(ood_instance) def start(self): self.mcc.rese...
import socket from ood.minecraft import Client from ood.models import SimpleServerState class SimpleServerController(object): def __init__(self, ood_instance): self.state, _ = SimpleServerState.objects.get_or_create( ood=ood_instance) self.mcc = Client(ood_instance) def start(se...
Create SimpleServerState object if it doesn't exist.
Create SimpleServerState object if it doesn't exist.
Python
mit
markrcote/ood,markrcote/ood,markrcote/ood,markrcote/ood
a7919b78c96128cc5bcfda759da11f6b067d0041
tests/__init__.py
tests/__init__.py
import base64 import unittest def setup_package(self): pass def teardown_package(self): pass class BaseS3EncryptTest(unittest.TestCase): def decode64(self, data): return base64.b64decode(data) def encode64(self, data): return base64.b64encode(data)
import base64 import codecs import unittest def setup_package(self): pass def teardown_package(self): pass class BaseS3EncryptTest(unittest.TestCase): def decode64(self, data): return base64.b64decode(codecs.decode(data, 'utf-8')) def encode64(self, data): return codecs.encode(ba...
Make test helpers py 3 compatable
Make test helpers py 3 compatable
Python
bsd-3-clause
boldfield/s3-encryption
24ed97f09707a404bf81062a99a485c547d92d11
accio/webhooks/views.py
accio/webhooks/views.py
from django.http.response import HttpResponse def webhook(request): return HttpResponse('Webhooks not implemented yet', status=501)
from django.http.response import HttpResponse from django.views.decorators.csrf import csrf_exempt @csrf_exempt def webhook(request): return HttpResponse('Webhooks not implemented yet', status=501)
Add csrf_exempt to webhook view
fix: Add csrf_exempt to webhook view
Python
mit
relekang/accio,relekang/accio,relekang/accio
75345f55679437b418d9645371efc647b0d7db6c
filestore/api.py
filestore/api.py
from __future__ import absolute_import, division, print_function from .commands import insert_resource, insert_datum, retrieve
from __future__ import absolute_import, division, print_function from .commands import insert_resource, insert_datum, retrieve from .retrieve import register_handler
Add register_handler with the API.
API: Add register_handler with the API.
Python
bsd-3-clause
ericdill/fileStore,ericdill/databroker,ericdill/databroker,danielballan/filestore,ericdill/fileStore,stuwilkins/filestore,danielballan/filestore,NSLS-II/filestore,stuwilkins/filestore,tacaswell/filestore
dcd6d830033914a0ccf26822d6f305c084b90987
f8a_jobs/defaults.py
f8a_jobs/defaults.py
#!/usr/bin/env python3 import os from datetime import timedelta _BAYESIAN_JOBS_DIR = os.path.dirname(os.path.realpath(__file__)) DEFAULT_SERVICE_PORT = 34000 SWAGGER_YAML_PATH = os.path.join(_BAYESIAN_JOBS_DIR, 'swagger.yaml') DEFAULT_JOB_DIR = os.path.join(_BAYESIAN_JOBS_DIR, 'default_jobs') TOKEN_VALID_TIME = timed...
#!/usr/bin/env python3 import os from datetime import timedelta _BAYESIAN_JOBS_DIR = os.path.dirname(os.path.realpath(__file__)) DEFAULT_SERVICE_PORT = 34000 SWAGGER_YAML_PATH = os.path.join(_BAYESIAN_JOBS_DIR, 'swagger.yaml') DEFAULT_JOB_DIR = os.path.join(_BAYESIAN_JOBS_DIR, 'default_jobs') TOKEN_VALID_TIME = timed...
Fix wrong variable reference in configuration
Fix wrong variable reference in configuration
Python
apache-2.0
fabric8-analytics/fabric8-analytics-jobs,fabric8-analytics/fabric8-analytics-jobs
25e5b39113994769c01bf6a79a9ca65764861ab3
spicedham/__init__.py
spicedham/__init__.py
from pkg_resources import iter_entry_points from spicedham.config import config # TODO: Wrap all of this in an object with this in an __init__ function plugins = [] for plugin in iter_entry_points(group='spicedham.classifiers', name=None): pluginClass = plugin.load() plugins.append(pluginClass()) def train(...
from pkg_resources import iter_entry_points from spicedham.config import load_config _plugins = None def load_plugins(): """ If not already loaded, load plugins. """ if _plugins == None load_config() _plugins = [] for plugin in iter_entry_points(group='spicedham.classifiers', ...
Fix code which executes on module load.
Fix code which executes on module load.
Python
mpl-2.0
mozilla/spicedham,mozilla/spicedham
8e76b64fa3eafa9d22fc37b68ddb1daff6633119
thinglang/parser/tokens/functions.py
thinglang/parser/tokens/functions.py
from thinglang.lexer.symbols.base import LexicalIdentifier from thinglang.parser.tokens import BaseToken, DefinitionPairToken from thinglang.parser.tokens.collections import ListInitializationPartial, ListInitialization from thinglang.utils.type_descriptors import ValueType class Access(BaseToken): def __init__(s...
from thinglang.lexer.symbols.base import LexicalIdentifier, LexicalAccess from thinglang.parser.tokens import BaseToken, DefinitionPairToken from thinglang.parser.tokens.collections import ListInitializationPartial, ListInitialization from thinglang.utils.type_descriptors import ValueType class Access(BaseToken): ...
Use original LexicalIDs in Access
Use original LexicalIDs in Access
Python
mit
ytanay/thinglang,ytanay/thinglang,ytanay/thinglang,ytanay/thinglang
22e90cf883fa0b6d4c8acb282ebe28929f6d9487
nhs/patents/models.py
nhs/patents/models.py
from django.db import models from nhs.prescriptions.models import Product class Patent(models.Model): drug = models.ForeignKey(Product) expiry_date = models.DateField() start_date = models.DateField(null=True, blank=True) # Stupid. But you know, they're called patent number...
from django.db import models from nhs.prescriptions.models import Product class Patent(models.Model): drug = models.ForeignKey(Product) expiry_date = models.DateField() start_date = models.DateField(null=True, blank=True) # Stupid. But you know, they're called patent number...
Add that field in the model
Add that field in the model
Python
agpl-3.0
openhealthcare/open-prescribing,openhealthcare/open-prescribing,openhealthcare/open-prescribing
5597c9db9067ce466697f75949d47d7f94077fae
tests/test_forms.py
tests/test_forms.py
from django.forms import ModelForm, RadioSelect from .models import Product, Option class ProductForm(ModelForm): class Meta: model = Product class OptionForm(ModelForm): class Meta: model = Option def test_post(rf): req = rf.post('/', {'price': '2.12'}) form = ProductForm(req.POST...
from django.forms import ModelForm, RadioSelect from .models import Product, Option class ProductForm(ModelForm): class Meta: model = Product class OptionForm(ModelForm): class Meta: model = Option def test_post(rf): req = rf.post('/', {'price': '2.12'}) form = ProductForm(req.POST...
Add tests for proper values in select/radios
Add tests for proper values in select/radios
Python
bsd-2-clause
Suor/django-easymoney
b4f17dfd004cf0033e1aeccbb9e75a07bbe35cfa
competition_scripts/interop/tra.py
competition_scripts/interop/tra.py
import argparse from time import time try: # Python 3 from xmlrpc.client import ServerProxy except ImportError: # Python 2 from SimpleXMLRPCServer import ServerProxy if __name__ == '__main__': parser = argparse.ArgumentParser( description='AUVSI SUAS TRA') parser.add_argument( '...
import argparse from time import time try: # Python 3 from xmlrpc.client import ServerProxy except ImportError: # Python 2 from SimpleXMLRPCServer import ServerProxy if __name__ == '__main__': parser = argparse.ArgumentParser( description='AUVSI SUAS TRA') parser.add_argument( '...
Add initialization for ServerProxy object
Add initialization for ServerProxy object
Python
mit
FlintHill/SUAS-Competition,FlintHill/SUAS-Competition,FlintHill/SUAS-Competition,FlintHill/SUAS-Competition,FlintHill/SUAS-Competition
d6da05f79d62f90d8d03908197a0389b67535aa5
halfedge_mesh.py
halfedge_mesh.py
class HalfedgeMesh: def __init__(self, filename=None): """Make an empty halfedge mesh.""" self.vertices = [] self.halfedges = [] self.facets = [] def read_off(self, filename): class Vertex: def __init__(self, x, y, z, index): """Create a vertex with give...
class HalfedgeMesh: def __init__(self, filename=None): """Make an empty halfedge mesh.""" self.vertices = [] self.halfedges = [] self.facets = [] def parse_off(self, filename): """Parses OFF files and returns a set of vertices, halfedges, and facets. """ ...
Add parse_off stub and change docstring
Add parse_off stub and change docstring I follow the TomDoc format for docstrings.
Python
mit
carlosrojas/halfedge_mesh
a1a9852f478258b2c2f6f28a0ee28f223adaa299
src/myarchive/db/tables/ljtables.py
src/myarchive/db/tables/ljtables.py
from sqlalchemy import ( LargeBinary, Boolean, Column, Integer, String, PickleType, ForeignKey) from sqlalchemy.orm import backref, relationship from sqlalchemy.orm.exc import NoResultFound from myarchive.db.tables.base import Base from myarchive.db.tables.file import TrackedFile from myarchive.db.tables.associati...
from sqlalchemy import ( Column, Integer, String, TIMESTAMP, ForeignKey) from sqlalchemy.orm import backref, relationship from sqlalchemy.orm.exc import NoResultFound from myarchive.db.tables.base import Base from myarchive.db.tables.file import TrackedFile class LJHost(Base): """Class representing a user re...
Add a bunch of LJ tables
Add a bunch of LJ tables
Python
mit
zetasyanthis/myarchive
13350cdf5598ac0ed55e5404cf6d407300b4c1ac
apps/home/forms.py
apps/home/forms.py
# -*- coding: utf-8 -*- import re from django import forms from apps.chat.models import Chats from django.utils.translation import ugettext as _ class CreateChatForm(forms.Form): pass class JoinChatForm(forms.Form): chat_token = forms.CharField(required=True, max_length=24, label='') chat_token.widget =...
# -*- coding: utf-8 -*- import re from django import forms from apps.chat.models import Chats from django.utils.translation import ugettext as _ class CreateChatForm(forms.Form): pass class JoinChatForm(forms.Form): chat_token = forms.CharField(required=True, max_length=24, label='') chat_token.widget =...
Set autocomplete off for chat token form field
Set autocomplete off for chat token form field
Python
bsd-3-clause
MySmile/sfchat,MySmile/sfchat,MySmile/sfchat,MySmile/sfchat
e8da237a6c1542b997b061db43cc993942983b10
django_local_apps/management/commands/local_app_utils/db_clean_utils.py
django_local_apps/management/commands/local_app_utils/db_clean_utils.py
from django.db.models import Q from django.utils import timezone def remove_expired_record(expire_days, query_set, time_attr_name="timestamp"): expired_record_filter = {"%s__lt" % time_attr_name: timezone.now() - timezone.timedelta(days=expire_days)} q = Q(**expired_record_filter) final_q = query_set.filt...
from django.db.models import Q from django.utils import timezone def remove_expired_record(expire_days, query_set, time_attr_name="timestamp"): expired_record_filter = {"%s__lt" % time_attr_name: timezone.now() - timezone.timedelta(days=expire_days)} q = Q(**expired_record_filter) final_q = query_set.filt...
Delete item with limited size.
Delete item with limited size.
Python
bsd-3-clause
weijia/django-local-apps,weijia/django-local-apps
ce3948b2aacddfb9debd4834d9aa446e99987a0d
app/views.py
app/views.py
from app import mulungwishi_app as url from flask import render_template @url.route('/') def index(): return render_template('index.html') @url.route('/<query>') def print_user_input(query): if '=' in query: query_container, query_value = query.split('=') return 'Your query is {} which is eq...
from app import mulungwishi_app as url from flask import render_template @url.route('/') def index(): return render_template('index.html') @url.route('/<query>') def print_user_input(query): if '=' in query: query_container, query_value = query.split('=') return 'Your query is {} which is eq...
Replace string concatenation with .format function
Replace string concatenation with .format function
Python
mit
admiral96/mulungwishi-webhook,engagespark/public-webhooks,admiral96/public-webhooks,admiral96/mulungwishi-webhook,admiral96/public-webhooks,engagespark/mulungwishi-webhook,engagespark/mulungwishi-webhook,engagespark/public-webhooks
98aea2115cb6c5101379be2320a6fb0735a32490
helenae/web/views.py
helenae/web/views.py
from flask import render_template from flask_app import app @app.route('/') def index(): return render_template('index.html')
# -*- coding: utf-8 -*- import datetime from hashlib import sha256 from time import gmtime, strftime import sqlalchemy from flask import render_template, redirect, url_for from flask_app import app, db_connection, dbTables from forms import RegisterForm @app.route('/', methods=('GET', 'POST')) def index(): retur...
Add routes for other pages
Add routes for other pages
Python
mit
Relrin/Helenae,Relrin/Helenae,Relrin/Helenae
590f80bc382cdbec97e2cb3e7b92c79bb7fa89cc
dyndns/models.py
dyndns/models.py
from django.db import models class Record(models.Model): domain_id = models.IntegerField() name = models.CharField(max_length=30) type=models.CharField(max_length=6) content=models.CharField(max_length=30) ttl=models.IntegerField() prio=models.IntegerField() change_date= models.IntegerField() def __unicode__(s...
from django.db import models class Domain(models.Model): id = models.IntegerField(primary_key=True) name = models.CharField(unique=True, max_length=255) master = models.CharField(max_length=128) last_check = models.IntegerField() type = models.CharField(max_length=6) notified_serial = models.In...
Update model to match latest PDNS and add other two tables
Update model to match latest PDNS and add other two tables
Python
bsd-2-clause
zefciu/django-powerdns-dnssec,allegro/django-powerdns-dnssec,dominikkowalski/django-powerdns-dnssec,dominikkowalski/django-powerdns-dnssec,dominikkowalski/django-powerdns-dnssec,allegro/django-powerdns-dnssec,zefciu/django-powerdns-dnssec,dominikkowalski/django-powerdns-dnssec,zefciu/django-powerdns-dnssec,allegro/djan...
454e107abfdc9e3038a18500568e9a1357364bd0
pygraphc/similarity/JaroWinkler.py
pygraphc/similarity/JaroWinkler.py
import jellyfish import multiprocessing from itertools import combinations class JaroWinkler(object): def __init__(self, event_attributes, event_length): self.event_attributes = event_attributes self.event_length = event_length def __jarowinkler(self, unique_event_id): string1 = unico...
import jellyfish import multiprocessing from itertools import combinations class JaroWinkler(object): def __init__(self, event_attributes, event_length): self.event_attributes = event_attributes self.event_length = event_length def __jarowinkler(self, unique_event_id): string1 = unico...
Add checking for zero distance
Add checking for zero distance
Python
mit
studiawan/pygraphc
39d7ec0fe9fdbdd152dfcc2d4280b784f6315886
stardate/urls/index_urls.py
stardate/urls/index_urls.py
from django.conf.urls import include, url from django.views import generic from stardate.models import Blog from stardate.views import ( BlogCreate, select_backend, process_webhook, ) urlpatterns = [ url(r'^new/$', select_backend, name='blog-new'), url(r'^create/(?P<provider>[-\w]+)/$', BlogCreat...
from django.conf.urls import include, url from django.views import generic from stardate.models import Blog from stardate.views import ( BlogCreate, select_backend, process_webhook, ) urlpatterns = [ url(r'^new/$', select_backend, name='blog-new'), url(r'^create/(?P<provider>[-\w]+)/$', BlogCreat...
Revert "remove blog urls from index urls"
Revert "remove blog urls from index urls" This reverts commit f8d5541a8e5de124dcec62a32bd19a8226869622.
Python
bsd-3-clause
blturner/django-stardate,blturner/django-stardate
93d0f11658c7417371ec2e040397c7a572559585
django_remote_submission/consumers.py
django_remote_submission/consumers.py
"""Manage websocket connections.""" # -*- coding: utf-8 -*- import json from channels import Group from channels.auth import channel_session_user_from_http, channel_session_user from .models import Job @channel_session_user_from_http def ws_connect(message): message.reply_channel.send({ 'accept': True, ...
"""Manage websocket connections.""" # -*- coding: utf-8 -*- import json from channels import Group from channels.auth import channel_session_user_from_http, channel_session_user from .models import Job import json @channel_session_user_from_http def ws_connect(message): last_jobs = message.user.jobs.order_by('...
Send last jobs on initial connection
Send last jobs on initial connection
Python
isc
ornl-ndav/django-remote-submission,ornl-ndav/django-remote-submission,ornl-ndav/django-remote-submission
22472d7947c16388dc849b2c317ee4d509322754
docs/examples/01_make_resourcelist.py
docs/examples/01_make_resourcelist.py
from resync.resource_list import ResourceList from resync.resource import Resource from resync.sitemap import Sitemap rl = ResourceList() rl.add( Resource('http://example.com/res1', lastmod='2013-01-01') ) rl.add( Resource('http://example.com/res2', lastmod='2013-01-02') ) sm = Sitemap(pretty_xml=True) print sm.resour...
from resync.resource_list import ResourceList from resync.resource import Resource from resync.sitemap import Sitemap rl = ResourceList() rl.add( Resource('http://example.com/res1', lastmod='2013-01-01') ) rl.add( Resource('http://example.com/res2', lastmod='2013-01-02') ) print rl.as_xml(pretty_xml=True)
Update to use ResourceList methods
Update to use ResourceList methods
Python
apache-2.0
dans-er/resync,lindareijnhoudt/resync,lindareijnhoudt/resync,dans-er/resync,resync/resync
e82225201772794bf347c6e768d25f24a61b9b54
migrations/schematic_settings.py
migrations/schematic_settings.py
import sys import os # This only works if you're running schematic from the zamboni root. sys.path.insert(0, os.path.realpath('.')) # Set up zamboni. import manage from django.conf import settings config = settings.DATABASES['default'] config['HOST'] = config.get('HOST', 'localhost') config['PORT'] = config.get('POR...
import sys import os sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) # Set up zamboni. import manage from django.conf import settings config = settings.DATABASES['default'] config['HOST'] = config.get('HOST', 'localhost') config['PORT'] = config.get('PORT', '3306') if not config['HOS...
Make the settings work when there's no port, and fix up the path manipulation
Make the settings work when there's no port, and fix up the path manipulation
Python
bsd-3-clause
kumar303/zamboni,kmaglione/olympia,Prashant-Surya/addons-server,jamesthechamp/zamboni,yfdyh000/olympia,aviarypl/mozilla-l10n-addons-server,Joergen/zamboni,muffinresearch/addons-server,Jobava/zamboni,koehlermichael/olympia,clouserw/zamboni,kmaglione/olympia,mstriemer/addons-server,Hitechverma/zamboni,mstriemer/olympia,p...
e53e489da4e9f53e371997449bc813def2600008
opps/contrib/notifications/models.py
opps/contrib/notifications/models.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import json from django.db import models from django.utils.translation import ugettext_lazy as _ from opps.core.models import Publishable from opps.db import Db NOTIFICATION_TYPE = ( (u'json', _(u'JSON')), (u'text', _(u'Text')), (u'html', _(u'HTML')), ) cla...
#!/usr/bin/env python # -*- coding: utf-8 -*- import json from django.db import models from django.utils.translation import ugettext_lazy as _ from opps.core.models import Publishable from opps.db import Db NOTIFICATION_TYPE = ( (u'json', _(u'JSON')), (u'text', _(u'Text')), (u'html', _(u'HTML')), ) cla...
Add get_absolute_url on notification model
Add get_absolute_url on notification model
Python
mit
YACOWS/opps,opps/opps,jeanmask/opps,williamroot/opps,jeanmask/opps,opps/opps,YACOWS/opps,opps/opps,williamroot/opps,jeanmask/opps,jeanmask/opps,YACOWS/opps,YACOWS/opps,williamroot/opps,opps/opps,williamroot/opps
eccda634d3233cd4f8aaeea372735731fd674c29
pysis/labels/__init__.py
pysis/labels/__init__.py
import io import functools import warnings import six from .decoder import LabelDecoder from .encoder import LabelEncoder def load(stream): """Parse an isis label from a stream. :param stream: a ``.read()``-supporting file-like object containing a label. if ``stream`` is a string it will be treated ...
import io import warnings import six from .decoder import LabelDecoder from .encoder import LabelEncoder def load(stream): """Parse an isis label from a stream. :param stream: a ``.read()``-supporting file-like object containing a label. if ``stream`` is a string it will be treated as a filename ...
Add depreciation messages to old parse_label methods.
Add depreciation messages to old parse_label methods.
Python
bsd-3-clause
michaelaye/Pysis,wtolson/pysis,wtolson/pysis,michaelaye/Pysis