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
5cf0e2e9d68d2e0fca3780608f33d5d8cdaef8a9
admin/metrics/views.py
admin/metrics/views.py
from django.views.generic import TemplateView from django.contrib.auth.mixins import PermissionRequiredMixin from admin.base.settings import KEEN_CREDENTIALS from admin.base.utils import OSFAdmin class MetricsView(OSFAdmin, TemplateView, PermissionRequiredMixin): template_name = 'metrics/osf_metrics.html' ...
from django.views.generic import TemplateView from django.contrib.auth.mixins import PermissionRequiredMixin from admin.base.settings import KEEN_CREDENTIALS class MetricsView(TemplateView, PermissionRequiredMixin): template_name = 'metrics/osf_metrics.html' permission_required = 'admin.view_metrics' de...
Remove one more reference to old group permissions
Remove one more reference to old group permissions
Python
apache-2.0
erinspace/osf.io,adlius/osf.io,hmoco/osf.io,Johnetordoff/osf.io,cslzchen/osf.io,cslzchen/osf.io,saradbowman/osf.io,icereval/osf.io,icereval/osf.io,leb2dg/osf.io,icereval/osf.io,sloria/osf.io,caseyrollins/osf.io,sloria/osf.io,Nesiehr/osf.io,Johnetordoff/osf.io,cslzchen/osf.io,felliott/osf.io,monikagrabowska/osf.io,brian...
d1917d20f3aa26380e1e617f50b380142905d745
engines/string_template_engine.py
engines/string_template_engine.py
#!/usr/bin/env python """Provide the standard Python string.Template engine.""" from __future__ import print_function from string import Template from . import Engine class StringTemplate(Engine): """String.Template engine.""" handle = 'string.Template' def __init__(self, template, tolerant=False, ...
#!/usr/bin/env python """Provide the standard Python string.Template engine.""" from __future__ import print_function from string import Template from . import Engine class StringTemplate(Engine): """String.Template engine.""" handle = 'string.Template' def __init__(self, template, tolerant=False, *...
Transform values in string.Template engine before substitution.
Transform values in string.Template engine before substitution.
Python
mit
blubberdiblub/eztemplate
b1bc34e9a83cb3af5dd11baa1236f2b65ab823f9
cspreports/models.py
cspreports/models.py
# STANDARD LIB import json #LIBRARIES from django.db import models from django.utils.html import escape from django.utils.safestring import mark_safe class CSPReport(models.Model): class Meta(object): ordering = ('-created',) created = models.DateTimeField(auto_now_add=True) modified = models.D...
#LIBRARIES from django.db import models from django.utils.html import escape from django.utils.safestring import mark_safe # CSP REPORTS from cspreports import utils class CSPReport(models.Model): class Meta(object): ordering = ('-created',) created = models.DateTimeField(auto_now_add=True) mod...
Make `CSPReport.json_as_html` use the robust `utils.format_report` for formatting.
Make `CSPReport.json_as_html` use the robust `utils.format_report` for formatting.
Python
mit
adamalton/django-csp-reports
5183ad354943e81787010e3f108b1e819b9f703d
quran_tafseer/serializers.py
quran_tafseer/serializers.py
from django.urls import reverse from rest_framework import serializers from .models import Tafseer, TafseerText class TafseerSerializer(serializers.ModelSerializer): class Meta: model = Tafseer fields = ['id', 'name'] class TafseerTextSerializer(serializers.ModelSerializer): tafseer_id = ...
from django.urls import reverse from rest_framework import serializers from .models import Tafseer, TafseerText class TafseerSerializer(serializers.ModelSerializer): class Meta: model = Tafseer fields = ['id', 'name', 'language', 'author', 'book_name'] class TafseerTextSerializer(serializers....
Add meta data to Serializer
[FIX] Add meta data to Serializer
Python
mit
EmadMokhtar/tafseer_api
0be6ab488b74d628229c54a42117f5e69497737b
armstrong/apps/articles/admin.py
armstrong/apps/articles/admin.py
from django.contrib import admin from reversion.admin import VersionAdmin from armstrong.core.arm_content.admin import fieldsets from .models import Article class ArticleAdmin(VersionAdmin): fieldsets = ( (None, { 'fields': ('title', 'summary', 'body', 'primary_section', 'sect...
from django.contrib import admin from reversion.admin import VersionAdmin from armstrong.core.arm_content.admin import fieldsets from armstrong.core.arm_sections.admin import SectionTreeAdminMixin from .models import Article class ArticleAdmin(SectionTreeAdminMixin, VersionAdmin): fieldsets = ( (None, { ...
Add support for displaying with tree sections properly
Add support for displaying with tree sections properly
Python
apache-2.0
armstrong/armstrong.apps.articles,armstrong/armstrong.apps.articles
319bdba73d0ccecb229454272bb9bb12c226335a
cineapp/fields.py
cineapp/fields.py
# -*- coding: utf-8 -*- from wtforms import fields, widgets # Define wtforms widget and field class CKTextAreaWidget(widgets.TextArea): def __call__(self, field, **kwargs): kwargs.setdefault('class_', 'ckeditor') html_string = super(CKTextAreaWidget, self).__call__(field, **kwargs) html_string += ("""<script> ...
# -*- coding: utf-8 -*- from wtforms import fields, widgets from flask import Markup # Define wtforms widget and field class CKTextAreaWidget(widgets.TextArea): def __call__(self, field, **kwargs): kwargs.setdefault('class_', 'ckeditor') html_string = super(CKTextAreaWidget, self).__call__(field, **kwargs) htm...
Fix unwanted escape for CKEditor display
Fix unwanted escape for CKEditor display Fixes: #117
Python
mit
ptitoliv/cineapp,ptitoliv/cineapp,ptitoliv/cineapp
7d5fa6a8eda793ff4cc2183992949a095d65c1b0
app/enums/registration_fields.py
app/enums/registration_fields.py
class RegistrationFields: repository = 'repository' job = 'job' labels = 'labels' requested_params = 'requested_params' branch_restrictions = 'branch_restrictions' change_restrictions = 'change_restrictions' file_restrictions = 'file_restrictions' missed_times = 'missed_times'
class RegistrationFields: repository = 'repository' job = 'job' labels = 'labels' requested_params = 'requested_params' branch_restrictions = 'branch_restrictions' change_restrictions = 'change_restrictions' file_restrictions = 'file_restrictions' missed_times = 'missed_times' jenkin...
Add jenkins_url to valid registration fields
Add jenkins_url to valid registration fields
Python
mit
futuresimple/triggear
a6e7f053c151fc343f0dd86010b159e21c0948b5
accountsplus/forms.py
accountsplus/forms.py
from __future__ import unicode_literals import django.forms from django.conf import settings from django.apps import apps from django.contrib.auth.forms import AuthenticationForm from django.contrib.admin.forms import AdminAuthenticationForm from captcha.fields import ReCaptchaField class CaptchaForm(django.forms.F...
from __future__ import unicode_literals import django.forms from django.conf import settings from django.apps import apps from django.contrib.auth.forms import AuthenticationForm from django.contrib.admin.forms import AdminAuthenticationForm from captcha.fields import ReCaptchaField class CaptchaForm(django.forms.F...
Fix how we are reading user name
Fix how we are reading user name
Python
mit
foundertherapy/django-users-plus,foundertherapy/django-users-plus
7c4442099eb3d00f0c14381d1091e45daf8e9179
all/newterm/_posix.py
all/newterm/_posix.py
# coding: utf-8 from __future__ import unicode_literals, division, absolute_import, print_function import sys import os import subprocess def launch_executable(executable, args, cwd, env=None): """ Launches an executable with optional arguments :param executable: A unicode string of an executabl...
# coding: utf-8 from __future__ import unicode_literals, division, absolute_import, print_function import sys import os import subprocess def launch_executable(executable, args, cwd, env=None): """ Launches an executable with optional arguments :param executable: A unicode string of an executabl...
Fix a bug launching a posix executable
Fix a bug launching a posix executable
Python
mit
codexns/newterm
5e67e16d17d06a0f4d307a035ca6b62f094995c6
network/api/serializers.py
network/api/serializers.py
from rest_framework import serializers from network.base.models import Data class DataSerializer(serializers.ModelSerializer): class Meta: model = Data fields = ('id', 'start', 'end', 'observation', 'ground_station', 'payload') read_only_fields = ['id', 'start', 'end', 'observation', 'gro...
from rest_framework import serializers from network.base.models import Data class DataSerializer(serializers.ModelSerializer): class Meta: model = Data fields = ('id', 'start', 'end', 'observation', 'ground_station', 'payload') read_only_fields = ['id', 'start', 'end', 'observation', 'gro...
Adjust API to TLE code changes
Adjust API to TLE code changes
Python
agpl-3.0
cshields/satnogs-network,cshields/satnogs-network,cshields/satnogs-network,cshields/satnogs-network
84e2e931ea83c25154fbcf749c797faae19ba8af
src/test_heap.py
src/test_heap.py
# _*_coding:utf-8 _*_ """Test heap.""" data = [1, 2, 3, 4] def heap_init(): """Test heap init.""" from heap import Heap assert isinstance(Heap() == Heap) def test_push(): """Test push method.""" from heap import Heap high_low = Heap() high_low.push(data[0]) high_low.push(data[1]) ...
# _*_coding:utf-8 _*_ """Test heap.""" data = [1, 2, 3, 4] def heap_init(): """Test heap init.""" from heap import Heap assert isinstance(Heap() == Heap) def test_push(): """Test push method.""" from heap import Heap high_low = Heap() high_low.push(data[0]) high_low.push(data[1]) ...
Test left and right method, almost identical to get test
Test left and right method, almost identical to get test
Python
mit
regenalgrant/datastructures
72dcc89d96935ba4336ebafed5252628ecf92ed4
stables/views.py
stables/views.py
u""" 🐴 ✔ ✘ ▏ """ from django.shortcuts import render from django.shortcuts import get_object_or_404 from django.views.generic.base import RedirectView from urllib.parse import quote from . import models class BadgeView(RedirectView): permanent = False def get_redirect_url(self, *args, **kwargs): st...
u""" 🐴 ✔ ✘ ▏ """ from django.db.models import Q from django.shortcuts import render from django.shortcuts import get_object_or_404 from django.views.generic.base import RedirectView from urllib.parse import quote from . import models def badge_escape(val): return quote(val.replace('-', '--')) class BadgeView(R...
Update badge view with new model schema.
Update badge view with new model schema.
Python
mit
django-stables/django-stables,django-stables/django-stables
376b327379caeb0845007c3a0e7c33e1f15869f0
flatisfy/constants.py
flatisfy/constants.py
# coding: utf-8 """ Constants used across the app. """ from __future__ import absolute_import, print_function, unicode_literals # Some backends give more infos than others. Here is the precedence we want to # use. First is most important one, last is the one that will always be # considered as less trustable if two ba...
# coding: utf-8 """ Constants used across the app. """ from __future__ import absolute_import, print_function, unicode_literals # Some backends give more infos than others. Here is the precedence we want to # use. First is most important one, last is the one that will always be # considered as less trustable if two ba...
Drop support for entreparticuliers Weboob module
Drop support for entreparticuliers Weboob module
Python
mit
Phyks/Flatisfy,Phyks/Flatisfy,Phyks/Flatisfy,Phyks/Flatisfy
5ac83deb88c8ae34a361c9a5b60dcb16fea77b35
custom/inddex/reports/master_data_file.py
custom/inddex/reports/master_data_file.py
from django.utils.functional import cached_property from memoized import memoized from custom.inddex.food import FoodData from custom.inddex.ucr_data import FoodCaseData from custom.inddex.utils import BaseGapsSummaryReport class MasterDataFileSummaryReport(BaseGapsSummaryReport): title = 'Output 1 - Master Dat...
from django.utils.functional import cached_property from corehq.apps.reports.datatables import DataTablesColumn, DataTablesHeader from corehq.apps.reports.generic import GenericTabularReport from corehq.apps.reports.standard import CustomProjectReport, DatespanMixin from custom.inddex.filters import ( CaseOwnersFi...
Make it a normal report
Make it a normal report No need to override a bunch of stuff, assemble filters and configs through inheritance, use a custom template, etcetera
Python
bsd-3-clause
dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq
40a63fd8ca5dd574e729b9f531664ce384aa404c
app/schedule/tasks.py
app/schedule/tasks.py
from datetime import datetime from importlib import import_module import pytz from django.conf import settings from app.schedule.celery import celery_app from app.schedule.libs.sms import DeviceNotFoundError @celery_app.task(bind=True) def send_message(self, to, message, sg_user, sg_password): def load_sms_clas...
from datetime import datetime from importlib import import_module import pytz from django.conf import settings from app.schedule.celery import celery_app from app.schedule.libs.sms import DeviceNotFoundError @celery_app.task(bind=True) def send_message(self, to, message, sg_user, sg_password): def load_sms_clas...
Increase retry count and add countdown to retry method
Increase retry count and add countdown to retry method
Python
agpl-3.0
agendaodonto/server,agendaodonto/server
d9b5a78b36729bdb3ce11c8626d00b57555fb356
core/views.py
core/views.py
from django_filters.rest_framework import DjangoFilterBackend from rest_framework import viewsets, mixins, routers from rest_framework.filters import SearchFilter, OrderingFilter from rest_framework.viewsets import GenericViewSet from core import serializers as api from core.models import Image, Pin from core.permissi...
from django_filters.rest_framework import DjangoFilterBackend from rest_framework import viewsets, mixins, routers from rest_framework.filters import SearchFilter, OrderingFilter from rest_framework.viewsets import GenericViewSet from core import serializers as api from core.models import Image, Pin from core.permissi...
Allow only the user-data fetching
Refactor: Allow only the user-data fetching
Python
bsd-2-clause
pinry/pinry,pinry/pinry,lapo-luchini/pinry,lapo-luchini/pinry,lapo-luchini/pinry,lapo-luchini/pinry,pinry/pinry,pinry/pinry
c86d5c928cdefd09aca102b2a5c37f662e1426a6
{{cookiecutter.repo_name}}/{{cookiecutter.repo_name}}/users/tests/factories.py
{{cookiecutter.repo_name}}/{{cookiecutter.repo_name}}/users/tests/factories.py
from feder.users import models import factory class UserFactory(factory.django.DjangoModelFactory): username = factory.Sequence(lambda n: 'user-{0}'.format(n)) email = factory.Sequence(lambda n: 'user-{0}@example.com'.format(n)) password = factory.PosteGnerationMethodCall('set_password', 'password') ...
import factory class UserFactory(factory.django.DjangoModelFactory): username = factory.Sequence(lambda n: 'user-{0}'.format(n)) email = factory.Sequence(lambda n: 'user-{0}@example.com'.format(n)) password = factory.PostGenerationMethodCall('set_password', 'password') class Meta: model = 'us...
Fix typo & import in UserFactory
Fix typo & import in UserFactory
Python
bsd-3-clause
andresgz/cookiecutter-django,gappsexperts/cookiecutter-django,asyncee/cookiecutter-django,gappsexperts/cookiecutter-django,calculuscowboy/cookiecutter-django,aleprovencio/cookiecutter-django,ddiazpinto/cookiecutter-django,asyncee/cookiecutter-django,drxos/cookiecutter-django-dokku,thisjustin/cookiecutter-django,aleprov...
98f638e5a42765a284a4fd006190507efee5363a
runtests.py
runtests.py
#!/usr/bin/env python import os import sys os.environ.setdefault("DJANGO_SETTINGS_MODULE", "farnsworth.settings") this_dir = os.path.abspath(os.path.dirname(__file__)) if this_dir not in sys.path: sys.path.insert(0, this_dir) import django from django.test.utils import get_runner from django.conf import settings d...
#!/usr/bin/env python import os import sys os.environ.setdefault("DJANGO_SETTINGS_MODULE", "farnsworth.settings") this_dir = os.path.abspath(os.path.dirname(__file__)) if this_dir not in sys.path: sys.path.insert(0, this_dir) import django from django.test.runner import DiscoverRunner from django.conf import settin...
Use the new test runner
Use the new test runner
Python
bsd-2-clause
knagra/farnsworth,knagra/farnsworth,knagra/farnsworth,knagra/farnsworth
9d1a21e046bac48719e6f396a55489bffe631cf7
runtests.py
runtests.py
#!/usr/bin/env python import os, sys from django.conf import settings def runtests(*test_args): if not test_args: test_args = ['lockdown'] parent = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, parent) settings.configure( DATABASE_ENGINE='sqlite3', INSTALLED_A...
#!/usr/bin/env python import os, sys from django.conf import settings def runtests(*test_args): if not test_args: test_args = ['lockdown'] parent = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, parent) settings.configure( DATABASE_ENGINE='sqlite3', INSTALLED_A...
Add in django.contrib.auth to the default test runner
Add in django.contrib.auth to the default test runner
Python
bsd-3-clause
Dunedan/django-lockdown,Dunedan/django-lockdown
b0e614ea7ac59b6b869155b9ac8ea370cb56f83d
cardinal/decorators.py
cardinal/decorators.py
import functools def command(triggers): def wrap(f): @functools.wraps(f) def inner(*args, **kwargs): return f(*args, **kwargs) inner.commands = triggers return inner return wrap def help(line): def wrap(f): @functools.wraps(f) def inner(*args, ...
import functools def command(triggers): if isinstance(triggers, basestring): triggers = [triggers] def wrap(f): @functools.wraps(f) def inner(*args, **kwargs): return f(*args, **kwargs) inner.commands = triggers return inner return wrap def help(line)...
Allow for single trigger in @command decorator
Allow for single trigger in @command decorator
Python
mit
BiohZn/Cardinal,JohnMaguire/Cardinal
2aac8cafc0675d38cabcc137d063de0119b3ff3d
game.py
game.py
import pygame, sys """ A simple four in a row game. Author: Isaac Arvestad """ class Game: def __init__(self): def update(self): "Handle input." for event in pygame.event.get(): if event.type == pygame.QUIT: return False elif event.type == pygame.KEYDO...
import pygame, sys from board import Board """ A simple four in a row game. Author: Isaac Arvestad """ class Game: def __init__(self): pygame.init() self.screen = pygame.display.set_mode((600,600)) self.background = pygame.Surface(self.screen.get_size()) self.bac...
Create screen and draw board to screen.
Create screen and draw board to screen.
Python
mit
isaacarvestad/four-in-a-row
00208e088ea62eb3c405e22f54a96e6e46869844
pubsub/backend/rabbitmq.py
pubsub/backend/rabbitmq.py
from gevent import monkey monkey.patch_all() import uuid from kombu.mixins import ConsumerMixin from pubsub.backend.base import BaseSubscriber, BasePublisher from pubsub.helpers import get_config from pubsub.backend.handlers import RabbitMQHandler class RabbitMQPublisher(BasePublisher, RabbitMQHandler): def __...
from gevent import monkey monkey.patch_all() import uuid from kombu.mixins import ConsumerMixin from pubsub.backend.base import BaseSubscriber, BasePublisher from pubsub.helpers import get_config from pubsub.backend.handlers import RabbitMQHandler class RabbitMQPublisher(BasePublisher, RabbitMQHandler): def __...
Add the possiblity to pass a conf file to Publisher and Subscriber class
Add the possiblity to pass a conf file to Publisher and Subscriber class Closes #20
Python
mit
WeLikeAlpacas/Qpaca,WeLikeAlpacas/python-pubsub,csarcom/python-pubsub
1acb0e5db755b0d4cc389ed32f740d7e65218a5e
celestial/views.py
celestial/views.py
from django.views.generic import ListView, DetailView from .models import Planet, SolarSystem class SystemMixin(object): model = SolarSystem def get_queryset(self): return super(SystemMixin, self).get_queryset().filter(radius__isnull=False) class PlanetMixin(object): model = Planet def get_...
from django.views.generic import ListView, DetailView from .models import Planet, SolarSystem class SystemMixin(object): model = SolarSystem def get_queryset(self): return super(SystemMixin, self).get_queryset().filter(radius__isnull=False) class PlanetMixin(object): model = Planet def get_...
Order planets by distance form their star.
Order planets by distance form their star.
Python
mit
Floppy/kepler-explorer,Floppy/kepler-explorer,Floppy/kepler-explorer
8858cf1f0b87026ce913a19c4e5df415409cfd79
streak-podium/read.py
streak-podium/read.py
import logging import requests def input_file(filename): """ Read a file and return list of usernames. Assumes one username per line and ignores blank lines. """ with open(filename, 'r') as f: return list(line.strip() for line in f if line.strip()) def org_members(org_name): """ ...
import logging import requests def input_file(filename): """ Read a file and return list of usernames. Assumes one username per line and ignores blank lines. """ with open(filename, 'r') as f: return list(line.strip() for line in f if line.strip()) def org_members(org_name): """ ...
Handle None for org or file with default org name
Handle None for org or file with default org name
Python
mit
supermitch/streak-podium,jollyra/hubot-commit-streak,jollyra/hubot-streak-podium,jollyra/hubot-commit-streak,supermitch/streak-podium,jollyra/hubot-streak-podium
b9f8012084a0f7faae4b1a820b25ceb93b29e04c
install_steps/create_bosh_cert.py
install_steps/create_bosh_cert.py
from subprocess import call from os import makedirs from shutil import copy def do_step(context): makedirs("bosh/manifests") # Generate the private key and certificate call("sh create_cert.sh", shell=True) copy("bosh.key", "./bosh/bosh") with open('bosh_cert.pem', 'r') as tmpfile: ssh_ce...
from subprocess import call from os import makedirs from os import path from shutil import copy def do_step(context): if not path.isdir("bosh/manifests"): makedirs("bosh/manifests") # Generate the private key and certificate call("sh create_cert.sh", shell=True) copy("bosh.key", "./bosh/bosh...
Check to see if manifests path exists
Check to see if manifests path exists
Python
apache-2.0
cf-platform-eng/bosh-azure-template,cf-platform-eng/bosh-azure-template
9109e3803b139c349d17b9b413b0ff9d5b965b55
hassio/addons/util.py
hassio/addons/util.py
"""Util addons functions.""" import hashlib import pathlib import re import unicodedata RE_SLUGIFY = re.compile(r'[^a-z0-9_]+') def slugify(text): """Slugify a given text.""" text = unicodedata.normalize('NFKD', text) text = text.lower() text = text.replace(" ", "_") text = RE_SLUGIFY.sub("", tex...
"""Util addons functions.""" import hashlib import pathlib import re RE_SLUGIFY = re.compile(r'[^a-z0-9_]+') RE_SHA1 = re.compile(r"[a-f0-9]{40}") def get_hash_from_repository(repo): """Generate a hash from repository.""" key = repo.lower().encode() return hashlib.sha1(key).hexdigest()[:8] def extract_...
Use in every case a hash for addon name
Use in every case a hash for addon name
Python
bsd-3-clause
pvizeli/hassio,pvizeli/hassio
dcd3e4f5ded298b79b40d16a9f0274752ed96ad1
linter.py
linter.py
# # linter.py # Linter for SublimeLinter3, a code checking framework for Sublime Text 3 # # Written by NotSqrt # Copyright (c) 2013 NotSqrt # # License: MIT # """This module exports the Cppcheck plugin class.""" from SublimeLinter.lint import Linter, util class Cppcheck(Linter): """Provides an interface to cpp...
# # linter.py # Linter for SublimeLinter3, a code checking framework for Sublime Text 3 # # Written by NotSqrt # Copyright (c) 2013 NotSqrt # # License: MIT # """This module exports the Cppcheck plugin class.""" from SublimeLinter.lint import Linter, util class Cppcheck(Linter): """Provides an interface to cpp...
Add support to C files
Add support to C files
Python
mit
SublimeLinter/SublimeLinter-cppcheck,ftoulemon/SublimeLinter-cppcheck
301a70469dba6fdfe8d72d3d70fa75e4146756c6
integration-test/843-normalize-underscore.py
integration-test/843-normalize-underscore.py
# http://www.openstreetmap.org/way/219071307 assert_has_feature( 16, 10478, 25338, 'roads', { 'id': 219071307, 'kind': 'minor_road', 'service': 'drive_through' }) # http://www.openstreetmap.org/way/258020271 assert_has_feature( 16, 11077, 25458, 'roads', { 'id': 258020271, 'kind': 'aerialway', 'aerialw...
# http://www.openstreetmap.org/way/219071307 assert_has_feature( 16, 10478, 25338, 'roads', { 'id': 219071307, 'kind': 'minor_road', 'service': 'drive_through' }) # http://www.openstreetmap.org/way/258020271 assert_has_feature( 16, 11077, 25458, 'roads', { 'id': 258020271, 'kind': 'aerialway', 'aerialw...
Simplify test to check for no aerialway property
Simplify test to check for no aerialway property
Python
mit
mapzen/vector-datasource,mapzen/vector-datasource,mapzen/vector-datasource
a2fef3f2090f0df5425cf21a70d24c77224eae17
tests/cyclus_tools.py
tests/cyclus_tools.py
#! /usr/bin/env python from tools import check_cmd def run_cyclus(cyclus, cwd, sim_files): """Runs cyclus with various inputs and creates output databases """ for sim_input, sim_output in sim_files: holdsrtn = [1] # needed because nose does not send() to test generator cmd = [cyclus, ...
#! /usr/bin/env python import os from tools import check_cmd def run_cyclus(cyclus, cwd, sim_files): """Runs cyclus with various inputs and creates output databases """ for sim_input, sim_output in sim_files: holdsrtn = [1] # needed because nose does not send() to test generator # ma...
Add a check if the target output directories exist
Add a check if the target output directories exist
Python
bsd-3-clause
rwcarlsen/cycamore,Baaaaam/cyCLASS,jlittell/cycamore,jlittell/cycamore,gonuke/cycamore,jlittell/cycamore,Baaaaam/cyCLASS,rwcarlsen/cycamore,Baaaaam/cyBaM,cyclus/cycaless,jlittell/cycamore,Baaaaam/cyBaM,rwcarlsen/cycamore,Baaaaam/cycamore,gonuke/cycamore,Baaaaam/cyBaM,gonuke/cycamore,cyclus/cycaless,rwcarlsen/cycamore,B...
7bf477f2ce728ed4af4163a0a96f9ec1b3b76d8d
tests/cyclus_tools.py
tests/cyclus_tools.py
#! /usr/bin/env python import os from tools import check_cmd def run_cyclus(cyclus, cwd, sim_files): """Runs cyclus with various inputs and creates output databases """ for sim_input, sim_output in sim_files: holdsrtn = [1] # needed because nose does not send() to test generator # ma...
#! /usr/bin/env python import os from tools import check_cmd def run_cyclus(cyclus, cwd, sim_files): """Runs cyclus with various inputs and creates output databases """ for sim_input, sim_output in sim_files: holdsrtn = [1] # needed because nose does not send() to test generator # ma...
Correct a bug in creating directories as needed for output.
Correct a bug in creating directories as needed for output.
Python
bsd-3-clause
Baaaaam/cyBaM,Baaaaam/cyBaM,Baaaaam/cyBaM,rwcarlsen/cycamore,rwcarlsen/cycamore,gonuke/cycamore,Baaaaam/cycamore,Baaaaam/cyBaM,jlittell/cycamore,rwcarlsen/cycamore,jlittell/cycamore,cyclus/cycaless,gonuke/cycamore,Baaaaam/cyCLASS,jlittell/cycamore,gonuke/cycamore,jlittell/cycamore,Baaaaam/cycamore,gonuke/cycamore,cyclu...
ad31b6f0226ecd642289f54ec649964aeb9b5799
tests/sanity_tests.py
tests/sanity_tests.py
import filecmp import os import tempfile import unittest import isomedia TESTDATA = os.path.join(os.path.dirname(__file__), 'testdata') class TestSanity(unittest.TestCase): def test_sanity(self): mp4filename = os.path.join(TESTDATA, 'loop_circle.mp4') mp4file = open(mp4filename, 'rb') iso...
import filecmp import os import tempfile import unittest import isomedia TESTDATA = os.path.join(os.path.dirname(__file__), 'testdata') class TestSanity(unittest.TestCase): def test_sanity(self): mp4filename = os.path.join(TESTDATA, 'loop_circle.mp4') mp4file = open(mp4filename, 'rb') iso...
Clean up more in tests
Clean up more in tests
Python
mit
flxf/isomedia
4a32fe3b3735df9ec56a4ca1769268740ef5d8f4
tests/test_to_html.py
tests/test_to_html.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals import unittest class ToHTMLTest(unittest.TestCase): SAMPLE = "Проверяем *CommonMark*.\n\nВставляем `код`.\nИ другие штуки." def setUp(self): from paka.cmark import to_html self.func = to_html def check(self, source, expe...
# -*- coding: utf-8 -*- from __future__ import unicode_literals import unittest class ToHTMLTest(unittest.TestCase): SAMPLE = ( "Проверяем *CommonMark*.\n\nВставляем `код`.\nИ другие штуки.\n\n" "<p>Test of <em>HTML</em>.</p>") def setUp(self): from paka.cmark import to_html ...
Add HTML fragment to test sample
Add HTML fragment to test sample
Python
bsd-3-clause
PavloKapyshin/paka.cmark,PavloKapyshin/paka.cmark,PavloKapyshin/paka.cmark
005e7175f5fcd7e74637790e66e5cf46825195f6
tests/cupy_tests/cuda_tests/test_nccl.py
tests/cupy_tests/cuda_tests/test_nccl.py
import unittest from cupy import cuda from cupy.testing import attr @unittest.skipUnless(cuda.nccl_enabled, 'nccl is not installed') class TestNCCL(unittest.TestCase): @attr.gpu def test_single_proc_ring(self): id = cuda.nccl.get_unique_id() comm = cuda.nccl.NcclCommunicator(1, id, 0) ...
import unittest from cupy import cuda from cupy.testing import attr @unittest.skipUnless(cuda.nccl_enabled, 'nccl is not installed') class TestNCCL(unittest.TestCase): @attr.gpu def test_single_proc_ring(self): id = cuda.nccl.get_unique_id() comm = cuda.nccl.NcclCommunicator(1, id, 0) ...
Add a test for initAll()
Add a test for initAll()
Python
mit
cupy/cupy,cupy/cupy,cupy/cupy,cupy/cupy
620d59b82e8a5c98fd4568217c74b485f802ac94
tests/integration/test_authentication.py
tests/integration/test_authentication.py
from pyutrack import Connection from pyutrack import Credentials from pyutrack.errors import LoginError from tests.integration import IntegrationTest class AuthenticationTests(IntegrationTest): def test_successful_authentication(self): connection = Connection( credentials=Credentials(username=...
from pyutrack import Connection from pyutrack import Credentials from pyutrack.errors import LoginError from tests.integration import IntegrationTest class AuthenticationTests(IntegrationTest): def test_successful_authentication(self): connection = Connection( credentials=Credentials(username=...
Fix order of assertion arguments
Fix order of assertion arguments
Python
mit
alisaifee/pyutrack,alisaifee/pyutrack
245a6b190c1ad3c5e380c5957d6b98593fdb4006
logserver/__main__.py
logserver/__main__.py
from argparse import ArgumentParser import logging from . import run_server from .handlers import SQLiteHandler parser = ArgumentParser( description="Run a standalone log server using a SQLite database.") parser.add_argument("-p", "--port", default=9123, help="Port to listen on") parser.add_argument("-t", "--tabl...
from argparse import ArgumentParser import logging from . import run_server from .handlers import SQLiteHandler parser = ArgumentParser( description="Run a standalone log server using a SQLite database.") parser.add_argument("-p", "--port", default=9123, help="Port to listen on") parser.add_argument("-t", "--tabl...
Format messages in stream handler
Format messages in stream handler
Python
mit
mivade/logserver
0ac5a45c27b574c73d2660e96543220e274e1c64
magpy/server/_ejdb.py
magpy/server/_ejdb.py
"""EJDB driver for Magpy. Currently does not do much except support certain command line scripts. """ import os import pyejdb class Database(object): """Simple database connection for use in serverside scripts etc.""" def __init__(self, database_name=None, config_file=None): ...
"""EJDB driver for Magpy. Currently does not do much except support certain command line scripts. """ import os import pyejdb class Database(object): """Simple database connection for use in serverside scripts etc.""" def __init__(self, database_name=None, config_file=None): ...
Deal with the weirdnesses of ejdb.
Deal with the weirdnesses of ejdb.
Python
bsd-3-clause
zeth/magpy,catsmith/magpy,zeth/magpy,catsmith/magpy
8a0f17eea757f2001ec9d9579a413ab852549d39
tavenner.py
tavenner.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import errno import zipfile import sys import hashlib def main(): from urllib2 import Request, urlopen, HTTPError url_base = 'http://ethicssearch.dls.virginia.gov/ViewFormBinary.aspx?filingid=' errors = 0 i = 1 while True: req ...
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import errno import zipfile import sys import hashlib output_dir = 'output' def main(): # Make our output directory, if it doesn't exist. if not os.path.exists(output_dir): os.makedirs(output_dir) from urllib2 import Request, urlopen, ...
Store output in a subdirectory
Store output in a subdirectory
Python
mit
openva/tavenner
d2e03bf76f585dc1025b5a94be0327284f8d5fa2
Left_pare.py
Left_pare.py
# This macro is to remove 1 character form selected line on the left. # Useful to clean code copied from diff file. # # Author: Nguyễn Hồng Quân (ng.hong.quan@gmail.com) from xpcom import components viewSvc = components.classes["@activestate.com/koViewService;1"]\ .getService(components.interfaces.koIViewService) ...
# This macro is to remove 1 character form selected line on the left. # Useful to clean code copied from diff file. # # Author: Nguyễn Hồng Quân (ng.hong.quan@gmail.com) from xpcom import components viewSvc = components.classes["@activestate.com/koViewService;1"]\ .getService(components.interfaces.koIViewService) ...
Correct selecting text by length when text is Unicode.
Correct selecting text by length when text is Unicode.
Python
mpl-2.0
Komodo/macros,Komodo/macros
0a884d3c38cb1449a6fa5c650ed06cde647de4a8
settings/sqlite.py
settings/sqlite.py
from .base import * import os.path DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(SITE_ROOT, 'dev.db'), } } SESSION_COOKIE_DOMAIN = None HAYSTACK_SOLR_URL = 'http://localhost:8983/solr'
from .base import * import os.path DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(SITE_ROOT, 'dev.db'), } } SESSION_COOKIE_DOMAIN = None HAYSTACK_SOLR_URL = 'http://localhost:8983/solr' try: ...
Allow local settings override as well.
Allow local settings override as well.
Python
mit
singingwolfboy/readthedocs.org,laplaceliu/readthedocs.org,kenwang76/readthedocs.org,hach-que/readthedocs.org,fujita-shintaro/readthedocs.org,rtfd/readthedocs.org,tddv/readthedocs.org,raven47git/readthedocs.org,mhils/readthedocs.org,royalwang/readthedocs.org,johncosta/private-readthedocs.org,asampat3090/readthedocs.org,...
14d170eece4e8bb105f5316fb0c6e672a3253b08
py3flowtools/flowtools_wrapper.py
py3flowtools/flowtools_wrapper.py
# flowtools_wrapper.py # Copyright 2014 Bo Bayles (bbayles@gmail.com) # See http://github.com/bbayles/py3flowtools for documentation and license from __future__ import division, print_function, unicode_literals import io import os import sys from .flow_line import FlowLine if sys.version_info.major < 3: import ...
# flowtools_wrapper.py # Copyright 2014 Bo Bayles (bbayles@gmail.com) # See http://github.com/bbayles/py3flowtools for documentation and license from __future__ import division, print_function, unicode_literals import io import os import sys from .flow_line import FlowLine if sys.version_info.major < 3: import ...
Convert FlowToolsLog to a class
Convert FlowToolsLog to a class
Python
mit
bbayles/py3flowtools
5b6bd6cacc7032bc6a830707374b1448861e5d08
plugin.py
plugin.py
import sublime def plugin_loaded(): # Native package causes some conflicts. # Thanks https://github.com/SublimeText-Markdown/MarkdownEditing disable_native_php_package() def disable_native_php_package(): settings = sublime.load_settings('Preferences.sublime-settings') ignored_packages = settings.g...
import sublime def plugin_loaded(): # Native package causes some conflicts. # Thanks https://github.com/SublimeText-Markdown/MarkdownEditing disable_native_php_package() def disable_native_php_package(): settings = sublime.load_settings('Preferences.sublime-settings') ignored_packages = settings.g...
Sort ignored packages when adding native PHP package
Sort ignored packages when adding native PHP package
Python
bsd-3-clause
gerardroche/sublime-php-grammar,gerardroche/sublime-php-grammar
76e766998984da126de4cb6121c07690fbdeeba1
pystil/data/graph/line.py
pystil/data/graph/line.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (C) 2011 by Florian Mounier, Kozea # This file is part of pystil, licensed under a 3-clause BSD license. """Treat line data""" from pystil.data.utils import make_time_serie, on, between from pystil.db import db, count, Visit, distinct def process_data(site,...
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (C) 2011 by Florian Mounier, Kozea # This file is part of pystil, licensed under a 3-clause BSD license. """Treat line data""" from pystil.data.utils import make_time_serie, on, between from pystil.db import db, count, Visit, distinct def process_data(site,...
Fix the new/unique visits (at least!)
Fix the new/unique visits (at least!)
Python
bsd-3-clause
Kozea/pystil,Kozea/pystil,Kozea/pystil,Kozea/pystil,Kozea/pystil
268467c5eb12e92a031d22e3e0515e9d6fc264b7
ofgem_certificates.py
ofgem_certificates.py
#!/usr/bin/env python # coding=utf-8 # # Copyright 2013 david reid <zathrasorama@gmail.com> # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # #     http://www.apache.org/licenses/LICENSE-2.0 ...
#!/usr/bin/env python # coding=utf-8 # # Copyright 2013 david reid <zathrasorama@gmail.com> # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # #     http://www.apache.org/licenses/LICENSE-2.0 ...
Update the certificate script to accept month & year
Update the certificate script to accept month & year
Python
unlicense
zathras777/pywind,zathras777/pywind
695b3f628b56cd1dbe050f07692559ff3685290c
templatefinder/__init__.py
templatefinder/__init__.py
from __future__ import absolute_import from .utils import * VERSION = (0, 5,)
from __future__ import absolute_import # this is required for setup.py to work try: from .utils import * except ImportError: pass VERSION = (0, 5, 1,)
Fix setup.py for installs without Django
Fix setup.py for installs without Django
Python
bsd-2-clause
TyMaszWeb/django-template-finder
a764e58549284b8af1b3978676b8ee121fd918e3
thecure/levels/__init__.py
thecure/levels/__init__.py
from thecure.levels.base import * from thecure.levels.cliff import Cliff from thecure.levels.overworld import Overworld def get_levels(): return [Cliff] #return [Overworld, Cliff]
from thecure.levels.base import * from thecure.levels.cliff import Cliff from thecure.levels.overworld import Overworld def get_levels(): return [Overworld, Cliff]
Set the overworld as the default level again.
Set the overworld as the default level again.
Python
mit
chipx86/the-cure
9b239f3484f3ec3e03ad1fda2a76d35852f662e6
_releng/deploy.py
_releng/deploy.py
#!/usr/bin/env python3 import os import subprocess PUBLIC_URL = "https://frida.re" BUCKET_URI = "s3://frida.re" MAX_PURGES_PER_REQUEST = 30 def main(): repo_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) urls = [] listing = subprocess.check_output([ "s3cmd", "ls", ...
#!/usr/bin/env python3 import os import subprocess PUBLIC_URL = "https://frida.re" BUCKET_URI = "s3://frida.re" MAX_PURGES_PER_REQUEST = 30 def main(): repo_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) urls = [] listing = subprocess.check_output([ "s3cmd", "ls", ...
Make cache purging logic a bit more thorough
Make cache purging logic a bit more thorough
Python
mit
frida/frida-website,frida/frida-website,frida/frida-website
fa42219c1e6763f3adfc1f6ede4080f769e476a6
tests/test_mongo.py
tests/test_mongo.py
#!/usr/bin/env python # coding=utf8 from uuid import uuid4 as uuid import pytest pymongo = pytest.importorskip('pymongo') from simplekv.db.mongo import MongoStore from basic_store import BasicStore class TestMongoDB(BasicStore): @pytest.fixture def db_name(self): return '_simplekv_test_{}'.format(u...
#!/usr/bin/env python # coding=utf8 from uuid import uuid4 as uuid import pytest pymongo = pytest.importorskip('pymongo') from simplekv.db.mongo import MongoStore from basic_store import BasicStore class TestMongoDB(BasicStore): @pytest.fixture def db_name(self): return '_simplekv_test_{}'.format(u...
Add database table name to MongoStore tests.
Add database table name to MongoStore tests.
Python
mit
fmarczin/simplekv,karteek/simplekv,mbr/simplekv,mbr/simplekv,fmarczin/simplekv,karteek/simplekv
af6c31d09aef686ba896b2a2c74fbb88cc7f1be0
tests/test_utils.py
tests/test_utils.py
#!/usr/bin/python2.5 # # Copyright 2008 the Melange authors. # # 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...
#!/usr/bin/python2.5 # # Copyright 2008 the Melange authors. # # 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...
Add a start and end method to MockRequest
Add a start and end method to MockRequest
Python
apache-2.0
SRabbelier/Melange,SRabbelier/Melange,SRabbelier/Melange,SRabbelier/Melange,SRabbelier/Melange,SRabbelier/Melange,SRabbelier/Melange,SRabbelier/Melange,SRabbelier/Melange
bff9e9c8c72be580bca4d82abf2d7931379f8ebf
scripts/get_services_to_deploy.py
scripts/get_services_to_deploy.py
#!/usr/bin/env python import requests import json import sys import argparse parser = argparse.ArgumentParser('Queries Monorail to get the services and deployNotes where a list of Pull requests will be deployed') parser.add_argument('--url', help='URL where Monorail is located') parser.add_argument('--pr', help='List...
#!/usr/bin/env python import requests import json import sys import argparse parser = argparse.ArgumentParser('Queries Monorail to get the services and deployNotes where a list of Pull requests will be deployed') parser.add_argument('--url', help='URL where Monorail is located') parser.add_argument('--pr', help='List...
Print variables for initial testing
Print variables for initial testing
Python
mit
AudienseCo/monorail,AudienseCo/monorail
e3545cf444aea043fa892caeaff5a66ce893a0bb
misc/move-objects.py
misc/move-objects.py
from sys import argv from axiom.store import Store from entropy.store import ImmutableObject from entropy.util import getAppStore def moveObjects(appStore, start, limit=1000): obj = None for obj in appStore.query( ImmutableObject, ImmutableObject.storeID >= start, limit=li...
from sys import argv from axiom.store import Store from entropy.store import ImmutableObject from entropy.util import getAppStore def moveObjects(appStore, start, limit): obj = None for obj in appStore.query( ImmutableObject, ImmutableObject.storeID >= start, limit=limit):...
Make limit a command-line parameter too.
Make limit a command-line parameter too.
Python
mit
fusionapp/entropy
b1382e380016c9034826b090540275ce2bbe3a95
src/ggrc_basic_permissions/roles/ProgramAuditReader.py
src/ggrc_basic_permissions/roles/ProgramAuditReader.py
# Copyright (C) 2015 Google Inc., authors, and contributors <see AUTHORS file> # Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file> # Created By: anze@reciprocitylabs.com # Maintained By: anze@reciprocitylabs.com scope = "AuditImplied" description = """ A user with the ProgramReader role fo...
# Copyright (C) 2015 Google Inc., authors, and contributors <see AUTHORS file> # Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file> # Created By: anze@reciprocitylabs.com # Maintained By: anze@reciprocitylabs.com scope = "AuditImplied" description = """ A user with the ProgramReader role fo...
Allow Program Readers to view comments
Allow Program Readers to view comments
Python
apache-2.0
jmakov/ggrc-core,plamut/ggrc-core,NejcZupec/ggrc-core,j0gurt/ggrc-core,VinnieJohns/ggrc-core,AleksNeStu/ggrc-core,kr41/ggrc-core,selahssea/ggrc-core,VinnieJohns/ggrc-core,kr41/ggrc-core,NejcZupec/ggrc-core,edofic/ggrc-core,jmakov/ggrc-core,NejcZupec/ggrc-core,kr41/ggrc-core,j0gurt/ggrc-core,VinnieJohns/ggrc-core,josthk...
d0e7d3578fe79432ad2b2cc62be2203d4ff36014
examples/charts/file/cat_heatmap.py
examples/charts/file/cat_heatmap.py
from bokeh.charts import HeatMap, output_file, show from bokeh.sampledata.unemployment1948 import data # pandas magic df = data[data.columns[:-2]] df2 = df.set_index(df[df.columns[0]].astype(str)) df2.drop(df.columns[0], axis=1, inplace=True) df3 = df2.transpose() output_file("cat_heatmap.html") hm = HeatMap(df3, ti...
from bokeh.charts import HeatMap, output_file, show from bokeh.palettes import YlOrRd9 as palette from bokeh.sampledata.unemployment1948 import data # pandas magic df = data[data.columns[:-1]] df2 = df.set_index(df[df.columns[0]].astype(str)) df2.drop(df.columns[0], axis=1, inplace=True) df3 = df2.transpose() output_...
Use all the months of the year and tweak palette.
Use all the months of the year and tweak palette. - Picked a continuous palette and reversed as better for the data.
Python
bsd-3-clause
abele/bokeh,laurent-george/bokeh,azjps/bokeh,josherick/bokeh,rs2/bokeh,timsnyder/bokeh,draperjames/bokeh,matbra/bokeh,ptitjano/bokeh,DuCorey/bokeh,awanke/bokeh,akloster/bokeh,xguse/bokeh,stonebig/bokeh,KasperPRasmussen/bokeh,phobson/bokeh,stonebig/bokeh,CrazyGuo/bokeh,ericmjl/bokeh,rhiever/bokeh,caseyclements/bokeh,rox...
a7c5c9d27d29e14ebb2d314890b40eab318501ac
dialogos/admin.py
dialogos/admin.py
from django.contrib import admin from dialogos.models import Comment class CommentAdmin(admin.ModelAdmin): list_display = ['author', 'content_type', 'public'] list_filter = ['public', 'content_type'] admin.site.register(Comment, CommentAdmin)
from django.contrib import admin from dialogos.models import Comment class CommentAdmin(admin.ModelAdmin): list_display = ["author", "content_type", "public"] list_filter = ["public", "content_type"] admin.site.register(Comment, CommentAdmin)
Update style to match Pinax conventions
Update style to match Pinax conventions
Python
mit
pinax/pinax-comments,rizumu/dialogos,GeoNode/geonode-dialogos,eldarion/dialogos,georgedorn/dialogos,pinax/pinax-comments
c09465f6f5d70789ca01470015985cbbdb465db9
problem_2/solution.py
problem_2/solution.py
from timeit import timeit def sum_even_fibonacci_numbers_1(): f1, f2, s, = 0, 1, 0, while f2 < 4000000: f2, f1 = f1, f1 + f2 if f2 % 2 == 0: s += f2 return s def sum_even_fibonacci_numbers_2(): s, a, b = 0, 1, 1 c = a + b while c < 4000000: s += c a = ...
import time def sum_even_fibonacci_numbers_1(): f1, f2, s, = 0, 1, 0, while f2 < 4000000: f2, f1 = f1, f1 + f2 if f2 % 2 == 0: s += f2 return s def sum_even_fibonacci_numbers_2(): s, a, b = 0, 1, 1 c = a + b while c < 4000000: s += c a = b + c ...
Add better timing for python implementation of problem 2
Add better timing for python implementation of problem 2
Python
mit
mdsrosa/project_euler,mdsrosa/project_euler,mdsrosa/project_euler,mdsrosa/project_euler,mdsrosa/project_euler,mdsrosa/project_euler,mdsrosa/project_euler,mdsrosa/project_euler
a612a245937781e86391e5c3ec8a740f36b405ce
problems/19/Solver.py
problems/19/Solver.py
class Solver: def solve(self, start_number): recipient = 1 remaining = start_number power = 1 while remaining > 1: new_remaining = remaining // 2 remaining_was_odd = remaining % 2 power *= 2 remaining = new_remaining if rema...
class Solver: def __init__(self): self.next_elves = {} def solve(self, start_number): recipient = 1 remaining = start_number power = 1 while remaining > 1: new_remaining = remaining // 2 remaining_was_odd = remaining % 2 power *= 2 ...
Refactor to use linked list
Refactor to use linked list
Python
mit
tmct/adventOfCode2016
44191360586beeec04a4abc8a4aa262bc5ec052d
odinweb/exceptions.py
odinweb/exceptions.py
# -*- coding: utf-8 -*- """ Exceptions ~~~~~~~~~~ """ from .constants import HTTPStatus from .resources import Error class ImmediateHttpResponse(Exception): """ A response that should be returned immediately. """ def __init__(self, resource, status=HTTPStatus.OK, headers=None): self.resource ...
# -*- coding: utf-8 -*- """ Exceptions ~~~~~~~~~~ """ from .constants import HTTPStatus from .resources import Error __all__ = ('ImmediateHttpResponse', 'HttpError', 'PermissionDenied') class ImmediateHttpResponse(Exception): """ A response that should be returned immediately. """ def __init__(self,...
Refactor HttpError to use Error.from_status helper
Refactor HttpError to use Error.from_status helper
Python
bsd-3-clause
python-odin/odinweb,python-odin/odinweb
7ae151e277d2cb03037d40e1598b190ba4736433
dthm4kaiako/events/views.py
dthm4kaiako/events/views.py
"""Views for events application.""" from django.views import generic from django.utils.timezone import now from events.models import ( Event, Location, ) class HomeView(generic.TemplateView): """View for event homepage.""" template_name = 'events/home.html' def get_context_data(self, **kwargs):...
"""Views for events application.""" from django.views import generic from django.utils.timezone import now from events.models import ( Event, Location, ) class HomeView(generic.TemplateView): """View for event homepage.""" template_name = 'events/home.html' def get_context_data(self, **kwargs):...
Reduce SQL queries for events homepage
Reduce SQL queries for events homepage
Python
mit
uccser/cs4teachers,uccser/cs4teachers,uccser/cs4teachers,uccser/cs4teachers
834349fc6cc2f6d281f03f339dab116b897615fc
knowledge_repo/postprocessors/format_checks.py
knowledge_repo/postprocessors/format_checks.py
from ..constants import FORMAT_CHECKS from ..post import HEADER_OPTIONAL_FIELD_TYPES, HEADER_REQUIRED_FIELD_TYPES from ..postprocessor import KnowledgePostProcessor class FormatChecks(KnowledgePostProcessor): _registry_keys = [FORMAT_CHECKS] def process(self, kp): headers = kp.headers for fie...
from ..constants import FORMAT_CHECKS from ..post import HEADER_OPTIONAL_FIELD_TYPES, HEADER_REQUIRED_FIELD_TYPES from ..postprocessor import KnowledgePostProcessor class FormatChecks(KnowledgePostProcessor): _registry_keys = [FORMAT_CHECKS] def process(self, kp): headers = kp.headers for fie...
Refactor to avoid duplicate code
Refactor to avoid duplicate code
Python
apache-2.0
airbnb/knowledge-repo,airbnb/knowledge-repo,airbnb/knowledge-repo,airbnb/knowledge-repo,airbnb/knowledge-repo
5d2110059731069a6a29a31d2b9f02bb2743e90b
scripts/cleanup-images.py
scripts/cleanup-images.py
#!/usr/bin/python import os, sys import pwd if os.geteuid(): print >> sys.stderr, "Script must be run as root to manipulate permissions" sys.exit(1) from conary import dbstore from mint import config apacheGid = pwd.getpwnam('apache')[3] isogenUid = pwd.getpwnam('isogen')[2] cfg = config.MintConfig() cfg.r...
#!/usr/bin/python import os, sys import pwd if os.geteuid(): print >> sys.stderr, "Script must be run as root to manipulate permissions" sys.exit(1) from conary import dbstore from mint import config apacheGid = pwd.getpwnam('apache')[3] isogenUid = pwd.getpwnam('isogen')[2] cfg = config.MintConfig() cfg.r...
Kill off another hardcoded path
Kill off another hardcoded path
Python
apache-2.0
sassoftware/mint,sassoftware/mint,sassoftware/mint,sassoftware/mint,sassoftware/mint
eabc02aed1cd5a109554f48bfb82f185e392c404
remo/base/middleware.py
remo/base/middleware.py
from django.conf import settings from django.contrib import messages from django.core.urlresolvers import reverse from django.shortcuts import redirect class RegisterMiddleware(object): """Middleware to enforce users to complete registration. When a user logins and has the registration_complete field in his ...
from django.conf import settings from django.contrib import messages from django.core.urlresolvers import reverse from django.shortcuts import redirect class RegisterMiddleware(object): """Middleware to enforce users to complete registration. When a user logins and has the registration_complete field in his ...
Add 'oidc_logout' in allowed urls.
Add 'oidc_logout' in allowed urls.
Python
bsd-3-clause
flamingspaz/remo,akatsoulas/remo,mozilla/remo,Mte90/remo,flamingspaz/remo,akatsoulas/remo,Mte90/remo,Mte90/remo,flamingspaz/remo,mozilla/remo,akatsoulas/remo,tsmrachel/remo,tsmrachel/remo,akatsoulas/remo,tsmrachel/remo,tsmrachel/remo,mozilla/remo,flamingspaz/remo,Mte90/remo,mozilla/remo
5ab34396d4f494f884ddf98fb993bcf1b928216e
api/citations/urls.py
api/citations/urls.py
from django.conf.urls import url from api.citations import views urlpatterns = [ url(r'^$', views.CitationList.as_view(), name=views.CitationList.view_name), url(r'^(?P<citation_id>\w+)/$', views.CitationDetail.as_view(), name=views.CitationDetail.view_name), ]
from django.conf.urls import url from api.citations import views urlpatterns = [ url(r'^styles/$', views.CitationList.as_view(), name=views.CitationList.view_name), url(r'^styles/(?P<citation_id>\w+)/$', views.CitationDetail.as_view(), name=views.CitationDetail.view_name), ]
Add styles prefix to match api v1
Add styles prefix to match api v1
Python
apache-2.0
mattclark/osf.io,chennan47/osf.io,rdhyee/osf.io,alexschiller/osf.io,mluo613/osf.io,HalcyonChimera/osf.io,TomBaxter/osf.io,laurenrevere/osf.io,Nesiehr/osf.io,mfraezz/osf.io,caneruguz/osf.io,crcresearch/osf.io,sloria/osf.io,adlius/osf.io,caseyrollins/osf.io,monikagrabowska/osf.io,caseyrollins/osf.io,brianjgeiger/osf.io,i...
3059f6448e0fc2dd49ad38306f8efedc734b3aab
api/projects/tasks.py
api/projects/tasks.py
# -*- coding: utf-8 -*- from __future__ import absolute_import, division, print_function import logging from api.settings import CeleryTasks, Intervals from api.celery_api import app as celery_app from experiments.tasks import build_experiment from projects.models import ExperimentGroup logger = logging.getLogger('p...
# -*- coding: utf-8 -*- from __future__ import absolute_import, division, print_function import logging from api.settings import CeleryTasks, Intervals from api.celery_api import app as celery_app from experiments.tasks import build_experiment from projects.models import ExperimentGroup logger = logging.getLogger('p...
Fix retry for experiment group
Fix retry for experiment group
Python
apache-2.0
polyaxon/polyaxon,polyaxon/polyaxon,polyaxon/polyaxon
10655be79d9ab65f86939d0bd085197e0e35b39d
CodeFights/knapsackLight.py
CodeFights/knapsackLight.py
#!/usr/local/bin/python # Code Fights Knapsack Problem def knapsackLight(value1, weight1, value2, weight2, maxW): if weight1 + weight2 <= maxW: return value1 + value2 else: return max([v for v, w in zip((value1, value2), (weight1, weight2)) if w <= maxW] + [0]) def main():...
#!/usr/local/bin/python # Code Fights Knapsack Problem def knapsackLight(value1, weight1, value2, weight2, maxW): if weight1 + weight2 <= maxW: return value1 + value2 else: return max([v for v, w in zip((value1, value2), (weight1, weight2)) if w <= maxW] + [0]) def main():...
Format Code Fights knapsack light problem
Format Code Fights knapsack light problem
Python
mit
HKuz/Test_Code
82796dfb24c3e65b669d4336948e76e2a64cf73f
LR/lr/model/node_service.py
LR/lr/model/node_service.py
#!/usr/bin/pyton # Copyright 2011 Lockheed Martin ''' Created on Mar 17, 2011 Base model class for learning registry data model @author: jpoyau ''' from base_model import createBaseModel, ModelParser, defaultCouchServer, appConfig from pylons import * import datetime, logging log = logging.getLogger(__name__)...
#!/usr/bin/pyton # Copyright 2011 Lockheed Martin ''' Created on Mar 17, 2011 Base model class for learning registry data model @author: jpoyau ''' from base_model import createBaseModel, ModelParser, defaultCouchServer, appConfig from pylons import * import datetime, logging log = logging.getLogger(__name__)...
Add 'distribute' to the node services
Add 'distribute' to the node services
Python
apache-2.0
jimklo/LearningRegistry,jimklo/LearningRegistry,LearningRegistry/LearningRegistry,LearningRegistry/LearningRegistry,jimklo/LearningRegistry,jimklo/LearningRegistry,jimklo/LearningRegistry,jimklo/LearningRegistry,LearningRegistry/LearningRegistry,LearningRegistry/LearningRegistry,jimklo/LearningRegistry,jimklo/LearningR...
dcd97762b65df37b5f7c4724892ab76bb631762f
src/havenctl/havenctl/launcher.py
src/havenctl/havenctl/launcher.py
import sys import getopt from ctl import HavenCtl def print_version(): import pkg_resources # part of setuptools version = pkg_resources.require("havenctl")[0].version print(version) def print_usage(): print """ Usage: havenctl [-a <remote_address> | --address=<remote_address>] [-p <...
import sys import getopt from ctl import HavenCtl def print_version(): import pkg_resources # part of setuptools version = pkg_resources.require("havenctl")[0].version print(version) def print_usage(): print """ Usage: havenctl [-a <remote_address> | --address=<remote_address>] [-p <...
Make plain repl work again.
Make plain repl work again.
Python
apache-2.0
fintler/tomatodb,fintler/tomatodb,fintler/tomatodb
7ce0478dafebb7f6c52150a3563ae4cc59d68d6e
mass_mailing_switzerland/models/mailchimp_merge_fields.py
mass_mailing_switzerland/models/mailchimp_merge_fields.py
############################################################################## # # Copyright (C) 2021 Compassion CH (http://www.compassion.ch) # Releasing children from poverty in Jesus' name # @author: Emanuel Cino <ecino@compassion.ch> # # The licence is in the file __manifest__.py # #####################...
############################################################################## # # Copyright (C) 2021 Compassion CH (http://www.compassion.ch) # Releasing children from poverty in Jesus' name # @author: Emanuel Cino <ecino@compassion.ch> # # The licence is in the file __manifest__.py # #####################...
FIX mailing_contact merge fields value
FIX mailing_contact merge fields value
Python
agpl-3.0
CompassionCH/compassion-switzerland,CompassionCH/compassion-switzerland,eicher31/compassion-switzerland,CompassionCH/compassion-switzerland,eicher31/compassion-switzerland,eicher31/compassion-switzerland
2ad16c44adb20e9ba023e873149d67068504c34c
saleor/cart/__init__.py
saleor/cart/__init__.py
from __future__ import unicode_literals from django.utils.translation import pgettext from satchless import cart from satchless.item import ItemList, ClassifyingPartitioner from ..product.models import DigitalShip class ShippedGroup(ItemList): ''' Group for shippable products. ''' pass class Digit...
from __future__ import unicode_literals from django.utils.translation import pgettext from satchless import cart from satchless.item import ItemList, ClassifyingPartitioner from ..product.models import DigitalShip class ShippedGroup(ItemList): ''' Group for shippable products. ''' pass class Digit...
Add ability to clear cart
Add ability to clear cart
Python
bsd-3-clause
avorio/saleor,laosunhust/saleor,hongquan/saleor,maferelo/saleor,avorio/saleor,car3oon/saleor,tfroehlich82/saleor,UITools/saleor,car3oon/saleor,Drekscott/Motlaesaleor,maferelo/saleor,hongquan/saleor,josesanch/saleor,taedori81/saleor,KenMutemi/saleor,tfroehlich82/saleor,spartonia/saleor,mociepka/saleor,itbabu/saleor,UITo...
5f9cf67c473ef7d304da067b70b56d77f71ca4fa
web/impact/impact/middleware/method_override_middleware.py
web/impact/impact/middleware/method_override_middleware.py
# MIT License # Copyright (c) 2017 MassChallenge, Inc. # METHOD_OVERRIDE_HEADER = 'HTTP_X_HTTP_METHOD_OVERRIDE' METHOD_OVERRIDE_HEADER = 'X-HTTP-Method-Override' class MethodOverrideMiddleware(object): def process_request(self, request): if request.method != 'POST': return if METHOD_OV...
# MIT License # Copyright (c) 2017 MassChallenge, Inc. METHOD_OVERRIDE_HEADER = 'HTTP_X_HTTP_METHOD_OVERRIDE' class MethodOverrideMiddleware(object): def process_request(self, request): if request.method != 'POST': return if METHOD_OVERRIDE_HEADER not in request.META: retur...
Revert Changes To Middleware To Prevent Build Hangup
[AC-4959] Revert Changes To Middleware To Prevent Build Hangup
Python
mit
masschallenge/impact-api,masschallenge/impact-api,masschallenge/impact-api,masschallenge/impact-api
42a0dd7f808b87035f8067c5d0ad4bb688632135
ecmd-core/pyapi/init/__init__.py
ecmd-core/pyapi/init/__init__.py
# import the right SWIG module depending on Python version from sys import version_info from sys import path as sys_path from os import path as os_path if version_info[0] >= 3: sys_path.insert(0, os_path.join(os_path.dirname(__file__), "python3")) from .python3 import * else: sys_path.insert(0, os_path.join...
# import the right SWIG module depending on Python version from sys import version_info from sys import path as sys_path from os import path as os_path if version_info[0] >= 3: sys_path.append(os_path.join(os_path.dirname(__file__), "python3")) from .python3 import * else: sys_path.append(os_path.join(os_pa...
Append version specific path to os.path rather than prepend
pyapi: Append version specific path to os.path rather than prepend Other code might depend on os.path[0] being the path of the executed script, and there is no need for our new path to be at the front.
Python
apache-2.0
open-power/eCMD,mklight/eCMD,mklight/eCMD,open-power/eCMD,mklight/eCMD,mklight/eCMD,open-power/eCMD,open-power/eCMD,open-power/eCMD,mklight/eCMD
b03c8ebe8cc426e21b45f4de0d8d6e7176a4a647
api/admin.py
api/admin.py
from django.contrib import admin from api import models class UserProfileAdmin(admin.ModelAdmin): list_display = ('user', 'country', ) class EventAdmin(admin.ModelAdmin): prepopulated_fields = {'slug': ('title',)} list_display = ('title', 'status', 'location', 'country', 'start_date') list_editable...
from django.contrib import admin from api import models class UserProfileAdmin(admin.ModelAdmin): list_display = ('user', 'country', ) search_fields = ['user__email', 'user__username', 'user__first_name', 'user__last_name'] class EventAdmin(admin.ModelAdmin): prepopulated_fields = {'slug': ('title',)} ...
Allow searching by email, username and names in user profiles
Allow searching by email, username and names in user profiles This is needed as user profiles need to be edited for setting main contact flag and ambassador roles.
Python
mit
codeeu/coding-events,michelesr/coding-events,michelesr/coding-events,michelesr/coding-events,codeeu/coding-events,codeeu/coding-events,michelesr/coding-events,codeeu/coding-events,codeeu/coding-events,michelesr/coding-events
eb313bcced5a71f80cff8b3314d3346a151297a9
flickr_api/__init__.py
flickr_api/__init__.py
""" Object Oriented implementation of Flickr API. Important notes: - For consistency, the nameing of methods might differ from the name in the official API. Please check the method "docstring" to know what is the implemented method. - For methods which expect an object "id", eith...
""" Object Oriented implementation of Flickr API. Important notes: - For consistency, the nameing of methods might differ from the name in the official API. Please check the method "docstring" to know what is the implemented method. - For methods which expect an object "id", eith...
Put some import clauses into try/except blocks to be able to use flickr_api.tools when the list of methods is not up to date
Put some import clauses into try/except blocks to be able to use flickr_api.tools when the list of methods is not up to date
Python
bsd-3-clause
alexis-mignon/python-flickr-api,alexis-mignon/python-flickr-api,bryndin/tornado-flickr-api
c1c2503933243fe51bb14f7d63222f958178d7e7
tfx/components/transform/executor_v2_test.py
tfx/components/transform/executor_v2_test.py
# Lint as: python3 # 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 ...
# Lint as: python3 # 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 ...
Remove version check now that TFX 0.25 is released.
Remove version check now that TFX 0.25 is released. PiperOrigin-RevId: 343533114
Python
apache-2.0
tensorflow/tfx,tensorflow/tfx
1eb6f65e40fccb3cea4b35374e7ddc25dd574dfa
examples/test/test_scratchnet.py
examples/test/test_scratchnet.py
#!/usr/bin/env python """ Test for scratchnet.py """ import unittest import pexpect class testScratchNet( unittest.TestCase ): opts = [ "1 packets transmitted, 1 received, 0% packet loss", pexpect.EOF ] def pingTest( self, name ): "Verify that no ping packets were dropped" p = pexpect.spawn...
#!/usr/bin/env python """ Test for scratchnet.py """ import unittest import pexpect class testScratchNet( unittest.TestCase ): opts = [ "1 packets transmitted, 1 received, 0% packet loss", pexpect.EOF ] def pingTest( self, name ): "Verify that no ping packets were dropped" p = pexpect.spawn...
Increase scratchnet timeout to see if it's just slow.
Increase scratchnet timeout to see if it's just slow.
Python
bsd-3-clause
mininet/mininet,mininet/mininet,mininet/mininet
c6e16cf939e74640fc8aec3475bf917214ee8ee6
copyrightme.py
copyrightme.py
import sublime, sublime_plugin class CopyrightmeCommand(sublime_plugin.TextCommand): def run(self, edit, text): region = self.view.visible_region() if text not in self.view.substr(region): self.view.split_by_newlines(region) self.view.insert(edit, 0, text + '\n\n')
import sublime, sublime_plugin class CopyrightmeCommand(sublime_plugin.TextCommand): def run(self, edit, text): region = self.view.visible_region() if text not in self.view.substr(region): self.view.insert(edit, 0, text + '\n\n')
Remove line splitting in view
Remove line splitting in view
Python
mit
tatarin0/CopyrightMe,tatarin0/CopyrightMe
1a242dc184adf4a3917b6c82742a667399c16ae9
respite/middleware.py
respite/middleware.py
from django.http import QueryDict class HttpMethodOverrideMiddleware: """ Facilitate for overriding the HTTP method with the X-HTTP-Method-Override header or a '_method' HTTP POST parameter. """ def process_request(self, request): if request.META.has_key('HTTP_X_HTTP_METHOD_OVERRIDE') \ ...
import re from django.http import QueryDict class HttpMethodOverrideMiddleware: """ Facilitate for overriding the HTTP method with the X-HTTP-Method-Override header or a '_method' HTTP POST parameter. """ def process_request(self, request): if request.META.has_key('HTTP_X_HTTP_METHOD_OVER...
Discard the '_method' parameter on HTTP POST
Discard the '_method' parameter on HTTP POST
Python
mit
jgorset/django-respite,jgorset/django-respite,jgorset/django-respite
04e243aafbd08008556d83d73fbbf22e5398aab4
telostats/stations/models.py
telostats/stations/models.py
from django.db import models from django.utils import timezone class Station(models.Model): id = models.IntegerField(unique=True, primary_key=True) name = models.CharField(u'name', max_length=100) longitude = models.FloatField(u'longitude') latitude = models.FloatField(u'latitude') class Status(mode...
from django.db import models from django.utils import timezone class Station(models.Model): id = models.IntegerField(unique=True, primary_key=True) name = models.CharField(u'name', max_length=100) longitude = models.FloatField(u'longitude') latitude = models.FloatField(u'latitude') def __unicode_...
Add unicode methods to Station/Status
Add unicode methods to Station/Status
Python
bsd-3-clause
idan/telostats,idan/telostats,idan/telostats
bd0310663a4f646873119e6b01afe585d0ef40bb
lib/interpreters/ScssInterpreter.py
lib/interpreters/ScssInterpreter.py
import re from os import path from ..interpreter import * from ..SIMode import SIMode from ..utils import endswith class ScssInterpreter(Interpreter): def run(self): self.settings = { "extensions": [".scss"], "remove_extensions": [".scss"], "extra_extensions": [".jpg", ".png", ".gif", ".svg"], ...
import re from os import path from ..interpreter import * from ..SIMode import SIMode from ..utils import endswith class ScssInterpreter(Interpreter): def run(self): self.settings = { "extensions": [".scss"], "remove_extensions": [".scss"], "extra_extensions": [".jpg", ".png", ".gif", ".svg"], ...
Add single-quotes setting to scss
Add single-quotes setting to scss
Python
mit
vinpac/sublime-simple-import,vini175pa/sublime-simple-import,vini175pa/sublime-simple-import,vini175pa/simple-import-js,vini175pa/simple-import-js
9219a70106ce3008e5d4a394bb0d8507d474405b
pylib/mapit/areas/management/commands/utils.py
pylib/mapit/areas/management/commands/utils.py
import sys def save_polygons(lookup): for shape in lookup.values(): m, poly = shape if not poly: continue sys.stdout.write(".") sys.stdout.flush() #g = OGRGeometry(OGRGeomType('MultiPolygon')) m.polygons.all().delete() for p in poly: p...
import sys def save_polygons(lookup): for shape in lookup.values(): m, poly = shape if not poly: continue sys.stdout.write(".") sys.stdout.flush() #g = OGRGeometry(OGRGeomType('MultiPolygon')) m.polygons.all().delete() for p in poly: p...
Work around KML -> Django import bug.
Work around KML -> Django import bug.
Python
agpl-3.0
chris48s/mapit,chris48s/mapit,opencorato/mapit,chris48s/mapit,opencorato/mapit,New-Bamboo/mapit,Code4SA/mapit,opencorato/mapit,Sinar/mapit,Sinar/mapit,Code4SA/mapit,Code4SA/mapit,New-Bamboo/mapit
f3ae9106bf738fc3e86609fbf4d7ed26d4c76354
bookmarks/database.py
bookmarks/database.py
from sqlalchemy import create_engine from sqlalchemy.orm import scoped_session, sessionmaker from sqlalchemy.ext.declarative import declarative_base from bookmarks import app DATABASE_URL = 'postgresql://{}:{}@{}/{}'.format( app.config['DATABASE_USERNAME'], app.config['DATABASE_PASSWORD'], app.config['DATA...
from sqlalchemy import create_engine from sqlalchemy.orm import scoped_session, sessionmaker from sqlalchemy.ext.declarative import declarative_base from bookmarks import app engine = create_engine(app.config['DATABASE_URI'], convert_unicode=True) db_session = scoped_session(sessionmaker(autocommit=False, ...
Use a DATABASE_URI config for db reference
Use a DATABASE_URI config for db reference
Python
apache-2.0
byanofsky/bookmarks,byanofsky/bookmarks,byanofsky/bookmarks
62622d78c5cd45fbbe04497de856ff5424051678
tensorflow/models/rnn/__init__.py
tensorflow/models/rnn/__init__.py
# Copyright 2015 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or a...
# Copyright 2015 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or a...
Fix doc string weirdness introduced by script
Fix doc string weirdness introduced by script The doc string is still pretty confusing, but this is what it was before I messed it up with my script. Change: 114470999
Python
apache-2.0
sandeepdsouza93/TensorFlow-15712,alsrgv/tensorflow,annarev/tensorflow,EvenStrangest/tensorflow,chemelnucfin/tensorflow,SnakeJenny/TensorFlow,Carmezim/tensorflow,admcrae/tensorflow,cxxgtxy/tensorflow,anilmuthineni/tensorflow,benoitsteiner/tensorflow-xsmm,ppwwyyxx/tensorflow,calebfoss/tensorflow,MostafaGazar/tensorflow,h...
1b0fdfdc2ff49d6dfc7d239b5a9cda1ff334f20b
candidates/cache.py
candidates/cache.py
from django.core.cache import cache def post_cache_key(mapit_area_id): """Form the cache key used for post data""" return "post:{0}".format(mapit_area_id) def invalidate_posts(post_ids): for post_id in post_ids: post_key = post_cache_key(post_id) cache.delete(post_key) def get_post_cached...
from django.core.cache import cache def post_cache_key(mapit_area_id): """Form the cache key used for post data""" return "post:{0}".format(mapit_area_id) def person_cache_key(person_id): """Form the cache key used for person data""" return "person:{0}".format(person_id) def invalidate_posts(post_ids...
Add functions for caching person data from PopIt
Add functions for caching person data from PopIt
Python
agpl-3.0
mysociety/yournextrepresentative,openstate/yournextrepresentative,DemocracyClub/yournextrepresentative,mysociety/yournextrepresentative,datamade/yournextmp-popit,openstate/yournextrepresentative,mysociety/yournextmp-popit,DemocracyClub/yournextrepresentative,mysociety/yournextrepresentative,datamade/yournextmp-popit,Yo...
5831fe52a4b8296bd4f0c71e5e98369d704b8fc3
painter/urls.py
painter/urls.py
from django.conf.urls import url from django.contrib.staticfiles.urls import staticfiles_urlpatterns from . import views urlpatterns = [ url(r'^noreload$', views.CardDisplay.as_view(), name='card_display_noreload'), url(r'^$', views.CardDisplayReload.as_view(), name='card_display'), ] urlpatterns += staticf...
from django.conf.urls import url from . import views urlpatterns = [ url(r'^noreload$', views.CardDisplay.as_view(), name='card_display_noreload'), url(r'^$', views.CardDisplayReload.as_view(), name='card_display'), ]
Remove the staticfiles from the painter app URLconf.
Remove the staticfiles from the painter app URLconf.
Python
mit
adam-thomas/imperial-painter,adam-thomas/imperial-painter,adam-incuna/imperial-painter,adam-incuna/imperial-painter
4971f5cd840d17df237fc09dbd11cb8e265bc6e8
quickphotos/utils.py
quickphotos/utils.py
from django.utils.timezone import make_aware, utc from .models import Photo def update_photos(photos): for i in photos: image = i.images['standard_resolution'] obj, created = Photo.objects.update_or_create(photo_id=i.id, defaults={ 'user': i.user.username, 'image': image....
from django.utils.timezone import make_aware, utc from .models import Photo def update_photos(photos): obj_list = [] for i in photos: image = i.images['standard_resolution'] obj, created = Photo.objects.update_or_create(photo_id=i.id, defaults={ 'user': i.user.username, ...
Return a list of all photo objects which have been updated
Return a list of all photo objects which have been updated
Python
bsd-3-clause
blancltd/django-quick-photos,kmlebedev/mezzanine-instagram-quickphotos
47162e68dd7662efd8f1c2463d11dc9228726523
solar/dblayer/standalone_session_wrapper.py
solar/dblayer/standalone_session_wrapper.py
# Copyright 2015 Mirantis, Inc. # # 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 ...
# Copyright 2015 Mirantis, Inc. # # 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 ...
Fix session in CLI on Debian systems
Fix session in CLI on Debian systems Change-Id: I4b1a3e45417a8d8442e097d440ebee8a09a8aaa2
Python
apache-2.0
openstack/solar,pigmej/solar,openstack/solar,openstack/solar,pigmej/solar,pigmej/solar
fd599497011fcb94d8b5c29dc696128eafb9d603
tests/app/test_create_app.py
tests/app/test_create_app.py
"""Verifies that instance_links are being retrieved properly from LINKS. Verifies that app_data.json.j2 contains the instance link information""" from unittest import mock from foremast.plugin_manager import PluginManager MANAGER = PluginManager('app', 'aws') PLUGIN = MANAGER.load() @mock.patch('foremast.app.aws.ba...
"""Verifies that instance_links are being retrieved properly from LINKS. Verifies that app_data.json.j2 contains the instance link information""" from unittest import mock from foremast.plugin_manager import PluginManager MANAGER = PluginManager('app', 'aws') PLUGIN = MANAGER.load() @mock.patch('foremast.app.aws.ba...
Check handling duplicate key for instance links
test: Check handling duplicate key for instance links
Python
apache-2.0
gogoair/foremast,gogoair/foremast
3f5867695e5b980e05f1516f2bcbd246cdc3241f
install_deps.py
install_deps.py
#!/usr/bin/env python """ Install the packages you have listed in the requirements file you input as first argument. """ from __future__ import (absolute_import, division, print_function, unicode_literals) import sys import fileinput import subprocess from pip.req import parse_requirements ...
#!/usr/bin/env python """ Install the packages you have listed in the requirements file you input as first argument. """ from __future__ import (absolute_import, division, print_function, unicode_literals) import sys import fileinput import subprocess from pip.req import parse_requirements i...
Fix parse_requirements call for new pip version.
Fix parse_requirements call for new pip version.
Python
bsd-3-clause
Neurita/boyle
f1eae848aa48ef3891407f400410827d59d7c880
pyservice/__init__.py
pyservice/__init__.py
""" Copyright (c) 2014, Joseph Cross. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute,...
""" Copyright (c) 2014, Joseph Cross. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute,...
Make Client, Service importable from pyservice
Make Client, Service importable from pyservice
Python
mit
numberoverzero/pyservice
74d4868a0e43e5eb089d6d7a0a07545b7f829806
main.py
main.py
from common.bounty import * from common.peers import * from common import settings from time import sleep from common.safeprint import safeprint def main(): settings.setup() try: import miniupnpc except: settings.config['outbound'] = True safeprint("settings are:") safeprint(setting...
from common.bounty import * from common.peers import * from common import settings from time import sleep from common.safeprint import safeprint def main(): settings.setup() try: import miniupnpc except: settings.config['outbound'] = True safeprint("settings are:") safeprint(setting...
Add delay after listener start (for testing)
Add delay after listener start (for testing) [skip ci]
Python
mit
gappleto97/Senior-Project
34452461de40c35d28bfc8b2a18b6fa14ebb875d
onadata/apps/fsforms/management/commands/update_mongo_value_type.py
onadata/apps/fsforms/management/commands/update_mongo_value_type.py
from django.conf import settings from django.core.management.base import BaseCommand class Command(BaseCommand): help = "Update value type of fs_site and fs_uuid in mongo instances to make string type to int type" def handle(self, *args, **kwargs): xform_instances = settings.MONGO_DB.instances ...
from django.conf import settings from django.core.management.base import BaseCommand class Command(BaseCommand): help = "Update value type of fs_site and fs_uuid in mongo instances to make string type to int type" def handle(self, *args, **kwargs): xform_instances = settings.MONGO_DB.instances ...
Handle cases update mongo value type
Handle cases update mongo value type
Python
bsd-2-clause
awemulya/fieldsight-kobocat,awemulya/fieldsight-kobocat,awemulya/fieldsight-kobocat,awemulya/fieldsight-kobocat
c6b51b82fa0503a2696161374160c47297211c7c
qubs_data_api/urls.py
qubs_data_api/urls.py
from django.conf.urls import url, include from django.contrib import admin urlpatterns = [ url(r'^climate/', include('climate.urls')), url(r'^herbarium/', include('herbarium.urls')), url(r'^api-auth/', include('rest_framework.urls')), url(r'^admin/', admin.site.urls), ]
from django.conf.urls import url, include from django.contrib import admin urlpatterns = [ url(r'^', include('core.urls')), url(r'^climate/', include('climate.urls')), url(r'^herbarium/', include('herbarium.urls')), url(r'^api-auth/', include('rest_framework.urls')), url(r'^admin/', admin.site.urls...
Include Core URLS at the base URL path.
Include Core URLS at the base URL path.
Python
apache-2.0
qubs/data-centre,qubs/data-centre,qubs/climate-data-api,qubs/climate-data-api
102a35d9ce74a4f29be2fc0bb34b80cb7ee4d77d
tests/helper_methods_test.py
tests/helper_methods_test.py
import os import unittest from config import Config class HelperMethodsTest(unittest.TestCase): def test_that_config_week_is_only_A_or_B(self): """ This test ensures that the only value set for 'WEEK' in the envvars is A or B. """ config = Config() if os.path.exis...
import os import unittest from config import Config class HelperMethodsTest(unittest.TestCase): def test_that_config_week_is_only_A_or_B(self): """ This test ensures that the only value set for 'WEEK' in the envvars is A or B. """ config = Config() week_options = [...
Update tests for config week
Update tests for config week
Python
mit
andela-kanyanwu/food-bot-review
126d79011221da6692d70f9a9aba1f335155ab58
us_ignite/apps/management/commands/app_load_fixtures.py
us_ignite/apps/management/commands/app_load_fixtures.py
from django.core.management.base import BaseCommand from us_ignite.apps.models import Feature, Domain FEATURE_LIST = ( 'SDN', 'OpenFlow', 'Ultra fast', 'Speed', 'Low-latency', 'Local cloud / edge computing', ) DOMAIN_LIST = ( 'Healthcare', 'Education & Workforce', 'Energy', '...
from django.core.management.base import BaseCommand from us_ignite.apps.models import Feature, Domain FEATURE_LIST = ( 'SDN', 'OpenFlow', 'Ultra fast', 'Speed', 'Low-latency', 'Local cloud / edge computing', 'Advanced wireless', 'Ultra-fast/Gigabit to end-user', 'GENI/US Ignite Ra...
Update app domain initial fixtures.
Update app domain initial fixtures.
Python
bsd-3-clause
us-ignite/us_ignite,us-ignite/us_ignite,us-ignite/us_ignite,us-ignite/us_ignite,us-ignite/us_ignite
6e4e073b4979bbf6099d0054181f13134f8cfe73
stash_test_case.py
stash_test_case.py
import os import shutil import unittest from stash import Stash class StashTestCase(unittest.TestCase): """Base class for test cases that test stash functionality. This base class makes sure that all unit tests are executed in a sandbox environment. """ PATCHES_PATH = os.path.join('test', '.patc...
import os import shutil import unittest from stash import Stash class StashTestCase(unittest.TestCase): """Base class for test cases that test stash functionality. This base class makes sure that all unit tests are executed in a sandbox environment. """ PATCHES_PATH = os.path.join('test', '.patc...
Remove patches in between unit tests.
Remove patches in between unit tests.
Python
bsd-3-clause
ton/stash,ton/stash
7535e8020b2d29abbe45e724f5ff4f51613d95d0
survey/__init__.py
survey/__init__.py
import logging LOGGER = logging.getLogger(__name__) DEFAULT_SETTINGS = [ "CHOICES_SEPARATOR", "USER_DID_NOT_ANSWER", "TEX_CONFIGURATION_FILE", "SURVEY_DEFAULT_PIE_COLOR", "EXCEL_COMPATIBLE_CSV", ] def set_default_settings(): try: from django.conf import settings from . import...
import logging LOGGER = logging.getLogger(__name__) DEFAULT_SETTINGS = [ "CHOICES_SEPARATOR", "USER_DID_NOT_ANSWER", "TEX_CONFIGURATION_FILE", "SURVEY_DEFAULT_PIE_COLOR", "EXCEL_COMPATIBLE_CSV", ] def set_default_settings(): try: from django.conf import settings from . import...
Fix Use % formatting in logging functions
Fix Use % formatting in logging functions
Python
agpl-3.0
Pierre-Sassoulas/django-survey,Pierre-Sassoulas/django-survey,Pierre-Sassoulas/django-survey
7902711589cf3ce0fe492442dbfec2497fd06dc4
build-aux/dist-docs.py
build-aux/dist-docs.py
#!/usr/bin/env python3 import os import shutil import subprocess from pathlib import PurePath references = [ 'docs/json-glib/json-glib-1.0', ] sourceroot = os.environ.get('MESON_SOURCE_ROOT') buildroot = os.environ.get('MESON_BUILD_ROOT') distroot = os.environ.get('MESON_DIST_ROOT') for reference in reference...
#!/usr/bin/env python3 import os import shutil references = [ 'doc/json-glib-1.0', ] sourceroot = os.environ.get('MESON_SOURCE_ROOT') buildroot = os.environ.get('MESON_BUILD_ROOT') distroot = os.environ.get('MESON_DIST_ROOT') for reference in references: src_path = os.path.join(buildroot, reference) if...
Fix the docs path in the dist script
build: Fix the docs path in the dist script Fixes: #66
Python
lgpl-2.1
frida/json-glib,GNOME/json-glib,GNOME/json-glib,frida/json-glib
ac00ef4ac08c6e47de80c33a6781d00c7b2bc943
flask_sockets.py
flask_sockets.py
# -*- coding: utf-8 -*- def log_request(self): log = self.server.log if log: if hasattr(log, 'info'): log.info(self.format_request() + '\n') else: log.write(self.format_request() + '\n') # Monkeys are made for freedom. try: import gevent from geventwebsocket.gu...
# -*- coding: utf-8 -*- from functools import wraps from flask import request def log_request(self): log = self.server.log if log: if hasattr(log, 'info'): log.info(self.format_request() + '\n') else: log.write(self.format_request() + '\n') # Monkeys are made for fr...
Use Flask routing to allow for variables in URL
Use Flask routing to allow for variables in URL
Python
mit
clarkduvall/flask-sockets
b77174948721413de84d6037ef4e4329978978cc
taskzilla/views.py
taskzilla/views.py
from django.shortcuts import render from .models import Task def index(request): tasks_list = Task.objects.filter(closed=False) context = {'tasks_list' : tasks_list,} return render(request, 'taskzilla/index.html', context) def task_page(request, task_id): task = Task.objects.get(pk=task_id) context = {'task' :...
from django.shortcuts import render from .models import Task def index(request): tasks_list = Task.objects.filter(closed=False) context = {'tasks_list' : tasks_list,} return render(request, 'taskzilla/index.html', context) def task_page(request, task_id): task = Task.objects.get(pk=task_id) context = {'task' :...
Add comments to the Task Page
Views: Add comments to the Task Page
Python
mit
static-code-generators/taskzilla,jailuthra/taskzilla,jailuthra/taskzilla,static-code-generators/taskzilla,static-code-generators/taskzilla,jailuthra/taskzilla
1f13b7734b06e3c9572865734defa0b1afd4db8b
jobs_executor.py
jobs_executor.py
import subprocess import os import mail_handler from datetime import datetime from settings_handler import settings def execJobs(jobs): try: for job in jobs: if not execJob(job): return False print "Jobs executed" return True except: print "Executed failed" return False finally: output = "tmp/out...
import subprocess import os import mail_handler import tempfile from datetime import datetime from settings_handler import settings def execJobs(jobs): try: for job in jobs: if not execJob(job): return False print "Jobs executed" return True except: print "Executed failed" return False def execJob(...
Use the tempfile module to create system indipendend temporary file for the output.
Use the tempfile module to create system indipendend temporary file for the output. closes #1
Python
apache-2.0
baumartig/paperboy
7ff11cc0d8183a03bb83430236b12aa70ac2f8dc
lib/allosmod/get_ss.py
lib/allosmod/get_ss.py
"""Get secondary structure with DSSP.""" from __future__ import print_function, absolute_import import optparse import subprocess def check_output(args, stderr=None, retcode=0, input=None, *other): p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=stderr, stdin=subprocess.PIPE if ...
"""Get secondary structure with DSSP.""" from __future__ import print_function, absolute_import import optparse import subprocess def check_output(args, stderr=None, retcode=0, input=None, *other): p = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=stderr, stdin=subprocess.PIPE if ...
Return results as a generator, not in a file.
Return results as a generator, not in a file.
Python
lgpl-2.1
salilab/allosmod-lib,salilab/allosmod-lib,salilab/allosmod-lib,salilab/allosmod-lib,salilab/allosmod-lib
d49118a52c15b2434a43a717476cdc7340dfc8c6
test/test_suite.py
test/test_suite.py
# list examples a=['spam','eggs',100,1234] log(a[:2]+['bacon',2*2]) log(3*a[:3]+['Boo!']) log(a[:]) a[2]=a[2]+23 log(a) a[0:2]=[1,12] log(a) a[0:2]=[] log(a) a[1:1]=['bletch','xyzzy'] log(a) a[:0]=a log(a) a[:]=[] log(a)
# list examples a=['spam','eggs',100,1234] log(a[:2]+['bacon',2*2]) log(3*a[:3]+['Boo!']) log(a[:]) a[2]=a[2]+23 log(a) a[0:2]=[1,12] log(a) a[0:2]=[] log(a) a[1:1]=['bletch','xyzzy'] log(a) a[:0]=a log(a) a[:]=[] log(a) a.extend('ab') log(a) a.extend([1,2,33]) log(a)
Test suite copied from Python tutorial
Test suite copied from Python tutorial
Python
bsd-3-clause
sgzwiz/brython,sgzwiz/brython,sgzwiz/brython