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
b0273cc12abaf9a3f9f2e6c534d82bd7581c240e
ctypeslib/test/test_dynmodule.py
ctypeslib/test/test_dynmodule.py
# Basic test of dynamic code generation import unittest import stdio from ctypes import POINTER, c_int class DynModTest(unittest.TestCase): def test_fopen(self): self.failUnlessEqual(stdio.fopen.restype, POINTER(stdio.FILE)) self.failUnlessEqual(stdio.fopen.argtypes, [stdio.STRING, stdio.STRING]) ...
# Basic test of dynamic code generation import unittest import os, glob import stdio from ctypes import POINTER, c_int class DynModTest(unittest.TestCase): def tearDown(self): for fnm in glob.glob(stdio._gen_basename + ".*"): try: os.remove(fnm) except IOError: ...
Clean up generated files in the tearDown method.
Clean up generated files in the tearDown method. git-svn-id: ac2c3632cb6543e7ab5fafd132c7fe15057a1882@52711 6015fed2-1504-0410-9fe1-9d1591cc4771
Python
mit
trolldbois/ctypeslib,trolldbois/ctypeslib,luzfcb/ctypeslib,trolldbois/ctypeslib,luzfcb/ctypeslib,luzfcb/ctypeslib
0945e04edcb4739069f4263bbd022bff4320606e
examples/LKE_example.py
examples/LKE_example.py
# for local run, before pygraphc packaging import sys sys.path.insert(0, '../pygraphc/misc') from LKE import * sys.path.insert(0, '../pygraphc/clustering') from ClusterUtility import * from ClusterEvaluation import * ip_address = '161.166.232.17' standard_path = '/home/hudan/Git/labeled-authlog/dataset/' + ip_address ...
# for local run, before pygraphc packaging import sys sys.path.insert(0, '../pygraphc/misc') from LKE import * sys.path.insert(0, '../pygraphc/evaluation') from ExternalEvaluation import * ip_address = '161.166.232.17' standard_path = '/home/hudan/Git/labeled-authlog/dataset/' + ip_address standard_file = standard_pat...
Change module path for cluster evaluation and edit how to get original logs
Change module path for cluster evaluation and edit how to get original logs
Python
mit
studiawan/pygraphc
7c49517c3c24d239c2bd44d82916b4f3d90ca1e2
utilities/__init__.py
utilities/__init__.py
#! /usr/bin/env python from subprocess import Popen, PIPE def launch(cmd): """ Fork the specified command, returning a tuple of (stdout, stderr) """ return Popen(cmd, shell=True, stdout=PIPE, stderr=PIPE).communicate() def get_stdout(cmd): """ Fork the specified command, returning stdout ...
#! /usr/bin/env python from subprocess import Popen, PIPE def popen(cmd): """ Fork the specified command, returning a tuple of (stdout, stderr) """ return Popen(cmd, shell=True, stdout=PIPE, stderr=PIPE).communicate() def get_stdout(cmd): """ Fork the specified command, returning stdout ...
Switch to using popen as the function name to stick more to subprocess naming
Switch to using popen as the function name to stick more to subprocess naming
Python
mit
IanLee1521/utilities
d147d8865dc4b82eaff87d0d4dd65ba7f4622a90
django/contrib/admin/__init__.py
django/contrib/admin/__init__.py
from django.contrib.admin.options import ModelAdmin, HORIZONTAL, VERTICAL from django.contrib.admin.options import StackedInline, TabularInline from django.contrib.admin.sites import AdminSite, site def autodiscover(): """ Auto-discover INSTALLED_APPS admin.py modules and fail silently when not present. T...
# ACTION_CHECKBOX_NAME is unused, but should stay since its import from here # has been referenced in documentation. from django.contrib.admin.helpers import ACTION_CHECKBOX_NAME from django.contrib.admin.options import ModelAdmin, HORIZONTAL, VERTICAL from django.contrib.admin.options import StackedInline, TabularInli...
Revert the removal of an unused import (in [14175]) that was referenced in documentation. Thanks for noticing, clong.
Revert the removal of an unused import (in [14175]) that was referenced in documentation. Thanks for noticing, clong. git-svn-id: http://code.djangoproject.com/svn/django/trunk@14359 bcc190cf-cafb-0310-a4f2-bffc1f526a37 --HG-- extra : convert_revision : e026073455a73c9fe9a9f026b76ac783b2a12d23
Python
bsd-3-clause
adieu/django-nonrel,heracek/django-nonrel,adieu/django-nonrel,heracek/django-nonrel,adieu/django-nonrel,heracek/django-nonrel
4f05805c0ec31da0b978cdccc0d79336272859fe
node/multi_var.py
node/multi_var.py
from nodes import Node class MultiVar(Node): char = "'" args = 0 results = None contents = -1 def __init__(self, node_1: Node.NodeSingle, node_2: Node.NodeSingle): self.node_1 = node_1 self.node_2 = node_2 self.args = max([node_1.args, node_2.args]) def pr...
from nodes import Node class MultiVar(Node): char = "'" args = 0 results = None contents = -1 def __init__(self, node_1: Node.NodeSingle, node_2: Node.NodeSingle): self.node_1 = node_1 self.node_2 = node_2 def prepare(self, stack): self.node_1.prepare(stac...
Fix multivar for nodes with variable length stacks
Fix multivar for nodes with variable length stacks
Python
mit
muddyfish/PYKE,muddyfish/PYKE
3518e9088ecbbc273f922ba418d2962d6af2dda5
feature_extraction/measurements/texture_haralick.py
feature_extraction/measurements/texture_haralick.py
from . import Measurement import feature_extraction.util.cleanup as cleanup class HaralickTexture(Measurement): def compute(self, image): return []
from . import Measurement import feature_extraction.util.cleanup as cleanup from skimage.morphology import binary_erosion, disk class HaralickTexture(Measurement): default_options = { 'clip_cell_borders': True, 'erode_cell': False, 'erode_cell_amount': False, } def __init__(self, options=None): super(Harali...
Add cell-boundary preprocessing to HaralickTexture measurement
Add cell-boundary preprocessing to HaralickTexture measurement
Python
apache-2.0
widoptimization-willett/feature-extraction
b08315337e71737a36e3e79da99ce167620711b9
photodaemon.py
photodaemon.py
#!/bin/env python import picamera import redis import time import json import os def take_photo(): print "%s Capture photo" % (time.strftime('%Y.%m.%d %H:%M:%S %Z')) camera = picamera.PiCamera() camera.vflip = True camera.resolution = (1280, 720) time.sleep(1) camera.capture('static/photo.jpg'...
#!/bin/env python import picamera import redis import time import json import os def take_photo(): print "%s Capture photo" % (time.strftime('%Y.%m.%d %H:%M:%S %Z')) camera = picamera.PiCamera() camera.vflip = True camera.resolution = (1280, 720) time.sleep(1) camera.capture('static/photo.jpg'...
Fix publishing photo creation event
Fix publishing photo creation event
Python
mit
Ajnasz/pippo,Ajnasz/pippo,Ajnasz/pippo
b2fbb48049abbfff7f1636059f8ad7eda07667c7
test/single_system/all.py
test/single_system/all.py
import sys, unittest import bmc_test import power_test import xmlrunner tests = [] tests.extend(bmc_test.tests) #tests.extend(power_test.tests) if __name__ == '__main__': for test in tests: test.system = sys.argv[1] suite = unittest.TestLoader().loadTestsFromTestCase(test) xmlrunner.XMLTes...
import sys, unittest, os import bmc_test import power_test import xmlrunner tests = [] tests.extend(bmc_test.tests) #tests.extend(power_test.tests) if __name__ == '__main__': for test in tests: test.system = sys.argv[1] suite = unittest.TestLoader().loadTestsFromTestCase(test) result = xml...
Return a bad error code when a test fails
Return a bad error code when a test fails
Python
bsd-3-clause
Cynerva/pyipmi,emaadmanzoor/pyipmi
6046de052e1f19d2b7cdd3d86f921ac3c16ce338
usaidmmc/__init__.py
usaidmmc/__init__.py
from __future__ import absolute_import from usaidmmc.celery import app as celery_app
from __future__ import absolute_import from usaidmmc.celery import app as celery_app # flake8: noqa
Stop flake8 complaining about task importer
Stop flake8 complaining about task importer
Python
bsd-3-clause
praekelt/django-usaid-mmc,praekelt/django-usaid-mmc
94b55ead63523f7f5677989f1a4999994b205cdf
src/runcommands/util/enums.py
src/runcommands/util/enums.py
import enum import subprocess from blessings import Terminal TERM = Terminal() class Color(enum.Enum): none = "" reset = TERM.normal black = TERM.black red = TERM.red green = TERM.green yellow = TERM.yellow blue = TERM.blue magenta = TERM.magenta cyan = TERM.cyan white = TE...
import enum import os import subprocess import sys from blessings import Terminal from .misc import isatty if not (isatty(sys.stdout) and os.getenv("TERM")): class Terminal: def __getattr__(self, name): return "" TERM = Terminal() class Color(enum.Enum): none = "" reset = TERM....
Check for TTY and TERM when setting up Color enum
Check for TTY and TERM when setting up Color enum Amends 0d27649df30419a79ca063ee3e47073f2ba8330e
Python
mit
wylee/runcommands,wylee/runcommands
621ca7bebfcc53026d8f98b9f6cfefe6ff25961b
src/util/constants.py
src/util/constants.py
# start of sentence token SOS = '<S>' # end of sentence token EOS = '</S>'
# start of sentence token SOS = chr(2) # end of sentence token EOS = chr(3)
Use separate characters for SOS and EOS
Use separate characters for SOS and EOS
Python
mit
milankinen/c2w2c,milankinen/c2w2c
e6bfc4eb1d8f5a4d0239232fa89aa9d3d756549c
test/geocoders/geonames.py
test/geocoders/geonames.py
import unittest from geopy.geocoders import GeoNames from test.geocoders.util import GeocoderTestBase, env @unittest.skipUnless( # pylint: disable=R0904,C0111 bool(env.get('GEONAMES_USERNAME')), "No GEONAMES_USERNAME env variable set" ) class GeoNamesTestCase(GeocoderTestBase): @classmethod def se...
# -*- coding: UTF-8 -*- import unittest from geopy.geocoders import GeoNames from test.geocoders.util import GeocoderTestBase, env @unittest.skipUnless( # pylint: disable=R0904,C0111 bool(env.get('GEONAMES_USERNAME')), "No GEONAMES_USERNAME env variable set" ) class GeoNamesTestCase(GeocoderTestBase): ...
Use different location for GeoNames integration test
Use different location for GeoNames integration test
Python
mit
RDXT/geopy,Vimos/geopy,mthh/geopy,memaldi/geopy,ahlusar1989/geopy,jmb/geopy,two9seven/geopy,magnushiie/geopy,ahlusar1989/geopy,mthh/geopy,Vimos/geopy,smileliaohua/geopy,SoftwareArtisan/geopy,magnushiie/geopy,cffk/geopy,cffk/geopy,geopy/geopy,memaldi/geopy,RDXT/geopy,sebastianneubauer/geopy,sebastianneubauer/geopy,smile...
56e5e255b19c0b0d5998628706542d8f9666f58c
tests/builtins/test_sum.py
tests/builtins/test_sum.py
from .. utils import TranspileTestCase, BuiltinFunctionTestCase class SumTests(TranspileTestCase): def test_sum_list(self): self.assertCodeExecution(""" print(sum([1, 2, 3, 4, 5, 6, 7])) """) def test_sum_tuple(self): self.assertCodeExecution(""" print(sum((1, ...
from .. utils import TranspileTestCase, BuiltinFunctionTestCase class SumTests(TranspileTestCase): def test_sum_list(self): self.assertCodeExecution(""" print(sum([1, 2, 3, 4, 5, 6, 7])) """) def test_sum_tuple(self): self.assertCodeExecution(""" print(sum((1, ...
Put ‘test_frozenset’ back into BuiltinSumFunctionTests.not_implemented
Put ‘test_frozenset’ back into BuiltinSumFunctionTests.not_implemented I’m fairly certain that this was accidentally removed by my automatic processing
Python
bsd-3-clause
cflee/voc,freakboy3742/voc,cflee/voc,freakboy3742/voc
cf0193adcf6c58d82b577f09842c265bc09a685a
candidates/csv_helpers.py
candidates/csv_helpers.py
import csv import StringIO from .models import CSV_ROW_FIELDS def encode_row_values(d): return { k: unicode('' if v is None else v).encode('utf-8') for k, v in d.items() } def list_to_csv(candidates_list): output = StringIO.StringIO() writer = csv.DictWriter( output, f...
import csv import StringIO from .models import CSV_ROW_FIELDS def encode_row_values(d): return { k: unicode('' if v is None else v).encode('utf-8') for k, v in d.items() } def candidate_sort_key(row): return (row['constituency'], row['name'].split()[-1]) def list_to_csv(candidates_list):...
Sort the rows in CSV output on (constituency, last name)
Sort the rows in CSV output on (constituency, last name)
Python
agpl-3.0
datamade/yournextmp-popit,openstate/yournextrepresentative,datamade/yournextmp-popit,DemocracyClub/yournextrepresentative,neavouli/yournextrepresentative,YoQuieroSaber/yournextrepresentative,openstate/yournextrepresentative,mysociety/yournextrepresentative,DemocracyClub/yournextrepresentative,mysociety/yournextmp-popit...
f1c09bc9969cf9d66179baef80b5cbb3d28d5596
app/report/views.py
app/report/views.py
from flask import render_template from app import app @app.route('/') def index(): return render_template('index.html') @app.route('/report/<path:repository>') def report(): pass
from flask import flash, g, redirect, render_template, request, url_for from app import app from vcs.repository import is_valid_github_repository, parse_url_and_get_repo @app.route('/') def index(): return render_template('index.html') @app.route('/about') def about(): return render_template('about.html') ...
Create default behaviour for all routers
Create default behaviour for all routers
Python
mit
mingrammer/pyreportcard,mingrammer/pyreportcard
40b78b23072841cb7926d06a9d37f5a7cdd817ab
erpnext_ebay/tasks.py
erpnext_ebay/tasks.py
# -*- coding: utf-8 -*- """Scheduled tasks to be run by erpnext_ebay""" from frappe.utils.background_jobs import enqueue def all(): pass def hourly(): enqueue('erpnext_ebay.sync_orders.sync', queue='long', job_name='Sync eBay Orders') def daily(): enqueue('erpnext_ebay.ebay_active_listin...
# -*- coding: utf-8 -*- """Scheduled tasks to be run by erpnext_ebay""" from frappe.utils.background_jobs import enqueue def all(): pass def hourly(): enqueue('erpnext_ebay.sync_orders.sync', queue='long', job_name='Sync eBay Orders') def daily(): enqueue('erpnext_ebay.ebay_active_listin...
Add multiple_error_sites for daily eBay update
fix: Add multiple_error_sites for daily eBay update
Python
mit
bglazier/erpnext_ebay,bglazier/erpnext_ebay
3fe40e91f70e8256d7c86c46f866e82e3ccf26e2
commandment/profiles/cert.py
commandment/profiles/cert.py
''' Copyright (c) 2015 Jesse Peterson Licensed under the MIT license. See the included LICENSE.txt file for details. ''' from . import Payload import plistlib # needed for Data() wrapper class PEMCertificatePayload(Payload): '''PEM-encoded certificate without private key. May contain root certificates. P...
''' Copyright (c) 2015 Jesse Peterson Licensed under the MIT license. See the included LICENSE.txt file for details. ''' from . import Payload import plistlib # needed for Data() wrapper class PEMCertificatePayload(Payload): '''PEM-encoded certificate without private key. May contain root certificates. P...
Change style of Payload suclasses to better encapsulate internal structure
Change style of Payload suclasses to better encapsulate internal structure
Python
mit
mosen/commandment,jessepeterson/commandment,mosen/commandment,mosen/commandment,mosen/commandment,jessepeterson/commandment,mosen/commandment
20211a9494cc4ecd3f50bf1280d034da8f0cda50
comics/accounts/models.py
comics/accounts/models.py
import uuid from django.contrib.auth.models import User from django.db import models from django.dispatch import receiver @receiver(models.signals.post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: UserProfile.objects.create(user=instance) class UserProfil...
import uuid from django.contrib.auth.models import User from django.db import models from django.dispatch import receiver @receiver(models.signals.post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: UserProfile.objects.create(user=instance) def make_secret_...
Fix secret key generation for superuser created with mangage.py
Fix secret key generation for superuser created with mangage.py
Python
agpl-3.0
datagutten/comics,datagutten/comics,jodal/comics,datagutten/comics,jodal/comics,jodal/comics,jodal/comics,datagutten/comics
21b884876ad211851b0c8954a1cc3e4b42cae11e
test_chatbot_brain.py
test_chatbot_brain.py
import chatbot_brain import input_filters def test_initialize_bot(): bot = chatbot_brain.Chatbot() assert len(bot.tri_lexicon) == 0 assert len(bot.bi_lexicon) == 0 def test_fill_lexicon(): bot = chatbot_brain.Chatbot() bot.fill_lexicon() assert len(bot.tri_lexicon) > 0 assert len(bot.bi_...
import chatbot_brain def test_initialize_bot(): bot = chatbot_brain.Chatbot() assert len(bot.tri_lexicon) == 0 assert len(bot.bi_lexicon) == 0 def test_fill_lexicon(): bot = chatbot_brain.Chatbot() bot.fill_lexicon() assert len(bot.tri_lexicon) > 0 assert len(bot.bi_lexicon) > 0 def te...
Add test_i_filter_random_empty_words() to assert that a list that contains an empty string will return the stock phrase
Add test_i_filter_random_empty_words() to assert that a list that contains an empty string will return the stock phrase
Python
mit
corinnelhh/chatbot,corinnelhh/chatbot
bc7b52e9f2095291f9277e3c9cbac9c191fa61a5
cherrypy/py3util.py
cherrypy/py3util.py
""" A simple module that helps unify the code between a python2 and python3 library. """ import sys def sorted(lst): newlst = list(lst) newlst.sort() return newlst def reversed(lst): newlst = list(lst) return iter(newlst[::-1])
""" A simple module that helps unify the code between a python2 and python3 library. """ import sys try: sorted = sorted except NameError: def sorted(lst): newlst = list(lst) newlst.sort() return newlst try: reversed = reversed except NameError: def reversed(lst): newls...
Use builtin sorted, reversed if available.
Use builtin sorted, reversed if available. --HG-- extra : convert_revision : svn%3Ae1d34091-3ce9-0310-8e96-997e60db3bd5/trunk%402444
Python
bsd-3-clause
cherrypy/magicbus
20370bf79b43dc566a6a7e85a903275d80e437a2
api/projects/signals.py
api/projects/signals.py
from django.db.models.signals import post_save from django.dispatch import receiver from projects.models import ExperimentGroup from projects.tasks import start_group_experiments from experiments.models import Experiment @receiver(post_save, sender=ExperimentGroup, dispatch_uid="experiment_group_saved") def new_expe...
from django.db.models.signals import post_save, pre_save from django.dispatch import receiver from projects.models import ExperimentGroup from projects.tasks import start_group_experiments from experiments.models import Experiment from spawner import scheduler @receiver(post_save, sender=ExperimentGroup, dispatch_ui...
Stop experiments before deleting group
Stop experiments before deleting group
Python
apache-2.0
polyaxon/polyaxon,polyaxon/polyaxon,polyaxon/polyaxon
0eafac86c679689c77e371150c173c351d0aa926
appex_dump.py
appex_dump.py
# coding: utf-8 # See: https://forum.omz-software.com/topic/2358/appex-safari-content import appex def main(): if appex.is_running_extension(): for func in (appex.get_attachments, appex.get_file_path, appex.get_file_paths, appex.get_image, appex.get_images, appex.get_text, appex.g...
# coding: utf-8 # See: https://forum.omz-software.com/topic/2358/appex-safari-content import appex, inspect def main(): if appex.is_running_extension(): for name_func in inspect.getmembers(appex): name, func = name_func if name.startswith('get_'): # find all appex.get_xxx() metho...
Use inspect to remove hardcoding of method names
Use inspect to remove hardcoding of method names
Python
apache-2.0
cclauss/Ten-lines-or-less
42536943591ef77df3fc453e6e0b456e7a2bed89
cupy/array_api/_typing.py
cupy/array_api/_typing.py
""" This file defines the types for type annotations. These names aren't part of the module namespace, but they are used in the annotations in the function signatures. The functions in the module are only valid for inputs that match the given type annotations. """ from cupy.cuda import Device as _Device __all__ = [...
""" This file defines the types for type annotations. These names aren't part of the module namespace, but they are used in the annotations in the function signatures. The functions in the module are only valid for inputs that match the given type annotations. """ from cupy.cuda import Device as _Device from __futu...
Replace `NestedSequence` with a proper nested sequence protocol
ENH: Replace `NestedSequence` with a proper nested sequence protocol
Python
mit
cupy/cupy,cupy/cupy,cupy/cupy,cupy/cupy
79488513dfedb27a627a1eb516fb2fb2b6a2900c
geotrek/settings/env_tests.py
geotrek/settings/env_tests.py
# # Django Tests # .......................... TEST = True CELERY_ALWAYS_EAGER = True TEST_EXCLUDE = ('django',) INSTALLED_APPS += ( 'geotrek.diving', 'geotrek.sensitivity', 'geotrek.outdoor', ) LOGGING['handlers']['console']['level'] = 'CRITICAL' LANGUAGE_CODE = 'en' MODELTRANSLATION_DEFAULT_LANGUAGE...
# # Django Tests # .......................... TEST = True CELERY_ALWAYS_EAGER = True TEST_EXCLUDE = ('django',) INSTALLED_APPS += ( 'geotrek.diving', 'geotrek.sensitivity', 'geotrek.outdoor', 'drf_yasg', ) LOGGING['handlers']['console']['level'] = 'CRITICAL' LANGUAGE_CODE = 'en' MODELTRANSLATION_...
Enable drf_yasg in test settings
Enable drf_yasg in test settings
Python
bsd-2-clause
makinacorpus/Geotrek,GeotrekCE/Geotrek-admin,GeotrekCE/Geotrek-admin,makinacorpus/Geotrek,GeotrekCE/Geotrek-admin,makinacorpus/Geotrek,GeotrekCE/Geotrek-admin,makinacorpus/Geotrek
4a6ef7b593786f409c72f192c50e16e40082c8de
apps/dashboards/urls.py
apps/dashboards/urls.py
from django.conf.urls import patterns, url from django.views.generic.simple import redirect_to urlpatterns = patterns('dashboards.views', url(r'^dashboards/revisions$', 'revisions', name='dashboards.revisions'), url(r'^dashboards/user_lookup$', 'user_lookup', name='dashboards.user_lookup'), url(r'...
from django.conf.urls import patterns, url from django.views.generic.base import RedirectView urlpatterns = patterns('dashboards.views', url(r'^dashboards/revisions$', 'revisions', name='dashboards.revisions'), url(r'^dashboards/user_lookup$', 'user_lookup', name='dashboards.user_lookup'), url(r'^...
Hide DeprecationWarning for old function based generic views.
Hide DeprecationWarning for old function based generic views.
Python
mpl-2.0
jwhitlock/kuma,ollie314/kuma,chirilo/kuma,varunkamra/kuma,biswajitsahu/kuma,robhudson/kuma,openjck/kuma,RanadeepPolavarapu/kuma,scrollback/kuma,davehunt/kuma,a2sheppy/kuma,scrollback/kuma,davidyezsetz/kuma,robhudson/kuma,mozilla/kuma,davidyezsetz/kuma,nhenezi/kuma,MenZil/kuma,jezdez/kuma,RanadeepPolavarapu/kuma,escatto...
1a10f21566f59c9f4f8171bc088af1e2a18d9702
prestoadmin/_version.py
prestoadmin/_version.py
# -*- coding: utf-8 -*- # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software ...
# -*- coding: utf-8 -*- # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software ...
Prepare for the next development iteration
Prepare for the next development iteration
Python
apache-2.0
prestodb/presto-admin,prestodb/presto-admin
2f084990d919855a4b1e4bb909c607ef91810fba
knights/dj.py
knights/dj.py
from collections import defaultdict from django.template import TemplateDoesNotExist, TemplateSyntaxError # NOQA from django.template.backends.base import BaseEngine from django.template.backends.utils import csrf_input_lazy, csrf_token_lazy from . import compiler from . import loader class KnightsTemplater(BaseEn...
from collections import defaultdict from django.template import TemplateDoesNotExist, TemplateSyntaxError # NOQA from django.template.backends.base import BaseEngine from django.template.backends.utils import csrf_input_lazy, csrf_token_lazy from . import compiler from . import loader class KnightsTemplater(BaseEn...
Use built in template dirs list Add user to context
Use built in template dirs list Add user to context
Python
mit
funkybob/knights-templater,funkybob/knights-templater
720537726b3f1eb88e67ec7454ddddbee1f123fa
benchmarks/variables.py
benchmarks/variables.py
# Copyright 2022 D-Wave Systems 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 2022 D-Wave Systems 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...
Add benchmarks for Variables construction
Add benchmarks for Variables construction
Python
apache-2.0
dwavesystems/dimod,dwavesystems/dimod
9de844864b3e6c732241a68d1871f701232d2733
celery_janitor/utils.py
celery_janitor/utils.py
import importlib import urlparse from celery_janitor import conf from celery_janitor.exceptions import BackendNotSupportedException BACKEND_MAPPING = { 'sqs': 'celery_janitor.backends.sqs.SQSBackend' } def import_class(path): path_bits = path.split('.') class_name = path_bits.pop() module_path = '....
import importlib try: from urlparse import urlparse except ImportError: # Python 3.x from urllib.parse import urlparse from celery_janitor import conf from celery_janitor.exceptions import BackendNotSupportedException BACKEND_MAPPING = { 'sqs': 'celery_janitor.backends.sqs.SQSBackend' } def import_cla...
Fix Python 3.4 import error
Fix Python 3.4 import error
Python
mit
comandrei/celery-janitor
8fc43046ebfaa41410c28ba6d3d27fffed25ee4e
var/spack/repos/builtin/packages/glm/package.py
var/spack/repos/builtin/packages/glm/package.py
from spack import * class Glm(Package): """ OpenGL Mathematics (GLM) is a header only C++ mathematics library for graphics software based on the OpenGL Shading Language (GLSL) specification. """ homepage = "https://github.com/g-truc/glm" url = "https://github.com/g-truc/glm/archive/0.9.7.1.ta...
from spack import * class Glm(Package): """ OpenGL Mathematics (GLM) is a header only C++ mathematics library for graphics software based on the OpenGL Shading Language (GLSL) specification. """ homepage = "https://github.com/g-truc/glm" url = "https://github.com/g-truc/glm/archive/0.9.7.1.ta...
Add missing dependency for glm
Add missing dependency for glm
Python
lgpl-2.1
TheTimmy/spack,EmreAtes/spack,TheTimmy/spack,tmerrick1/spack,LLNL/spack,tmerrick1/spack,skosukhin/spack,matthiasdiener/spack,lgarren/spack,skosukhin/spack,TheTimmy/spack,LLNL/spack,EmreAtes/spack,matthiasdiener/spack,mfherbst/spack,matthiasdiener/spack,krafczyk/spack,tmerrick1/spack,EmreAtes/spack,skosukhin/spack,matth...
875f70c0c43b6fdc5825525e8ccfd137cecb2bfe
malcolm/modules/builtin/parts/helppart.py
malcolm/modules/builtin/parts/helppart.py
from annotypes import Anno from malcolm.core import Part, PartRegistrar, StringMeta, Widget, APartName from ..util import set_tags with Anno("The URL that gives some help documentation for this Block"): AHelpUrl = str # Pull re-used annotypes into our namespace in case we are subclassed APartName = APartName ...
from annotypes import Anno from malcolm.core import Part, PartRegistrar, StringMeta, Widget, APartName from ..util import set_tags with Anno("The URL that gives some help documentation for this Block"): AHelpUrl = str with Anno("The description of what the help documentation is about"): ADesc = str # Pull ...
Allow description to be changed in HelpPart
Allow description to be changed in HelpPart
Python
apache-2.0
dls-controls/pymalcolm,dls-controls/pymalcolm,dls-controls/pymalcolm
0468c944464d55ba7ce0a821e1085ae530d49cf6
corehq/apps/es/cases.py
corehq/apps/es/cases.py
from .es_query import HQESQuery from . import filters class CaseES(HQESQuery): index = 'cases' @property def builtin_filters(self): return [ opened_range, closed_range, is_closed, case_type, ] + super(CaseES, self).builtin_filters def open...
from .es_query import HQESQuery from . import filters class CaseES(HQESQuery): index = 'cases' @property def builtin_filters(self): return [ opened_range, closed_range, is_closed, case_type, owner, ] + super(CaseES, self).builtin...
Add `owner` filter to CaseES
Add `owner` filter to CaseES
Python
bsd-3-clause
puttarajubr/commcare-hq,qedsoftware/commcare-hq,puttarajubr/commcare-hq,puttarajubr/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,puttarajubr/commcare-hq,qedsoftware/commcare-hq,qedsoftware/commcare-hq,qedsoftware/commcare-hq,qedsoftware/commcare-hq,dimagi/commcare-hq
ef11e9d0247fbd10e317d30ca8898f9a3c079e37
cyder/base/tests/__init__.py
cyder/base/tests/__init__.py
from exceptions import AssertionError from django.core.exceptions import ValidationError from django.test import TestCase from django.test.client import Client from cyder.core.ctnr.models import Ctnr class CyTestMixin(object): """ Mixin for all tests. """ def _pre_setup(self): super(TestCase...
from exceptions import AssertionError from django.core.exceptions import ValidationError from django.test import TestCase from django.test.client import Client from cyder.core.ctnr.models import Ctnr class CyTestMixin(object): """ Mixin for all tests. """ def _pre_setup(self): super(TestCase...
Change variable names to reduce confusion
Change variable names to reduce confusion
Python
bsd-3-clause
murrown/cyder,drkitty/cyder,akeym/cyder,drkitty/cyder,OSU-Net/cyder,OSU-Net/cyder,zeeman/cyder,akeym/cyder,zeeman/cyder,akeym/cyder,akeym/cyder,drkitty/cyder,OSU-Net/cyder,zeeman/cyder,drkitty/cyder,zeeman/cyder,OSU-Net/cyder,murrown/cyder,murrown/cyder,murrown/cyder
a42a7e237a72825080fa0afea263dbd5766417bb
conary/lib/digestlib.py
conary/lib/digestlib.py
# # Copyright (c) 2004-2008 rPath, Inc. # # This program is distributed under the terms of the Common Public License, # version 1.0. A copy of this license should have been distributed with this # source file in a file called LICENSE. If it is not present, the license # is always available at http://www.rpath.com/perma...
# # Copyright (c) 2004-2008 rPath, Inc. # # This program is distributed under the terms of the Common Public License, # version 1.0. A copy of this license should have been distributed with this # source file in a file called LICENSE. If it is not present, the license # is always available at http://www.rpath.com/perma...
Use sha256 algorithm from pycrypto.
Use sha256 algorithm from pycrypto.
Python
apache-2.0
fedora-conary/conary,fedora-conary/conary,fedora-conary/conary,fedora-conary/conary,fedora-conary/conary
9a527d999075a92de3db174e0696e961c05041c4
dead_mailer.py
dead_mailer.py
#!/usr/bin/env python3 import boto3 client = boto3.client('ses') client.send_email( Source='david@severski.net', Message={ 'Subject': { 'Data': 'Here!', }, 'Body': { 'Text': { 'Data': "I'm not dead yet!", } } }, Destination={'ToAddresses': ['davidski@deadheaven.com']} )
#!/usr/bin/env python import boto3 from random import sample def acknowledge_send(): print "Acknowledge" def indicate_failure(): print "Failure" def set_message_body(selection): switcher = { '0': "I'm here!", '1': "Brrrraaaaains!", '2': "Arrived!" } return switcher.get(str(selection), 'nothing') if _...
Break down into core functions
Break down into core functions
Python
mit
davidski/imnotdeadyet,davidski/imnotdeadyet
7d7afb7d92797b48f215505579e0fb872deee0f3
rst2pdf/utils.py
rst2pdf/utils.py
# -*- coding: utf-8 -*- # See LICENSE.txt for licensing terms #$HeadURL$ #$LastChangedDate$ #$LastChangedRevision$ import shlex from reportlab.platypus import Spacer from flowables import * def parseRaw(data): """Parse and process a simple DSL to handle creation of flowables. Supported (ca...
# -*- coding: utf-8 -*- # See LICENSE.txt for licensing terms #$HeadURL$ #$LastChangedDate$ #$LastChangedRevision$ import shlex from reportlab.platypus import Spacer from flowables import * from styles import adjustUnits def parseRaw(data): """Parse and process a simple DSL to handle creation of f...
Add unit support for spacers
Add unit support for spacers
Python
mit
rafaelmartins/rst2pdf,rafaelmartins/rst2pdf
ff4c708d66f2d176697f01227061a9791e7d2488
statscache/utils.py
statscache/utils.py
import pkg_resources import logging log = logging.getLogger("fedmsg") def find_stats_consumer(hub): for cons in hub.consumers: if 'StatsConsumer' in str(type(cons)): return cons raise ValueError('StatsConsumer not found.') class memoized(object): def __init__(self, func): s...
import pkg_resources import logging log = logging.getLogger("fedmsg") def find_stats_consumer(hub): for cons in hub.consumers: if 'StatsConsumer' in str(type(cons)): return cons raise ValueError('StatsConsumer not found.') class memoized(object): def __init__(self, func): s...
Allow plugins to specify permissible update frequencies.
Allow plugins to specify permissible update frequencies. Fixed #2.
Python
lgpl-2.1
yazman/statscache,yazman/statscache,yazman/statscache
a36033badfa90fde764b136fa1e713dbb267a02b
depot/admin.py
depot/admin.py
from django.contrib import admin from .models import Depot, Item # make items modifiable by admin admin.site.register(Item) class DepotAdmin(admin.ModelAdmin): list_display = ['name', 'active'] ordering = ['name'] actions = ["make_archived", "make_restored"] def make_message(self, num_changed, ch...
from django.contrib import admin from .models import Depot, Item # make items modifiable by admin admin.site.register(Item) class DepotAdmin(admin.ModelAdmin): list_display = ['name', 'active'] ordering = ['name'] actions = ["make_archived", "make_restored"] @staticmethod def format_message(n...
Fix pylint complaining about spaces and other stuff
Fix pylint complaining about spaces and other stuff
Python
agpl-3.0
verleihtool/verleihtool,verleihtool/verleihtool,verleihtool/verleihtool,verleihtool/verleihtool
5651445944bce163a2c3f746d6ac1acd9ae76032
numpy/array_api/tests/test_asarray.py
numpy/array_api/tests/test_asarray.py
import numpy as np def test_fast_return(): """""" a = np.array([1, 2, 3], dtype='i') assert np.asarray(a) is a assert np.asarray(a, dtype='i') is a # This may produce a new view or a copy, but is never the same object. assert np.asarray(a, dtype='l') is not a unequal_type = np.dtype('i', ...
import numpy as np def test_fast_return(): """""" a = np.array([1, 2, 3], dtype='i') assert np.asarray(a) is a assert np.asarray(a, dtype='i') is a # This may produce a new view or a copy, but is never the same object. assert np.asarray(a, dtype='l') is not a unequal_type = np.dtype('i', ...
Update comment and obey formatting requirements.
Update comment and obey formatting requirements.
Python
bsd-3-clause
charris/numpy,mhvk/numpy,mattip/numpy,mattip/numpy,mattip/numpy,numpy/numpy,mhvk/numpy,endolith/numpy,charris/numpy,numpy/numpy,endolith/numpy,charris/numpy,numpy/numpy,endolith/numpy,endolith/numpy,charris/numpy,mattip/numpy,numpy/numpy,mhvk/numpy,mhvk/numpy,mhvk/numpy
7fed0208770413399fde5e76ad2046b6bc440b16
src/nodemgr/common/windows_process_manager.py
src/nodemgr/common/windows_process_manager.py
# # Copyright (c) 2018 Juniper Networks, Inc. All rights reserved. # import time from windows_process_mem_cpu import WindowsProcessMemCpuUsageData class WindowsProcessInfoManager(object): def get_mem_cpu_usage_data(self, pid, last_cpu, last_time): return WindowsProcessMemCpuUsageData(pid, last_cpu, last_...
# # Copyright (c) 2018 Juniper Networks, Inc. All rights reserved. # import psutil import time from windows_process_mem_cpu import WindowsProcessMemCpuUsageData def _service_status_to_state(status): if status == 'running': return 'PROCESS_STATE_RUNNING' else: return 'PROCESS_STATE_STOPPED' ...
Implement checking if agent is up on Windows
Implement checking if agent is up on Windows Very simple implementation using psutil Change-Id: I2b7c65d6d677f0f57e79277ac2298f0b73729b94 Partial-Bug: #1783539
Python
apache-2.0
eonpatapon/contrail-controller,rombie/contrail-controller,eonpatapon/contrail-controller,eonpatapon/contrail-controller,rombie/contrail-controller,eonpatapon/contrail-controller,rombie/contrail-controller,eonpatapon/contrail-controller,eonpatapon/contrail-controller,eonpatapon/contrail-controller,rombie/contrail-contro...
47a7770bd3c5552d61f69b7df62bf4c36de56dc8
wysteria/__init__.py
wysteria/__init__.py
from wysteria.client import Client, TlsConfig from wysteria import errors from wysteria.constants import FACET_COLLECTION from wysteria.constants import FACET_ITEM_TYPE from wysteria.constants import FACET_ITEM_VARIANT __all__ = [ "Client", "TlsConfig", "errors", "FACET_COLLECTION", "FACET_ITEM_TY...
"""The wysteria module provides a python interface for talking to a wysteria asset management server. Files: ------ - client.py high level class that wraps a middleware connection & adds some helpful functions. - constants.py various constants used - errors.py contains various exceptions that can be rais...
Add module level imports and doc strings
Add module level imports and doc strings
Python
bsd-3-clause
voidshard/pywysteria,voidshard/pywysteria
869bafa9aadf45c2beb3e6f4e3d3751d2d6baf8f
subversion/bindings/swig/python/tests/core.py
subversion/bindings/swig/python/tests/core.py
import unittest, os import svn.core class SubversionCoreTestCase(unittest.TestCase): """Test cases for the basic SWIG Subversion core""" def test_SubversionException(self): self.assertEqual(svn.core.SubversionException().args, ()) self.assertEqual(svn.core.SubversionException('error message').args, ...
import unittest, os import svn.core class SubversionCoreTestCase(unittest.TestCase): """Test cases for the basic SWIG Subversion core""" def test_SubversionException(self): self.assertEqual(svn.core.SubversionException().args, ()) self.assertEqual(svn.core.SubversionException('error message').args, ...
Add a regression test for the bug fixed in r28485.
Add a regression test for the bug fixed in r28485. * subversion/bindings/swig/python/tests/core.py (SubversionCoreTestCase.test_SubversionException): Test explicit exception fields. git-svn-id: f8a4e5e023278da1e04e203c7fe051e3c4285d88@868579 13f79535-47bb-0310-9956-ffa450edef68
Python
apache-2.0
wbond/subversion,wbond/subversion,YueLinHo/Subversion,YueLinHo/Subversion,YueLinHo/Subversion,wbond/subversion,wbond/subversion,YueLinHo/Subversion,YueLinHo/Subversion,wbond/subversion,wbond/subversion,YueLinHo/Subversion,wbond/subversion,YueLinHo/Subversion,YueLinHo/Subversion
b1b02a65cded26e7b0a6ddf207def5522297f7a7
__openerp__.py
__openerp__.py
# -*- coding: utf-8 -*- ############################################################################## # ############################################################################## { 'name': u"Asset Streamline", 'version': u"0.1", 'author': u"XCG Consulting", 'category': u"Custom Module", 'descri...
# -*- coding: utf-8 -*- ############################################################################## # ############################################################################## { 'name': u"Asset Streamline", 'version': u"1.0", 'author': u"XCG Consulting", 'category': u"Custom Module", 'descri...
Add dependency for 'analytic_structure' and change version to 1.0
Add dependency for 'analytic_structure' and change version to 1.0
Python
agpl-3.0
xcgd/account_asset_streamline
0c60434dc573b5770b8061751771c773032a4f76
salt/output/__init__.py
salt/output/__init__.py
''' Used to manage the outputter system. This package is the modular system used for managing outputters. ''' # Import salt utils import salt.loader def display_output(data, out, opts=None): ''' Print the passed data using the desired output ''' get_printout(out, opts)(data) def get_printout(out, o...
''' Used to manage the outputter system. This package is the modular system used for managing outputters. ''' # Import salt utils import salt.loader STATIC = ( 'yaml_out', 'txt_out', 'raw_out', 'json_out', ) def display_output(data, out, opts=None): ''' Prin...
Handle output passthrou from the cli
Handle output passthrou from the cli
Python
apache-2.0
saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt
9c058304c9ad1ad8c9220bc9f098a9dcf80700b9
valohai_yaml/objs/pipelines/execution_node.py
valohai_yaml/objs/pipelines/execution_node.py
from .node import Node class ExecutionNode(Node): type = 'execution' def __init__(self, name, step, override=None): if override is None: override = {} self.name = name self.step = step self.override = override
from .node import Node class ExecutionNode(Node): type = 'execution' def __init__(self, name, step, override=None): if override is None: override = {} self.name = name self.step = step self.override = override def lint(self, lint_result, context): supe...
Add linting for pipeline step existence
Add linting for pipeline step existence
Python
mit
valohai/valohai-yaml
4db714570a9ce58a08c72aa1477e9e7a48ed650c
tests/util_tests.py
tests/util_tests.py
# -*- coding: utf-8 -*- from chai import Chai from arrow import util class UtilTests(Chai): def test_is_timestamp(self): timestamp_float = 1563047716.958061 timestamp_int = int(timestamp_float) self.assertTrue(util.is_timestamp(timestamp_int)) self.assertTrue(util.is_timestamp(ti...
# -*- coding: utf-8 -*- import time from chai import Chai from arrow import util class UtilTests(Chai): def test_is_timestamp(self): timestamp_float = time.time() timestamp_int = int(timestamp_float) self.assertTrue(util.is_timestamp(timestamp_int)) self.assertTrue(util.is_times...
Replace hard coded timestamp with time.time()
Replace hard coded timestamp with time.time()
Python
apache-2.0
crsmithdev/arrow
7a172a7fe98223fd20a4bb5d497aa17653b8a13b
dev_tools/coverage_runner.py
dev_tools/coverage_runner.py
"""Run tests under coverage's measurement system (Used in CI) """ import os import sys from os.path import join, realpath # Third Party modules import nose import coverage cov = coverage.coverage(branch=True) cov.start() result = nose.run(defaultTest=realpath(join(__file__, "..", "..", "py2c"))) cov.stop() cov.save...
"""Run tests under coverage's measurement system (Used in CI) """ import os import sys from os.path import join, realpath # Third Party modules import nose import coverage cov = coverage.coverage(branch=True) cov.start() success = nose.run(defaultTest=realpath(join(__file__, "..", "..", "py2c"))) cov.stop() cov.sav...
Correct the usage of nose.run.
[TRAVIS] Correct the usage of nose.run. nose.run returns whether the test run was sucessful or not.
Python
bsd-3-clause
pradyunsg/Py2C,pradyunsg/Py2C
bd0800d46126d963f1ae107924a632752bc94173
indra/sources/bel/__init__.py
indra/sources/bel/__init__.py
from .api import process_ndex_neighborhood from .api import process_belrdf from .api import process_belscript from .api import process_pybel_graph from .api import process_json_file from .api import process_pybel_neighborhood
from .api import process_ndex_neighborhood, process_belrdf, \ process_belscript, process_pybel_graph, process_json_file, \ process_pybel_neighborhood, process_cbn_jgif_file
Add all endpoints to BEL API
Add all endpoints to BEL API
Python
bsd-2-clause
johnbachman/indra,sorgerlab/indra,bgyori/indra,bgyori/indra,johnbachman/indra,sorgerlab/indra,johnbachman/belpy,bgyori/indra,sorgerlab/belpy,sorgerlab/belpy,johnbachman/belpy,johnbachman/belpy,sorgerlab/belpy,johnbachman/indra,sorgerlab/indra
bcbe4f9d91ef386b5a09d99e9c0c22b4dfcdc09b
dmf_device_ui/__init__.py
dmf_device_ui/__init__.py
# -*- coding: utf-8 -*- import gtk import uuid def gtk_wait(wait_duration_s): gtk.main_iteration_do() def generate_plugin_name(prefix='plugin-'): ''' Generate unique plugin name. ''' return prefix + str(uuid.uuid4()).split('-')[0]
# -*- coding: utf-8 -*- from pygtkhelpers.utils import refresh_gui import uuid def gtk_wait(wait_duration_s): refresh_gui() def generate_plugin_name(prefix='plugin-'): ''' Generate unique plugin name. ''' return prefix + str(uuid.uuid4()).split('-')[0]
Use pygtkhelpers refresh_gui in gtk_wait
Use pygtkhelpers refresh_gui in gtk_wait
Python
lgpl-2.1
wheeler-microfluidics/dmf-device-ui
30be8d71fee8f7429d6b4d48a8168133062e3315
text_test/regex_utils_test.py
text_test/regex_utils_test.py
# coding=utf-8 import unittest from text import regex_utils class RegexUtilsTest(unittest.TestCase): def test_check_line(self): pass def test_parse_line(self): pass if __name__ == '__main__': # import sys;sys.argv = ['', 'Test.testName'] unittest.main()
# coding=utf-8 import unittest from text import regex_utils class RegexUtilsTest(unittest.TestCase): def test_check_line(self): self.assertTrue(regex_utils.check_line('.*(\d+.\d+.\d+.\d+)', 'MyIP is 192.168.199.4')) self.assertTrue(regex_utils.check_line('Test (Data|Case) For (py-text|py-task)', ...
Update regex_utils unit test case
Update regex_utils unit test case
Python
apache-2.0
PinaeOS/py-text,interhui/py-text
47088dd1ed69207e6e74af98c1f6a4124493ed0c
forum/forms.py
forum/forms.py
from django.forms import ModelForm,Textarea,TextInput from .models import Post class PostForm(ModelForm): class Meta: model = Post fields = ('subject','body') widgets = { 'subject': TextInput(attrs={'autofocus':'autofocus'}), 'body': Textarea( ...
from django.forms import ModelForm,Textarea,TextInput from .models import Post class PostForm(ModelForm): class Meta: model = Post fields = ('subject','body') widgets = { 'subject': TextInput(attrs={'autofocus':'autofocus'}), 'body': Textarea( ...
Use Octicons in Markdown editor
Use Octicons in Markdown editor
Python
mit
Kromey/fbxnano,Kromey/fbxnano,Kromey/akwriters,Kromey/akwriters,Kromey/akwriters,Kromey/fbxnano,Kromey/fbxnano,Kromey/akwriters
aa242ab8451887fe8a4ddfa223d0e11c8c3a472f
lilkv/columnfamily.py
lilkv/columnfamily.py
# -*- coding: utf-8 -*- """ lilkv.columnfamily This module implements the client-facing aspect of the `lilkv` app. All requests are handled through this interface. """ class ColumnFamily(object): """Column Family objects store information about all rows. daily_purchases_cf = ColumnFamily("daily...
# -*- coding: utf-8 -*- """ lilkv.columnfamily This module implements the client-facing aspect of the `lilkv` app. All requests are handled through this interface. """ class ColumnFamily(object): """Column Family objects store information about all rows. daily_purchases_cf = ColumnFamily("daily...
Define inserts and deletes on CFs.
Define inserts and deletes on CFs.
Python
mit
pgorla/lil-kv
b52523b78b7ebc5358cb3dc9aa257cc5b3fbbb72
blog/models.py
blog/models.py
from django.db import models from django.utils import timezone class Post(models.Model): title = models.CharField(max_length=200) author = models.CharField(max_length=100) tags = models.CharField(max_length=200) pub_date = models.DateTimeField(blank=True, null=True) text = models.TextField() d...
from django.db import models from django.utils import timezone class Post(models.Model): title = models.CharField(max_length=200) pub_date = models.DateTimeField(blank=True, null=True) text = models.TextField() def __str__(self): return self.title
Remove tags and fixed .gitignore
Remove tags and fixed .gitignore
Python
mit
DLance96/django-blog,DLance96/django-blog,DLance96/django-blog
12c57e52d3f107ce9723f33e7f35ef752bb8f3bc
axelrod/tests/unit/test_deterministic_cache.py
axelrod/tests/unit/test_deterministic_cache.py
import unittest class TestDeterministicCache(unittest.TestCase): def test_init(self): pass def test_setitem(self): pass def test_save(self): pass def test_load(self): pass
import unittest from axelrod import DeterministicCache, TitForTat, Defector class TestDeterministicCache(unittest.TestCase): @classmethod def setUpClass(cls): cls.test_key1 = (TitForTat, Defector) cls.test_value1 = [('C', 'D'), ('D', 'D'), ('D', 'D')] def test_basic_init(self): c...
Add content for basic tests
Add content for basic tests
Python
mit
ranjinidas/Axelrod,marcharper/Axelrod,ranjinidas/Axelrod,marcharper/Axelrod
63fe76240a819a0211aab566c1cd36b31c49c5d9
freepacktbook/pushover.py
freepacktbook/pushover.py
import json import requests class PushoverNotification(object): def __init__(self, pushover_user, pushover_token): self.pushover_api = 'https://api.pushover.net/1/messages.json' self.pushover_user = pushover_user self.pushover_token = pushover_token def get_image_content(self, image_u...
import json import requests class PushoverNotification(object): def __init__(self, pushover_user, pushover_token): self.pushover_api = 'https://api.pushover.net/1/messages.json' self.pushover_user = pushover_user self.pushover_token = pushover_token def get_image_content(self, image_u...
Fix syntax error and reuse variable
Fix syntax error and reuse variable
Python
mit
bogdal/freepacktbook
8404ced0a54df6ab4be3f6d10a4d1201d2105f09
fusesoc/build/__init__.py
fusesoc/build/__init__.py
from fusesoc.build.quartus import Quartus from fusesoc.build.ise import Ise def BackendFactory(system): if system.backend_name == 'quartus': return Quartus(system) elif system.backend_name == 'ise': return Ise(system) else: raise Exception("Backend not found")
from fusesoc.build.quartus import Quartus from fusesoc.build.ise import Ise def BackendFactory(system): if system.backend_name == 'quartus': return Quartus(system) elif system.backend_name == 'ise': return Ise(system) else: raise RuntimeError('Backend "{}" not found'.format(systaem....
Improve error handling for unknown backends
Improve error handling for unknown backends
Python
bsd-2-clause
olofk/fusesoc,lowRISC/fusesoc,olofk/fusesoc,lowRISC/fusesoc
8f094e1c3d4a64942cadf5603ce5b23706381fac
nubes/cmd/__init__.py
nubes/cmd/__init__.py
import openstack def main(): print("Hello Clouds!")
import argparse from nubes import dispatcher def main(): parser = argparse.ArgumentParser(description='Universal IaaS CLI') parser.add_argument('connector', help='IaaS Name') parser.add_argument('resource', help='Resource to perform action') parser.add_argument('action', help='Action to perform on re...
Make crude CLI commands work
Make crude CLI commands work This is mainly as an example to show what it can look like.
Python
apache-2.0
omninubes/nubes
15a9d8b9e361462532ed286abce4ee445b9ec74a
analytics/rejections.py
analytics/rejections.py
# -*- encoding: utf-8 """ I get a bunch of requests that are uninteresting for some reason -- maybe somebody trying to find a PHP admin page, or crawling for vulnerable WordPress instances. Any such request can immediately be rejected as uninteresting for my analytics. """ from urllib.parse import urlparse BAD_PATH...
# -*- encoding: utf-8 """ I get a bunch of requests that are uninteresting for some reason -- maybe somebody trying to find a PHP admin page, or crawling for vulnerable WordPress instances. Any such request can immediately be rejected as uninteresting for my analytics. """ from urllib.parse import urlparse BAD_PATH...
Add more to the list of bad paths
Add more to the list of bad paths
Python
mit
alexwlchan/alexwlchan.net,alexwlchan/alexwlchan.net,alexwlchan/alexwlchan.net,alexwlchan/alexwlchan.net,alexwlchan/alexwlchan.net
8f0befc2bd6e42c544e30630a82fdcec291dfe1f
judge/telerik_academy_auth.py
judge/telerik_academy_auth.py
from django.contrib.auth.models import User from dmoj import settings import json import requests from judge.models import Profile, Language class RemoteUserBackend (object): def get_login_url(self, api_key, username, password): return 'https://telerikacademy.com/Api/Users/CheckUserLogin?apiKey=%s&use...
from django.contrib.auth.models import User from dmoj import settings import json import requests from judge.models import Profile, Language class RemoteUserBackend (object): def get_login_url(self, api_key, username, password): return 'https://telerikacademy.com/Api/Users/CheckUserLogin?apiKey=%s&use...
Use username provided by telerik academy auth API
Use username provided by telerik academy auth API
Python
agpl-3.0
Minkov/site,Minkov/site,Minkov/site,Minkov/site
958a134bd5e68ac94e3f4f25d4587e357d9a7ba5
download_data.py
download_data.py
# coding: utf-8 """ Script to download the raw data from http://www.rsssf.com/ The data was processed mostly by interactive sessions in ipython. Almost every file had it's own format, so there is no point in trying to automate it in a fully automatic script, but this downloading script may be useful for future dowloads...
# coding: utf-8 """ Script to download the raw data from http://www.rsssf.com/ The data was processed mostly by interactive sessions in ipython. Almost every file had it's own format, so there is no point in trying to automate it in a fully automatic script, but this downloading script may be useful for future dowloads...
Use nltk to extract text from html data
Use nltk to extract text from html data
Python
mit
fisadev/afa_cup_learning
4212b19910e627b48df2c50389b5c8e46250c568
girder_worker/__init__.py
girder_worker/__init__.py
import abc import os from pkg_resources import DistributionNotFound, get_distribution from six.moves.configparser import SafeConfigParser from . import log_utils try: __version__ = get_distribution(__name__).version except DistributionNotFound: # package is not installed pass __license__ = 'Apache 2.0'...
import abc import os from pkg_resources import DistributionNotFound, get_distribution from six.moves.configparser import SafeConfigParser, add_metaclass from . import log_utils try: __version__ = get_distribution(__name__).version except DistributionNotFound: # package is not installed pass __license__...
Use six to add meta class
Use six to add meta class
Python
apache-2.0
girder/girder_worker,girder/girder_worker,girder/girder_worker
7638f03dfe347866d62ede55d0163e7593f9e6c9
waterbutler/core/__init__.py
waterbutler/core/__init__.py
from waterbutler.core.utils import async_retry from waterbutler.core.utils import make_provider __all__ = [ 'async_retry', 'make_provider', ]
# from waterbutler.core.utils import async_retry # from waterbutler.core.utils import make_provider # __all__ = [ # 'async_retry', # 'make_provider', # ]
Remove __all__ as it was not used and causing circular import errors when attempting to configure logging
Remove __all__ as it was not used and causing circular import errors when attempting to configure logging
Python
apache-2.0
TomBaxter/waterbutler,Johnetordoff/waterbutler,RCOSDP/waterbutler,kwierman/waterbutler,CenterForOpenScience/waterbutler,rdhyee/waterbutler,Ghalko/waterbutler,felliott/waterbutler,rafaeldelucena/waterbutler,hmoco/waterbutler,cosenal/waterbutler,icereval/waterbutler,chrisseto/waterbutler
4fe675af1cc8eb65f843e06962763dab8c920ce5
contrib/meson/GetLz4LibraryVersion.py
contrib/meson/GetLz4LibraryVersion.py
#!/usr/bin/env python3 # ############################################################################# # Copyright (c) 2018-present lzutao <taolzu(at)gmail.com> # All rights reserved. # # This source code is licensed under both the BSD-style license (found in the # LICENSE file in the root directory of this source t...
#!/usr/bin/env python3 # ############################################################################# # Copyright (c) 2018-present lzutao <taolzu(at)gmail.com> # All rights reserved. # # This source code is licensed under both the BSD-style license (found in the # LICENSE file in the root directory of this source t...
Use argparse instead of manually parsing
Use argparse instead of manually parsing [skip ci]
Python
isc
unknownbrackets/maxcso,unknownbrackets/maxcso,unknownbrackets/maxcso,unknownbrackets/maxcso,unknownbrackets/maxcso,unknownbrackets/maxcso,unknownbrackets/maxcso
b03b62e7abe9a8db0cded78b80cb8d565a424a7e
apps/activity/models.py
apps/activity/models.py
from django.db import models class Activity(models.Model): entry = models.ForeignKey('feeds.Entry', blank=True, null=True, unique=True) published_on = models.DateTimeField(auto_now_add=True) def __unicode__(self): return u'%s:%s => %s' % (self.source_class, self.sour...
from django.db import models class Activity(models.Model): entry = models.ForeignKey('feeds.Entry', blank=True, null=True, unique=True) published_on = models.DateTimeField(auto_now_add=True) def __unicode__(self): return u'%d: Entry: %s' % (self.pk, self.entry) def...
Remove reference to old field and unused method
Remove reference to old field and unused method
Python
bsd-3-clause
mozilla/betafarm,mozilla/mozilla-ignite,mozilla/mozilla-ignite,mozilla/mozilla-ignite,mozilla/betafarm,mozilla/betafarm,mozilla/betafarm,mozilla/mozilla-ignite
3504bd0c867841c85f5ef54cdb5096ec5117cc1e
backend/scripts/projsize.py
backend/scripts/projsize.py
#!/usr/bin/env python import rethinkdb as r from optparse import OptionParser def compute_project_size(project_id, conn): total = 0 for f in r.table('project2datafile').get_all(project_id, index="project_id").eq_join('datafile_id', r.table( 'datafiles')).zip().run(conn): total = total + f...
#!/usr/bin/env python import rethinkdb as r from optparse import OptionParser def compute_project_size(project_id, conn): total = 0 count = 0 for f in r.table('project2datafile').get_all(project_id, index="project_id").eq_join('datafile_id', r.table( 'datafiles')).zip().run(conn): tot...
Improve report format and information
Improve report format and information Include total number of files.
Python
mit
materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org
06effd31b4f52f1f61114c03ba8b1d6ce51738ab
zou/app/utils/permissions.py
zou/app/utils/permissions.py
from flask_principal import RoleNeed, Permission from werkzeug.exceptions import Forbidden admin_permission = Permission(RoleNeed('admin')) manager_permission = Permission(RoleNeed('manager')) class PermissionDenied(Forbidden): pass def has_manager_permissions(): return admin_permission.can() or manager_pe...
from flask_principal import RoleNeed, Permission from werkzeug.exceptions import Forbidden admin_permission = Permission(RoleNeed('admin')) manager_permission = Permission(RoleNeed('manager')) class PermissionDenied(Forbidden): pass def has_manager_permissions(): """ Return True if user is admin or man...
Add comments to permission utils
Add comments to permission utils
Python
agpl-3.0
cgwire/zou
5f21b5f387e895a9af2ac8481bd495f2dacd6cdf
carbonate/util.py
carbonate/util.py
import fileinput import os import socket import argparse def local_addresses(): ips = socket.gethostbyname_ex(socket.gethostname())[2] return set([ip for ip in ips if not ip.startswith("127.")][:1]) def common_parser(description='untitled'): parser = argparse.ArgumentParser( description=descript...
import fileinput import os import socket import argparse def local_addresses(): ips = socket.gethostbyname_ex(socket.gethostname())[2] return set([ip for ip in ips if not ip.startswith("127.")][:1]) def common_parser(description='untitled'): parser = argparse.ArgumentParser( description=descript...
Read config-file and cluster options from environ
Read config-file and cluster options from environ This would make it DRY in scripts/wrappers with non-default values.
Python
mit
jssjr/carbonate,criteo-forks/carbonate,ross/carbonate,criteo-forks/carbonate,graphite-project/carbonate,unbrice/carbonate,criteo-forks/carbonate,deniszh/carbonate,graphite-project/carbonate,jssjr/carbonate,deniszh/carbonate,unbrice/carbonate,deniszh/carbonate,jssjr/carbonate,ross/carbonate,graphite-project/carbonate,un...
355b1a91edf2dfcff66c2a02e034977f65d0690c
influxdb/dataframe_client.py
influxdb/dataframe_client.py
# -*- coding: utf-8 -*- """ DataFrame client for InfluxDB """ from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals __all__ = ['DataFrameClient'] try: import pandas del pandas except ImportError as err: from .cl...
# -*- coding: utf-8 -*- """ DataFrame client for InfluxDB """ from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals __all__ = ['DataFrameClient'] try: import pandas del pandas except ImportError as err: from .cl...
Fix DataFrameClient import error on python3.5
Fix DataFrameClient import error on python3.5
Python
mit
BenHewins/influxdb-python,omki2005/influxdb-python,omki2005/influxdb-python,Asimmetric/influxdb-python,tzonghao/influxdb-python,influxdata/influxdb-python,Asimmetric/influxdb-python,tzonghao/influxdb-python,BenHewins/influxdb-python,influxdb/influxdb-python,influxdata/influxdb-python,influxdb/influxdb-python
853bf035fcb9ea21e648cb0b1d1b13ee68f8e9cc
importer/tests/test_utils.py
importer/tests/test_utils.py
from unittest import TestCase from importer.utils import find_first class FindFirstTestCase(TestCase): def test_first_in_haystack(self): self.assertEqual( find_first( ['one', 'two', 'three'], ['one', 'four'] ), 'one', ) def ...
from unittest import TestCase from importer.utils import ( maybe, find_first, ) class MaybeTestCase(TestCase): def setUp(self): self.add_ten = maybe(lambda x: x + 10) def test_with_none(self): self.assertIsNone(self.add_ten(None)) def test_with_different_value(self): sel...
Add tests for maybe decorator
Add tests for maybe decorator
Python
mit
despawnerer/theatrics,despawnerer/theatrics,despawnerer/theatrics
7e4227b304da4313a3114a95d361fc5bb6bf5529
runtests.py
runtests.py
from django.conf import settings try: import honeypot except ImportError: honeypot = None if not settings.configured: INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.message...
from django.conf import settings try: import honeypot except ImportError: honeypot = None if not settings.configured: INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.message...
Test speedup by swapping password hasher.
Test speedup by swapping password hasher.
Python
mit
r4ts0n/django-envelope,zsiciarz/django-envelope,r4ts0n/django-envelope,zsiciarz/django-envelope
2d4b6b1fa84f7530d064bfc5577d61430b4e5a34
run_multip.py
run_multip.py
# -*- coding:utf-8 -*- from subprocess import check_output from multiprocessing import Pool from os import listdir, mkdir, path from sys import argv def run_simu((psfile, dir_runs)): """Runs the main script with specified parameter file.""" ndir = psfile[:-3] mkdir(ndir) simu_output = check_output(["p...
# -*- coding:utf-8 -*- """ Script for running multiple simulation with different parameter set. """ from subprocess import check_output from multiprocessing import Pool from os import listdir, mkdir, path from sys import argv def run_simu((psfile, dir_runs)): """Runs the main script with specified parameter file...
Clean main multi simulation script
Clean main multi simulation script
Python
mit
neuro-lyon/multiglom-model,neuro-lyon/multiglom-model
adb6c4c86407d6c66e8679aefdf2f2f0c9c87277
pltpreview/view.py
pltpreview/view.py
"""Convenience functions for matplotlib plotting and image viewing.""" import numpy as np from matplotlib import pyplot as plt def show(image, blocking=False, **kwargs): """Show *image*. If *blocking* is False the call is nonblocking. *kwargs* are passed to matplotlib's ``imshow`` function. This command a...
"""Convenience functions for matplotlib plotting and image viewing.""" import numpy as np from matplotlib import pyplot as plt def show(image, blocking=False, **kwargs): """Show *image*. If *blocking* is False the call is nonblocking. *kwargs* are passed to matplotlib's ``imshow`` function. This command a...
Return lines from plot command
Return lines from plot command
Python
mit
tfarago/pltpreview
c61cace4106a8cf9a27099acbfae26ba2a727d65
install_steps/run_errands.py
install_steps/run_errands.py
import bosh_client import os import yaml def do_step(context): settings = context.meta['settings'] username = settings["username"] home_dir = os.path.join("/home", username) f = open('manifests/index.yml') manifests = yaml.safe_load(f) f.close() client = bosh_client.BoshClient("https://1...
import bosh_client import os import yaml def do_step(context): settings = context.meta['settings'] username = settings["username"] home_dir = os.path.join("/home", username) f = open('manifests/index.yml') manifests = yaml.safe_load(f) f.close() client = bosh_client.BoshClient("https://1...
Convert task output to UTF8
Convert task output to UTF8
Python
apache-2.0
cf-platform-eng/bosh-azure-template,cf-platform-eng/bosh-azure-template
9a7de89fd4bc6d134f30bdee4c8a71b34e1e6ab9
stoq/__init__.py
stoq/__init__.py
#!/usr/bin/env python3 # Copyright 2014-2018 PUNCH Cyber Analytics Group # # 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 # # Un...
#!/usr/bin/env python3 # Copyright 2014-2018 PUNCH Cyber Analytics Group # # 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 # # Un...
Add StoqPluginException to default imports
Add StoqPluginException to default imports
Python
apache-2.0
PUNCH-Cyber/stoq
ea02f8e714df34da0ff55a8c9750eb0d992875c2
feincms3/apps.py
feincms3/apps.py
# pragma: no cover import warnings import django if django.VERSION < (3, 2): from feincms3.applications import * # noqa warnings.warn( "Django 3.2 will start autodiscovering app configs inside '.apps' modules." " We cannot continue using feincms3.apps because the AppsMixin inside this" ...
import warnings import django if django.VERSION < (3, 2): from feincms3.applications import * # noqa warnings.warn( "Django 3.2 will start autodiscovering app configs inside '.apps' modules." " We cannot continue using feincms3.apps because the AppsMixin inside this" " module can on...
Remove a no cover pragma having no effect (since the pragma only affects the current line)
Remove a no cover pragma having no effect (since the pragma only affects the current line)
Python
bsd-3-clause
matthiask/feincms3,matthiask/feincms3,matthiask/feincms3
bea83c533f65eeedae983b70fd41350e57df6908
cms/djangoapps/contentstore/features/video-editor.py
cms/djangoapps/contentstore/features/video-editor.py
# disable missing docstring #pylint: disable=C0111 from lettuce import world, step @step('I see the correct settings and default values$') def i_see_the_correct_settings_and_values(step): world.verify_all_setting_entries([['.75x', '', False], ['1.25x', '', False], ...
# disable missing docstring #pylint: disable=C0111 from lettuce import world, step @step('I see the correct settings and default values$') def i_see_the_correct_settings_and_values(step): world.verify_all_setting_entries([['Default Speed', '', False], ['Display Name', 'defau...
Update failing metadata settings acceptance test.
Update failing metadata settings acceptance test.
Python
agpl-3.0
bitifirefly/edx-platform,jonathan-beard/edx-platform,arbrandes/edx-platform,xuxiao19910803/edx-platform,zhenzhai/edx-platform,jazztpt/edx-platform,doismellburning/edx-platform,apigee/edx-platform,jbassen/edx-platform,inares/edx-platform,stvstnfrd/edx-platform,Edraak/edx-platform,a-parhom/edx-platform,etzhou/edx-platfor...
6b6fb12545ff3b35420fd2382576a6150044bdc8
kerze.py
kerze.py
from turtle import * GROESSE = 0.5 FARBE = "red" FAERBEN = True SHAPE = "turtle" fillcolor(FARBE) shape(SHAPE) def zeichneKerze(brennt): pd() begin_fill() forward(GROESSE*100) left(90) forward(GROESSE*400) left(90) forward(GROESSE*100) right(90) forward(GROESSE*30) back(GROESS...
from turtle import * GROESSE = 0.5 FARBE = "red" FAERBEN = True SHAPE = "turtle" fillcolor(FARBE) shape(SHAPE) def zeichneKerze(brennt): pd() begin_fill() forward(GROESSE*100) left(90) forward(GROESSE*400) left(90) forward(GROESSE*100) right(90) forward(GROESSE*30) back(GROESS...
Prepare for use as module
Prepare for use as module
Python
mit
luforst/adventskranz
204c955b7150e3ef26f44e1982359b2d6096eebe
lc053_maximum_subarray.py
lc053_maximum_subarray.py
"""Leetcode 53. Maximum Subarray Easy Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum. Example: Input: [-2,1,-3,4,-1,2,1,-5,4], Output: 6 Explanation: [4,-1,2,1] has the largest sum = 6. Follow up: If you have figured out the O(...
"""Leetcode 53. Maximum Subarray Easy Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum. Example: Input: [-2,1,-3,4,-1,2,1,-5,4], Output: 6 Explanation: [4,-1,2,1] has the largest sum = 6. Follow up: If you have figured out the O(...
Complete max subarray sum by DP
Complete max subarray sum by DP
Python
bsd-2-clause
bowen0701/algorithms_data_structures
5c7161858fa7ca2962f08b66f6d20ae49715c206
ci_scripts/buildLinuxWheels.py
ci_scripts/buildLinuxWheels.py
from subprocess import call, check_output import sys isPython3 = sys.version_info.major == 3 # https://stackoverflow.com/a/3357357 command = 'git log --format=%B -n 1'.split() out = check_output(command) if b'build wheels' not in out.lower() or not isPython3: exit(0) path = os.path.abspath(argv[1]) call('pip in...
from subprocess import call, check_output import sys import os isPython3 = sys.version_info.major == 3 # https://stackoverflow.com/a/3357357 command = 'git log --format=%B -n 1'.split() out = check_output(command) if b'build wheels' not in out.lower() or not isPython3: exit(0) path = os.path.abspath(argv[1]) ca...
Fix build wheels and upload 3.
Fix build wheels and upload 3.
Python
bsd-3-clause
jr-garcia/AssimpCy,jr-garcia/AssimpCy
7f6cd8f5444d92644642cadb84d7f958e0b6fce1
examples/image_test.py
examples/image_test.py
import sys import os import pyglet.window from pyglet.gl import * from pyglet import clock from pyglet.ext.scene2d import Image2d from ctypes import * if len(sys.argv) != 2: print 'Usage: %s <PNG/JPEG filename>'%sys.argv[0] sys.exit() window = pyglet.window.Window(width=400, height=400) image = Image2d.loa...
import sys import os import ctypes import pyglet.window from pyglet.gl import * from pyglet import clock from pyglet import image if len(sys.argv) != 2: print 'Usage: %s <PNG/JPEG filename>'%sys.argv[0] sys.exit() window = pyglet.window.Window(width=400, height=400) image = image.load(sys.argv[1]) imx = imy ...
Use the core, make example more useful.
Use the core, make example more useful. git-svn-id: d4fdfcd4de20a449196f78acc655f735742cd30d@874 14d46d22-621c-0410-bb3d-6f67920f7d95
Python
bsd-3-clause
regular/pyglet-avbin-optimizations,regular/pyglet-avbin-optimizations,regular/pyglet-avbin-optimizations,regular/pyglet-avbin-optimizations
fffce05288a80b4d4e8e45b6a1282eaa6c2d80c4
dec02/dec02part2.py
dec02/dec02part2.py
# Advent of Code # Dec 2, Part 2 # @geekygirlsarah
# Advent of Code # Dec 2, Part 1 # @geekygirlsarah inputFile = "input.txt" # Tracking vars finalCode = "" lastNumber = 5 # start here tempNumber = lastNumber with open(inputFile) as f: while True: line = f.readline(-1) if not line: # print "End of file" break ...
Add 12/2 part 2 solution
Add 12/2 part 2 solution
Python
mit
geekygirlsarah/adventofcode2016
c88310e970518c3531dbe26c9544ff4455068a7e
opps/core/tests/test_obj_tags.py
opps/core/tests/test_obj_tags.py
from django.test import TestCase from opps.channels.templatetags.menu_tags import ofKey class OfKeyTest(TestCase): def test_tag(self): result = ofKey({"name": "andrews"}, "name") self.assertEqual(result, "andrews") def test_tag_is_none(self): result = ofKey(None, "name") self...
from django.test import TestCase from opps.core.templatetags.obj_tags import ofKey class OfKeyTest(TestCase): def test_tag(self): result = ofKey({"name": "andrews"}, "name") self.assertEqual(result, "andrews") def test_tag_is_none(self): result = ofKey(None, "name") self.asse...
Fix import template tag obj_tags on test case core
Fix import template tag obj_tags on test case core
Python
mit
williamroot/opps,YACOWS/opps,opps/opps,williamroot/opps,williamroot/opps,YACOWS/opps,YACOWS/opps,williamroot/opps,jeanmask/opps,jeanmask/opps,opps/opps,YACOWS/opps,jeanmask/opps,opps/opps,opps/opps,jeanmask/opps
ee6bd389e3e602b67fac399cdb4a50c3a67666b9
twitter/admin.py
twitter/admin.py
from django.contrib import admin from twitter.models import User, Tweet, Analytics, AnalyticsReport class UserAdmin(admin.ModelAdmin): list_display = ('screen_name', 'current_followers') class AnalyticsAdmin(admin.ModelAdmin): list_display = ( 'date', 'user', 'followers', 'fo...
from django.contrib import admin from twitter.models import User, Tweet, Analytics, AnalyticsReport class UserAdmin(admin.ModelAdmin): list_display = ('screen_name', 'current_followers') class AnalyticsAdmin(admin.ModelAdmin): list_display = ( 'date', 'user', 'followers', 'fo...
Add a list filter to make looking a specific users easier.
Add a list filter to make looking a specific users easier.
Python
mit
CIGIHub/tweet_cache,albertoconnor/tweet_cache
0e866db1377e4c58ef05d66583cea6e35071ba20
nnpy/errors.py
nnpy/errors.py
from _nnpy import ffi, lib as nanomsg class NNError(Exception): def __init__(self, error_no, *args, **kwargs): super().__init__(*args, **kwargs) self.error_no = error_no def convert(rc, value=None): if rc < 0: error_no = nanomsg.nn_errno() chars = nanomsg.nn_strerror(error_no) ...
from _nnpy import ffi, lib as nanomsg class NNError(Exception): def __init__(self, error_no, *args, **kwargs): super(NNError, self).__init__(*args, **kwargs) self.error_no = error_no def convert(rc, value=None): if rc < 0: error_no = nanomsg.nn_errno() chars = nanomsg.nn_strerr...
Fix incorrect args to super
Fix incorrect args to super
Python
mit
nanomsg/nnpy
6557cbe8bee7ded848ba7c3928e2b4f82aedeea8
linked-list/remove-k-from-list.py
linked-list/remove-k-from-list.py
# Given a singly linked list of integers l and an integer k, remove all elements from list l that have a value equal to k class Node(object): def __init__(self, value): self.value = value self.next = None def remove_k_from_list(l, k): fake_head = Node(None) fake_head.next = l current_node = fake_head while ...
# Given a singly linked list of integers l and an integer k, remove all elements from list l that have a value equal to k class Node(object): # define constructor def __init__(self, value): self.value = value self.next = None class LinkedList(object): def __init__(self, head=None): self.head = head def add(...
Add linked list class and add method
Add linked list class and add method
Python
mit
derekmpham/interview-prep,derekmpham/interview-prep
06c7e43f96f9394949b0ec1ed709429ab3167cf9
incuna_auth/backends.py
incuna_auth/backends.py
from django.contrib.auth.backends import ModelBackend from django.contrib.auth.models import User class CustomUserModelBackend(ModelBackend): def authenticate(self, username=None, password=None): """Allow users to log in with their email as well as username.""" kw = 'email__iexact' if '@' in usern...
from django.contrib.auth.backends import ModelBackend try: from django.contrib.auth import get_user_model User = get_user_model() except ImportError: # Django < 1.5 from django.contrib.auth.models import User class CustomUserModelBackend(ModelBackend): def authenticate(self, username=None, passwor...
Make the CustomerUserModelBackend Dj1.5 compatible
Make the CustomerUserModelBackend Dj1.5 compatible
Python
bsd-2-clause
incuna/incuna-auth,ghickman/incuna-auth,ghickman/incuna-auth,incuna/incuna-auth
6a717adf087f847ae4a58375170d01adf5ef17de
polyaxon/factories/pipelines.py
polyaxon/factories/pipelines.py
import factory from factories.factory_projects import ProjectFactory from factories.factory_users import UserFactory from pipelines.models import Pipeline, Operation class PipelineFactory(factory.DjangoModelFactory): user = factory.SubFactory(UserFactory) project = factory.SubFactory(ProjectFactory) cla...
import factory from factories.factory_projects import ProjectFactory from factories.factory_users import UserFactory from pipelines.models import Pipeline, Operation, PipelineRun, OperationRun class PipelineFactory(factory.DjangoModelFactory): user = factory.SubFactory(UserFactory) project = factory.SubFacto...
Add pipeline run and operation run factories
Add pipeline run and operation run factories
Python
apache-2.0
polyaxon/polyaxon,polyaxon/polyaxon,polyaxon/polyaxon
08ac56dc6d80560ec46ad06fec6843be18bb1d91
dictionary/test1.py
dictionary/test1.py
#!/usr/local/bin/python #items=[('a','b'),(1,2)] #b=dict(items) #print b #c=dict(name='c',age=42) #print c #print len(c) #c['sex']='female' #print c #del c['age'] #print c #print 'sex' in c #c['age']=25 #print c #print c.clear() #print c #x={'name':'a','age':'14'} #y=x #print y #z=y.copy() #z.clear() #print x #print y ...
#!/usr/local/bin/python #items=[('a','b'),(1,2)] #b=dict(items) #print b #c=dict(name='c',age=42) #print c #print len(c) #c['sex']='female' #print c #del c['age'] #print c #print 'sex' in c #c['age']=25 #print c #print c.clear() #print c #x={'name':'a','age':'14'} #y=x #print y #z=y.copy() #z.clear() #print x #print y ...
Use update,get,setdefault and so on.
Use update,get,setdefault and so on.
Python
apache-2.0
Vayne-Lover/Python
a5d2751be278356e2a03fe07f5a1d0aef11b401f
ch07/enrich_airlines.py
ch07/enrich_airlines.py
# Load the on-time parquet file on_time_dataframe = sqlContext.read.parquet('../data/on_time_performance.parquet') wikidata = sqlContext.read.json('../data/wikidata-20160404-all.json.bz2')
# Load the on-time parquet file on_time_dataframe = sqlContext.read.parquet('data/on_time_performance.parquet') # The first step is easily expressed as SQL: get all unique tail numbers for each airline on_time_dataframe.registerTempTable("on_time_performance") carrier_codes = sqlContext.sql( "SELECT DISTINCT Carrier...
Work on chapter 7 enriching airlines with the name of the carrier from the openflights airline data
Work on chapter 7 enriching airlines with the name of the carrier from the openflights airline data
Python
mit
rjurney/Agile_Data_Code_2,naoyak/Agile_Data_Code_2,rjurney/Agile_Data_Code_2,rjurney/Agile_Data_Code_2,naoyak/Agile_Data_Code_2,rjurney/Agile_Data_Code_2,naoyak/Agile_Data_Code_2,naoyak/Agile_Data_Code_2
84ccc5489b4d3dfdf1883bb777cd597bd9cb8e53
src/test/testclasses.py
src/test/testclasses.py
from nose.tools import * from libeeyore.builtins import add_builtins from libeeyore.classvalues import * from libeeyore.environment import EeyEnvironment from libeeyore.cpp.cppvalues import * from libeeyore.cpp.cpprenderer import EeyCppRenderer from eeyasserts import assert_multiline_equal def test_Static_variable_...
from nose.tools import * from libeeyore.builtins import add_builtins from libeeyore.classvalues import * from libeeyore.environment import EeyEnvironment from libeeyore.cpp.cppvalues import * from libeeyore.cpp.cpprenderer import EeyCppRenderer from eeyasserts import assert_multiline_equal def test_Static_variable_...
Add a test that demonstrates calling a function within a class definition.
Add a test that demonstrates calling a function within a class definition.
Python
mit
andybalaam/pepper,andybalaam/pepper,andybalaam/pepper,andybalaam/pepper,andybalaam/pepper
898e087d67ba5f6f8af3f280d46c59edc0bb665e
modules/module_spotify.py
modules/module_spotify.py
import re import urllib def handle_url(bot, user, channel, url, msg): """Handle IMDB urls""" m = re.match("(http:\/\/open.spotify.com\/|spotify:)(album|artist|track)([:\/])([a-zA-Z0-9]+)\/?", url) if not m: return dataurl = "http://spotify.url.fi/%s/%s?txt" % (m.group(2), m.group(4)) f = ur...
import re import urllib def handle_url(bot, user, channel, url, msg): """Handle IMDB urls""" m = re.match("(http:\/\/open.spotify.com\/|spotify:)(album|artist|track)([:\/])([a-zA-Z0-9]+)\/?", url) if not m: return dataurl = "http://spotify.url.fi/%s/%s?txt" % (m.group(2), m.group(4)) f = ur...
Change output format to a more reasonable one
Change output format to a more reasonable one git-svn-id: 056f9092885898c4775d98c479d2d33d00273e45@143 dda364a1-ef19-0410-af65-756c83048fb2
Python
bsd-3-clause
EArmour/pyfibot,nigeljonez/newpyfibot,huqa/pyfibot,lepinkainen/pyfibot,rnyberg/pyfibot,lepinkainen/pyfibot,aapa/pyfibot,aapa/pyfibot,EArmour/pyfibot,rnyberg/pyfibot,huqa/pyfibot
afe792e50e6e30036f1ed718d7c3f5143a1e2da5
adhocracy4/follows/signals.py
adhocracy4/follows/signals.py
from django.conf import settings from django.db.models.signals import post_save from . import models def autofollow_hook(instance, **kwargs): if hasattr(instance.project, 'id'): models.Follow.objects.get_or_create( project=instance.project, creator=instance.creator, de...
from django.apps import apps from django.conf import settings from django.db.models.signals import post_save from . import models def autofollow_hook(instance, **kwargs): if hasattr(instance.project, 'id'): models.Follow.objects.get_or_create( project=instance.project, creator=ins...
Fix setting up AUTO_FOLLOWABLES models
Fix setting up AUTO_FOLLOWABLES models Note that `Signal.connect` expects the model class as the sender argument. Altough while using e.g. `post_save` it also works with a string `"apname.model"`
Python
agpl-3.0
liqd/adhocracy4,liqd/adhocracy4,liqd/adhocracy4,liqd/adhocracy4
817c9634e89be79c5ca4e08ce48c1eb1dd173f46
skimage/viewer/qt/__init__.py
skimage/viewer/qt/__init__.py
import os import warnings qt_api = os.environ.get('QT_API') if qt_api is None: try: import PySide qt_api = 'pyside' except ImportError: try: import PyQt4 qt_api = 'pyqt' except ImportError: qt_api = None # Note that we don't want ...
import os import warnings qt_api = os.environ.get('QT_API') if qt_api is None: try: import PySide qt_api = 'pyside' except ImportError: try: import PyQt4 qt_api = 'pyqt' except ImportError: qt_api = None # Note that we don't want ...
Fix setting of QT_API environment variable
Fix setting of QT_API environment variable
Python
bsd-3-clause
jwiggins/scikit-image,blink1073/scikit-image,Hiyorimi/scikit-image,pratapvardhan/scikit-image,paalge/scikit-image,rjeli/scikit-image,emon10005/scikit-image,robintw/scikit-image,newville/scikit-image,almarklein/scikit-image,almarklein/scikit-image,oew1v07/scikit-image,vighneshbirodkar/scikit-image,michaelaye/scikit-imag...
151dbe6d319b27882e4df42a73c4fe6c6b77b90a
rm/trials/templatetags/share.py
rm/trials/templatetags/share.py
""" Helpers for sharing """ from django.template import Library register = Library() def absolute(request): return request.build_absolute_uri(request.path) @register.inclusion_tag('share_this.html', takes_context=True) def share_this(context): "What, you can't copy a URL? Bah." return dict( title...
""" Helpers for sharing """ from django.template import Library register = Library() def absolute(request): return request.build_absolute_uri(request.path) @register.inclusion_tag('share_this.html', takes_context=True) def share_this(context): "What, you can't copy a URL? Bah." title = '' trial = con...
Move variable out of inline dict construction to debug production errors.
Move variable out of inline dict construction to debug production errors.
Python
agpl-3.0
openhealthcare/randomise.me,openhealthcare/randomise.me,openhealthcare/randomise.me,openhealthcare/randomise.me
0b6e9d6e329b8e88fca9635640ef0842f3cb82c2
api/tests/test_scrapers.py
api/tests/test_scrapers.py
def test_scrape_item_by_id(): from api.scrapers.item import scrape_item_by_id item = scrape_item_by_id('d19447e548d') assert item.id == 'd19447e548d' assert item.name == 'Thyrus Zenith' assert item.type == 'Two-handed Conjurer\'s Arm' assert item.ilvl == 90
def test_scrape_item_by_id(): from api.scrapers.item import scrape_item_by_id item = scrape_item_by_id('d19447e548d') assert item.id == 'd19447e548d' assert item.name == 'Thyrus Zenith' assert item.type == 'Two-handed Conjurer\'s Arm' assert item.ilvl == 90 def test_scrape_character_by_id():...
Add scrape character unit test
Add scrape character unit test
Python
mit
Demotivated/loadstone
27723696885319aabea974f83189d3a43770b7d5
spillway/fields.py
spillway/fields.py
"""Serializer fields""" from django.contrib.gis import forms from rest_framework.fields import WritableField from spillway.compat import json class GeometryField(WritableField): type_name = 'GeometryField' type_label = 'geometry' form_field_class = forms.GeometryField def to_native(self, value): ...
"""Serializer fields""" from django.contrib.gis import forms from rest_framework.fields import FileField, WritableField from greenwich.raster import Raster from spillway.compat import json class GeometryField(WritableField): type_name = 'GeometryField' type_label = 'geometry' form_field_class = forms.Geo...
Add numpy array serializer field
Add numpy array serializer field
Python
bsd-3-clause
bkg/django-spillway,barseghyanartur/django-spillway,kuzmich/django-spillway
f3ef685d4bb900733741f53e1afcefd143b26289
npcs.py
npcs.py
import random from characters import BaseCharacer class Mentor(BaseCharacer): MENTORS_COUNT = 4 def __init__(self, location, *groups): super(Mentor, self).__init__(location, *groups) def change_place(self, new_x, new_y): self.rect.left = new_x self.rect.top = new_y def chan...
import random from characters import BaseCharacer class Mentor(BaseCharacer): MENTORS_COUNT = 4 def __init__(self, location, *groups): super(Mentor, self).__init__(location, *groups) def change_place(self, new_x, new_y): self.rect.left = new_x self.rect.top = new_y def chan...
Add visit method to Mentor
Add visit method to Mentor
Python
mit
arturbalabanov/hacksym
5933f9ef0ff7af0fd85a7dbe6578eefe9b8f7cdf
seqcluster/create_report.py
seqcluster/create_report.py
import os import shutil import logging from bcbio import install install._set_matplotlib_default_backend() import matplotlib matplotlib.use('Agg', force=True) from libs.read import load_data from libs.report import make_profile from libs.utils import safe_dirs from db import make_database import templates logger = l...
import os import shutil import logging from bcbio import install install._set_matplotlib_default_backend() import matplotlib matplotlib.use('Agg', force=True) from libs.read import load_data from libs.report import make_profile from libs.utils import safe_dirs from db import make_database import templates logger = l...
Add message with link to seqclusterViz
Add message with link to seqclusterViz
Python
mit
lpantano/seqcluster,lpantano/seqcluster,lpantano/seqcluster,lpantano/seqcluster,lpantano/seqcluster
64219411d0bcbb7dafc754bef8538fc237584031
go/vumitools/tests/test_api_worker.py
go/vumitools/tests/test_api_worker.py
# -*- coding: utf-8 -*- """Tests for go.vumitools.api_worker.""" from twisted.internet.defer import inlineCallbacks from vumi.application.tests.test_base import ApplicationTestCase from go.vumitools.api_worker import VumiApiWorker from go.vumitools.api import VumiApiCommand class TestVumiApiWorker(ApplicationTest...
# -*- coding: utf-8 -*- """Tests for go.vumitools.api_worker.""" from twisted.internet.defer import inlineCallbacks from vumi.application.tests.test_base import ApplicationTestCase from go.vumitools.api_worker import VumiApiWorker from go.vumitools.api import VumiApiCommand class TestVumiApiWorker(ApplicationTest...
Remove send_to config from tests since Vumi's application test class now adds this automatically.
Remove send_to config from tests since Vumi's application test class now adds this automatically.
Python
bsd-3-clause
praekelt/vumi-go,praekelt/vumi-go,praekelt/vumi-go,praekelt/vumi-go
a38ee91cbb45cba35c930aae780a469c0cbc762c
mrbelvedereci/build/tasks.py
mrbelvedereci/build/tasks.py
from celery import shared_task from mrbelvedereci.build.models import Build from mrbelvedereci.salesforce.models import Org @shared_task def run_build(build_id): build = Build.objects.get(id=build_id) build.run() return build.status @shared_task def check_queued_build(build_id): build = Build.objects....
from celery import shared_task from mrbelvedereci.build.models import Build from mrbelvedereci.salesforce.models import Org @shared_task def run_build(build_id): build = Build.objects.get(id=build_id) build.run() return build.status @shared_task def check_queued_build(build_id): build = Build.objects....
Fix path to org field
Fix path to org field
Python
bsd-3-clause
SalesforceFoundation/mrbelvedereci,SalesforceFoundation/mrbelvedereci,SalesforceFoundation/mrbelvedereci,SalesforceFoundation/mrbelvedereci