commit
stringlengths
40
40
old_file
stringlengths
4
150
new_file
stringlengths
4
150
old_contents
stringlengths
0
3.26k
new_contents
stringlengths
1
4.43k
subject
stringlengths
15
501
message
stringlengths
15
4.06k
lang
stringclasses
4 values
license
stringclasses
13 values
repos
stringlengths
5
91.5k
diff
stringlengths
0
4.35k
164215cfde181626e458903b10b1d2ff961f4101
d1_mn_generic/src/gmn/app/migrations/0004_auto_20170523_0137.py
d1_mn_generic/src/gmn/app/migrations/0004_auto_20170523_0137.py
# -*- coding: utf-8 -*- # Generated by Django 1.11.1 on 2017-05-23 01:37 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('app', '0003_mediatype_mediatypeproperty'), ] opera...
Add Django db migration for new SID implementation
Add Django db migration for new SID implementation
Python
apache-2.0
DataONEorg/d1_python,DataONEorg/d1_python,DataONEorg/d1_python,DataONEorg/d1_python
--- +++ @@ -0,0 +1,43 @@ +# -*- coding: utf-8 -*- +# Generated by Django 1.11.1 on 2017-05-23 01:37 +from __future__ import unicode_literals + +from django.db import migrations, models +import django.db.models.deletion + + +class Migration(migrations.Migration): + + dependencies = [ + ('app', '0003_mediatyp...
f0d044b4e46c6aa25530057c772167389e485f04
BanHammer/blacklist/management/commands/update_third_party_rules.py
BanHammer/blacklist/management/commands/update_third_party_rules.py
from django.core.management.base import BaseCommand, CommandError import urllib2 import re STORE_FOLDER = '/usr/local/third_party_ips' ET_COMPROMISED_IPS_URL = 'https://rules.emergingthreatspro.com/blockrules/compromised-ips.txt' ET_COMPROMISED_IPS_REV = 'https://rules.emergingthreatspro.com/blockrules/COMPrev' ET_...
Update third party rules script
Update third party rules script
Python
bsd-3-clause
mozilla/BanHammer,mozilla/BanHammer,mozilla/BanHammer,mozilla/BanHammer
--- +++ @@ -0,0 +1,50 @@ +from django.core.management.base import BaseCommand, CommandError + +import urllib2 +import re + +STORE_FOLDER = '/usr/local/third_party_ips' + +ET_COMPROMISED_IPS_URL = 'https://rules.emergingthreatspro.com/blockrules/compromised-ips.txt' +ET_COMPROMISED_IPS_REV = 'https://rules.emergingth...
eceb4ff9f9c8cee19ebade50f7c88766a1fd7e14
windberg_results/cms_app.py
windberg_results/cms_app.py
from cms.app_base import CMSApp from django.utils.translation import ugettext_lazy as _ from cms.apphook_pool import apphook_pool class WindbergResultApp(CMSApp): name = _('Result App') urls = ['windberg_results.urls'] apphook_pool.register(WindbergResultApp)
Add the cms app for results
Add the cms app for results
Python
bsd-3-clause
janLo/Windberg-web,janLo/Windberg-web
--- +++ @@ -0,0 +1,11 @@ +from cms.app_base import CMSApp +from django.utils.translation import ugettext_lazy as _ +from cms.apphook_pool import apphook_pool + + +class WindbergResultApp(CMSApp): + name = _('Result App') + urls = ['windberg_results.urls'] + + +apphook_pool.register(WindbergResultApp)
4208c6e963ae59380999fae45930656c287a627d
nettests/core/dnsspoof.py
nettests/core/dnsspoof.py
from twisted.internet import defer from twisted.python import usage from scapy.all import IP, UDP, DNS, DNSQR from ooni.templates import scapyt from ooni.utils import log class UsageOptions(usage.Options): optParameters = [['resolver', 'r', None, 'Specify the resolver that should be used for ...
Implement test that detects DNS spoofing * To be run with a known good resolver and the default resolver of the country being tested, from inside the country with a hostname of a site that is known to be censored.
Implement test that detects DNS spoofing * To be run with a known good resolver and the default resolver of the country being tested, from inside the country with a hostname of a site that is known to be censored.
Python
bsd-2-clause
0xPoly/ooni-probe,0xPoly/ooni-probe,Karthikeyan-kkk/ooni-probe,Karthikeyan-kkk/ooni-probe,kdmurray91/ooni-probe,juga0/ooni-probe,juga0/ooni-probe,Karthikeyan-kkk/ooni-probe,lordappsec/ooni-probe,lordappsec/ooni-probe,0xPoly/ooni-probe,kdmurray91/ooni-probe,Karthikeyan-kkk/ooni-probe,lordappsec/ooni-probe,juga0/ooni-pro...
--- +++ @@ -0,0 +1,64 @@ +from twisted.internet import defer +from twisted.python import usage + +from scapy.all import IP, UDP, DNS, DNSQR + +from ooni.templates import scapyt +from ooni.utils import log + +class UsageOptions(usage.Options): + optParameters = [['resolver', 'r', None, + 'Specify...
2e245b0a28856b86aa8c73e8b2571dd9ffd7f035
benchmarks/bench_numpy_vjps.py
benchmarks/bench_numpy_vjps.py
from autograd import make_vjp import autograd.numpy as np import autograd.numpy.random as npr dot_0 = lambda A, B, g: make_vjp(np.dot)(A, B)[0](g) dot_1 = lambda A, B, g: make_vjp(np.dot, argnum=1)(A, B)[0](g) dot_0_0 = lambda A, B, g: make_vjp(dot_0)(A, B, g)[0](A) dot_0_1 = lambda A, B, g: make_vjp(dot_0)(A, B, g)...
Add benchmarks demonstrating dot grads performance
Add benchmarks demonstrating dot grads performance
Python
mit
HIPS/autograd,hips/autograd,hips/autograd,HIPS/autograd
--- +++ @@ -0,0 +1,43 @@ +from autograd import make_vjp + +import autograd.numpy as np +import autograd.numpy.random as npr + +dot_0 = lambda A, B, g: make_vjp(np.dot)(A, B)[0](g) +dot_1 = lambda A, B, g: make_vjp(np.dot, argnum=1)(A, B)[0](g) + +dot_0_0 = lambda A, B, g: make_vjp(dot_0)(A, B, g)[0](A) +dot_0_1 = lam...
9e7a42d91b6056494edf14dd5d5089b8b3a123ba
tools/apikeys.py
tools/apikeys.py
import argparse, shelve if __name__ == "__main__": # Parse the command line arguments parser = argparse.ArgumentParser(description="API key tool for PyHeufyBot.") parser.add_argument("-s", "--storage", help="The storage file to use", type=str, default="../heufybot.db") parser.add_argument("-k", "--key...
Add a tool to manage API keys
Add a tool to manage API keys
Python
mit
Heufneutje/PyHeufyBot,Heufneutje/PyHeufyBot
--- +++ @@ -0,0 +1,19 @@ +import argparse, shelve + + +if __name__ == "__main__": + # Parse the command line arguments + parser = argparse.ArgumentParser(description="API key tool for PyHeufyBot.") + parser.add_argument("-s", "--storage", help="The storage file to use", type=str, default="../heufybot.db") + ...
999f45ddb80899805293696dd2ff4627a63f73dd
functest/tests/unit/features/test_doctor.py
functest/tests/unit/features/test_doctor.py
#!/usr/bin/env python # Copyright (c) 2017 Orange and others. # # All rights reserved. This program and the accompanying materials # are made available under the terms of the Apache License, Version 2.0 # which accompanies this distribution, and is available at # http://www.apache.org/licenses/LICENSE-2.0 # pylint: d...
Add unit tests for doctor
Add unit tests for doctor Change-Id: Iba3c63592623623507e009b0b9f514792c82d25e Signed-off-by: Cédric Ollivier <d48310251a4a484d041bc5d09a9ac4d86d20f793@orange.com>
Python
apache-2.0
mywulin/functest,opnfv/functest,mywulin/functest,opnfv/functest
--- +++ @@ -0,0 +1,38 @@ +#!/usr/bin/env python + +# Copyright (c) 2017 Orange and others. +# +# All rights reserved. This program and the accompanying materials +# are made available under the terms of the Apache License, Version 2.0 +# which accompanies this distribution, and is available at +# http://www.apache.or...
1389c97b0e78e72496b62dc17a97baba7c12115a
knocky_code/knocky_config.py
knocky_code/knocky_config.py
#encoding: utf-8 # # (C) 2016 José Millán Soto <jmillan@kde-espana.org> # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unle...
Add module for handling configuration files
Add module for handling configuration files This module will store and load the configuration files (for now just a dictionary which contains the users as keys and the password as values), using pickle module.
Python
apache-2.0
gpul-labs/knocky
--- +++ @@ -0,0 +1,28 @@ +#encoding: utf-8 +# +# (C) 2016 José Millán Soto <jmillan@kde-espana.org> +# +# 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...
417196332246474b306e81c8d7d2f3a7a5065eb5
senic_hub/backend/subprocess_run.py
senic_hub/backend/subprocess_run.py
"""Provides `subprocess.run()` from Python 3.5+ if available. Otherwise falls back to `subprocess.check_output()`.""" try: from subprocess import run except ImportError: from collections import namedtuple from subprocess import check_output def run(args, *, stdin=None, input=None, stdout=None, stderr=...
"""Provides `subprocess.run()` from Python 3.5+ if available. Otherwise falls back to `subprocess.check_output()`.""" try: from subprocess import run except ImportError: from collections import namedtuple from subprocess import check_output, CalledProcessError def run(args, *, stdin=None, input=None, ...
Fix throwing error although check arg is false
Fix throwing error although check arg is false
Python
mit
grunskis/senic-hub,grunskis/nuimo-hub-backend,grunskis/senic-hub,grunskis/senic-hub,grunskis/senic-hub,grunskis/senic-hub,grunskis/nuimo-hub-backend,getsenic/senic-hub,grunskis/nuimo-hub-backend,grunskis/nuimo-hub-backend,grunskis/senic-hub,getsenic/senic-hub,grunskis/nuimo-hub-backend
--- +++ @@ -4,10 +4,16 @@ from subprocess import run except ImportError: from collections import namedtuple - from subprocess import check_output + from subprocess import check_output, CalledProcessError def run(args, *, stdin=None, input=None, stdout=None, stderr=None, shell=False, timeout=No...
6d6b942056eccf3e0c69e810e9a2d66cd70d240c
books/services.py
books/services.py
from datetime import date from datetime import timedelta from django.utils import timezone from books.models import Transaction def get_months_transactions(): today = timezone.now() first_day_of_a_month = date(today.year, today.month, 1) qs = Transaction.objects.filter(created__gte=first_day_of_a_month)...
Add helper functions for domain logic
Add helper functions for domain logic
Python
mit
trimailov/finance,trimailov/finance,trimailov/finance
--- +++ @@ -0,0 +1,28 @@ +from datetime import date +from datetime import timedelta + +from django.utils import timezone + +from books.models import Transaction + + +def get_months_transactions(): + today = timezone.now() + first_day_of_a_month = date(today.year, today.month, 1) + qs = Transaction.objects.fi...
c00e8e416429487fb225ba4e5506b16ea2aa9927
dakota-hydrotrend-uq-study.py
dakota-hydrotrend-uq-study.py
"""A Dakotathon uncertainty quantification experiment with Hydrotrend. This experiment requires a WMT executor with PyMT installed. It also requires Dakotathon and Hydrotrend installed as CSDMS components. """ import os import numpy as np from pymt.components import PolynomialChaos, Hydrotrend from dakotathon.utils i...
Add script for UQ experiment
Add script for UQ experiment
Python
mit
mdpiper/AGU-2016
--- +++ @@ -0,0 +1,45 @@ +"""A Dakotathon uncertainty quantification experiment with Hydrotrend. + +This experiment requires a WMT executor with PyMT installed. It also +requires Dakotathon and Hydrotrend installed as CSDMS components. + +""" +import os +import numpy as np +from pymt.components import PolynomialChaos...
0499189fb3906d3f9e5892ade07a136b0cc3a97e
comics/crawlers/deepfried.py
comics/crawlers/deepfried.py
from comics.crawler.base import BaseComicCrawler from comics.crawler.meta import BaseComicMeta class ComicMeta(BaseComicMeta): name = 'Deep Fried' language = 'en' url = 'http://www.whatisdeepfried.com/' start_date = '2001-09-16' history_capable_days = 14 schedule = 'Mo,Tu,We,Th,Fr,Sa' time_...
Add crawler for 'Deep Fried'
Add crawler for 'Deep Fried'
Python
agpl-3.0
jodal/comics,datagutten/comics,datagutten/comics,datagutten/comics,jodal/comics,jodal/comics,klette/comics,klette/comics,datagutten/comics,jodal/comics,klette/comics
--- +++ @@ -0,0 +1,25 @@ +from comics.crawler.base import BaseComicCrawler +from comics.crawler.meta import BaseComicMeta + +class ComicMeta(BaseComicMeta): + name = 'Deep Fried' + language = 'en' + url = 'http://www.whatisdeepfried.com/' + start_date = '2001-09-16' + history_capable_days = 14 + sch...
4a8d8e8e13d0ca685608532159868fc453df12ca
login/migrations/0017_auto_20181119_1631.py
login/migrations/0017_auto_20181119_1631.py
# -*- coding: utf-8 -*- # Generated by Django 1.11 on 2018-11-19 15:31 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('login', '0016_auto_20181018_1401'), ] operations = [ migrations.AlterField( ...
Migrate default for is_native to database
Migrate default for is_native to database
Python
agpl-3.0
openego/oeplatform,openego/oeplatform,openego/oeplatform,openego/oeplatform
--- +++ @@ -0,0 +1,20 @@ +# -*- coding: utf-8 -*- +# Generated by Django 1.11 on 2018-11-19 15:31 +from __future__ import unicode_literals + +from django.db import migrations, models + + +class Migration(migrations.Migration): + + dependencies = [ + ('login', '0016_auto_20181018_1401'), + ] + + operat...
ecf09e199a1dc03eaa7ad58f77865fd4d2de5ba3
tests/test_io.py
tests/test_io.py
""" Tests for the BSE IO functions """ # Most functionality is covered under other tests. # This tests the remainder import bse import os import pytest _data_dir = bse.default_data_dir @pytest.mark.parametrize('file_path', [ 'CC-PVDZ.0.table.json', 'CRENBL...
Test writing of json files
Test writing of json files
Python
bsd-3-clause
MOLSSI-BSE/basis_set_exchange
--- +++ @@ -0,0 +1,43 @@ +""" +Tests for the BSE IO functions +""" + +# Most functionality is covered under other tests. +# This tests the remainder + +import bse +import os +import pytest + +_data_dir = bse.default_data_dir + +@pytest.mark.parametrize('file_path', [ + 'CC-PVDZ.0.table.js...
200a9008512ba644e2ae773745d3c8896f390eee
dataactcore/migrations/versions/a7249e2d8a1a_wipe_tas_lookups.py
dataactcore/migrations/versions/a7249e2d8a1a_wipe_tas_lookups.py
"""Wipe TAS lookups: one-off data migration to delete existing TASLookups Revision ID: a7249e2d8a1a Revises: 0c857b50962a Create Date: 2016-10-18 19:58:19.837713 """ from alembic import op # revision identifiers, used by Alembic. revision = 'a7249e2d8a1a' down_revision = '0c857b50962a' branch_labels = None depends_o...
Add data migration for removing TAS entries
Add data migration for removing TAS entries We won't be clearing the whole TAS table when importing in a later commit, so drop all the data one last time.
Python
cc0-1.0
chambers-brian/SIG_Digital-Strategy_SI_ODP_Backend,fedspendingtransparency/data-act-broker-backend,fedspendingtransparency/data-act-broker-backend,chambers-brian/SIG_Digital-Strategy_SI_ODP_Backend
--- +++ @@ -0,0 +1,30 @@ +"""Wipe TAS lookups: one-off data migration to delete existing TASLookups + +Revision ID: a7249e2d8a1a +Revises: 0c857b50962a +Create Date: 2016-10-18 19:58:19.837713 + +""" +from alembic import op + +# revision identifiers, used by Alembic. +revision = 'a7249e2d8a1a' +down_revision = '0c857...
b7d3d0289c605c6174a7605fcc700945a48cab23
lino_extjs6/extjs6/models.py
lino_extjs6/extjs6/models.py
# -*- coding: UTF-8 -*- # Copyright 2015-2016 Luc Saffre # License: BSD (see file COPYING for details) """Database models for :mod:`extjs6`. """ from __future__ import unicode_literals import logging logger = logging.getLogger(__name__) from django.utils.translation import ugettext_lazy as _ from lino.api import ...
Add the prefered_theme field for User model
Add the prefered_theme field for User model
Python
agpl-3.0
lsaffre/lino_extjs6,lsaffre/lino_extjs6,lsaffre/lino_extjs6,lsaffre/lino_extjs6,lino-framework/extjs6,lsaffre/lino_extjs6,lino-framework/extjs6,lino-framework/extjs6
--- +++ @@ -0,0 +1,48 @@ +# -*- coding: UTF-8 -*- +# Copyright 2015-2016 Luc Saffre +# License: BSD (see file COPYING for details) +"""Database models for :mod:`extjs6`. + +""" + +from __future__ import unicode_literals + +import logging + +logger = logging.getLogger(__name__) + +from django.utils.translation import ...
bb6efe4170a9ddb144d09212ab5bf06b0d043f3d
judge/views/user.py
judge/views/user.py
from django.contrib.auth.decorators import login_required from django.core.exceptions import ObjectDoesNotExist from django.http import Http404, HttpResponseRedirect from django.shortcuts import render_to_response from django.template import RequestContext from judge.forms import ProfileForm from judge.models import Pr...
from django.contrib.auth.decorators import login_required from django.core.exceptions import ObjectDoesNotExist from django.http import Http404, HttpResponseRedirect from django.shortcuts import render_to_response from django.template import RequestContext from judge.forms import ProfileForm from judge.models import Pr...
Use long display name on profile
Use long display name on profile
Python
agpl-3.0
DMOJ/site,Minkov/site,Phoenix1369/site,Minkov/site,monouno/site,DMOJ/site,monouno/site,DMOJ/site,DMOJ/site,Minkov/site,monouno/site,Phoenix1369/site,Minkov/site,Phoenix1369/site,Phoenix1369/site,monouno/site,monouno/site
--- +++ @@ -10,7 +10,7 @@ def user(request, user): try: user = Profile.objects.get(user__username=user) - return render_to_response('user.html', {'user': user, 'title': 'User %s' % user.display_name()}, + return render_to_response('user.html', {'user': user, 'title': 'User %s' % user.long...
23962420a7bbdcdeaec500f94b4c5f19a16f63dc
patch_analyzer/patch_utils.py
patch_analyzer/patch_utils.py
from subprocess import Popen, PIPE def is_class(file): return file.endswith(".class") and not file.startswith("META-INF") def modified_paths(patch): p = Popen(["jar", "-tf", patch], stdout=PIPE) output, _ = p.communicate() return filter(is_class, [file.decode() for file in output.split(b"\n")]) def ...
Patch utils to get content from patch jars
Patch utils to get content from patch jars
Python
mit
alepulver/changesets
--- +++ @@ -0,0 +1,20 @@ +from subprocess import Popen, PIPE + +def is_class(file): + return file.endswith(".class") and not file.startswith("META-INF") + +def modified_paths(patch): + p = Popen(["jar", "-tf", patch], stdout=PIPE) + output, _ = p.communicate() + return filter(is_class, [file.decode() for ...
596692a033b7b9e76d7de176564abc640b647d95
confluent/auth.py
confluent/auth.py
# authentication and authorization routines for confluent import confluent.config as config def authorize(name, element): #TODO: actually use the element to ascertain if this user is good enough try: if '/' in name: tenant, user = name.split('/', 1) tenant = config.get_tenant_i...
Put missing file under git tracking
Put missing file under git tracking
Python
apache-2.0
jufm/confluent,jjohnson42/confluent,chenglch/confluent,xcat2/confluent,chenglch/confluent,michaelfardu/thinkconfluent,michaelfardu/thinkconfluent,whowutwut/confluent,michaelfardu/thinkconfluent,jjohnson42/confluent,xcat2/confluent,whowutwut/confluent,jufm/confluent,xcat2/confluent,michaelfardu/thinkconfluent,chenglch/c...
--- +++ @@ -0,0 +1,24 @@ +# authentication and authorization routines for confluent + +import confluent.config as config + +def authorize(name, element): + #TODO: actually use the element to ascertain if this user is good enough + try: + if '/' in name: + tenant, user = name.split('/', 1) + ...
edb8caff755853443cfd94cba6ef2e949ae47900
knights/django.py
knights/django.py
from django.template import TemplateDoesNotExist, TemplateSyntaxError 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(BaseEngine): def __init__(self, params): ...
Add Django 1.8 engine wrapper
Add Django 1.8 engine wrapper
Python
mit
funkybob/knights-templater,funkybob/knights-templater
--- +++ @@ -0,0 +1,42 @@ +from django.template import TemplateDoesNotExist, TemplateSyntaxError +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(BaseEngine): + + ...
88fc0bca84ea1a66e941b094c7a21ece8b97c616
python/gegl/pygobject_introspection/test.py
python/gegl/pygobject_introspection/test.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Copyright (c) 2015 Jérémie DECOCK (http://www.jdhp.org) """ A simple GEGL snippet with the Gobject automatic introspection method. This inverts the colors of a PNG file. BUG: GEGL has been built without introspection on Debian 8. See https://github.com/jsbueno/p...
Add a snippet (Python GEGL).
Add a snippet (Python GEGL).
Python
mit
jeremiedecock/snippets,jeremiedecock/snippets,jeremiedecock/snippets,jeremiedecock/snippets,jeremiedecock/snippets,jeremiedecock/snippets,jeremiedecock/snippets,jeremiedecock/snippets,jeremiedecock/snippets,jeremiedecock/snippets,jeremiedecock/snippets,jeremiedecock/snippets,jeremiedecock/snippets
--- +++ @@ -0,0 +1,78 @@ +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- + +# Copyright (c) 2015 Jérémie DECOCK (http://www.jdhp.org) + +""" +A simple GEGL snippet with the Gobject automatic introspection method. + +This inverts the colors of a PNG file. + +BUG: GEGL has been built without introspection on Debian 8....
c8b47062c76ebe77b8cf441107f97f3c2ec3f0ac
django/hello/world/models.py
django/hello/world/models.py
from django.db import models # Create your models here. class World(models.Model): randomnumber = models.IntegerField() class Meta: db_table = 'world' class Fortune(models.Model): message = models.CharField(max_length=65535) class Meta: db_table = 'fortune'
from django.db import models # Create your models here. class World(models.Model): randomnumber = models.IntegerField() class Meta: db_table = 'World' class Fortune(models.Model): message = models.CharField(max_length=65535) class Meta: db_table = 'Fortune'
Fix table name for MySQL
Fix table name for MySQL
Python
bsd-3-clause
greg-hellings/FrameworkBenchmarks,Dith3r/FrameworkBenchmarks,sxend/FrameworkBenchmarks,methane/FrameworkBenchmarks,zane-techempower/FrameworkBenchmarks,valyala/FrameworkBenchmarks,actframework/FrameworkBenchmarks,zane-techempower/FrameworkBenchmarks,leafo/FrameworkBenchmarks,kellabyte/FrameworkBenchmarks,s-ludwig/Frame...
--- +++ @@ -5,9 +5,9 @@ class World(models.Model): randomnumber = models.IntegerField() class Meta: - db_table = 'world' + db_table = 'World' class Fortune(models.Model): message = models.CharField(max_length=65535) class Meta: - db_table = 'fortune' + db_table = 'Fortune'
0802859bd579fd93c3d29e33ea84e3796f685163
set_building.py
set_building.py
import sys import json import time from sklearn.cluster import KMeans num_words = int(sys.argv[1]) num_clusters = int(sys.argv[2]) f = open("google-10000-vectors.json","r").read().split("\n") word_list = [] vector_list = [] for i in range(0,num_words): j = json.loads(f[i]) word_list.append(j[0]) vector_list.append...
Set Building Implemented * word2vec vectors generated from vocabulary file * KMeans clustering employed for grouping semantically similar vectors * storing as seperate files with group of similar sets
Set Building Implemented * word2vec vectors generated from vocabulary file * KMeans clustering employed for grouping semantically similar vectors * storing as seperate files with group of similar sets
Python
mit
iisc-sa-open/trsl,Jaiswal-ruhil/trsl,iisc-sa-open/trsl
--- +++ @@ -0,0 +1,29 @@ +import sys +import json +import time +from sklearn.cluster import KMeans + +num_words = int(sys.argv[1]) +num_clusters = int(sys.argv[2]) +f = open("google-10000-vectors.json","r").read().split("\n") +word_list = [] +vector_list = [] +for i in range(0,num_words): + j = json.loads(f[i]) + wo...
87f4c67f937ce23c01e41427f038152f38db82dc
python/utils/serial_debug.py
python/utils/serial_debug.py
#!/usr/bin/env python # coding=utf8 # http://stackoverflow.com/a/15095449/706819 import os import pty def print_serial(): master, slave = pty.openpty() tty_name = os.ttyname(slave) print("Write serial data to {}\nCtrl-C to exit\n\n".format(tty_name)) while True: print(os.read(master, 1024)) if __name__ == '...
Add debug util to listen on a tty and print input
Add debug util to listen on a tty and print input Makes it much easier to debug the arduino_serial stuff.
Python
bsd-3-clause
aranchelk/headmouse
--- +++ @@ -0,0 +1,19 @@ +#!/usr/bin/env python +# coding=utf8 + +# http://stackoverflow.com/a/15095449/706819 + +import os +import pty + +def print_serial(): + master, slave = pty.openpty() + tty_name = os.ttyname(slave) + + print("Write serial data to {}\nCtrl-C to exit\n\n".format(tty_name)) + + while True: + pri...
f4425bc8d63c725329ea04898c86275928f0f4be
scripts/learning_curve.py
scripts/learning_curve.py
#!/usr/bin/env python import argparse import pandas as pd import matplotlib.pyplot as plt def learning_curve(csv_file): df = pd.read_csv(csv_file) df_train = df.query("type == 'train'") df_val = df.query("type == 'val'") plt.figure() # train loss plt.subplot(221) plt.semilogy(df_train...
Add script to draw learning curve
Add script to draw learning curve
Python
mit
wkentaro/fcn
--- +++ @@ -0,0 +1,59 @@ +#!/usr/bin/env python + +import argparse + +import pandas as pd +import matplotlib.pyplot as plt + + +def learning_curve(csv_file): + df = pd.read_csv(csv_file) + df_train = df.query("type == 'train'") + df_val = df.query("type == 'val'") + + plt.figure() + + # train loss + ...
b5a108873ed9537b205be75eee58d7f6984a8a18
myuw_api/quarter.py
myuw_api/quarter.py
from django.conf import settings from django.core.exceptions import ObjectDoesNotExist from datetime import datetime from models import Term from restclients.sws_client import SWSClient import logging import urllib import re import json # quarter class definition class Quarter: __logger = logging.getLogger('quart...
Create the class that maintain the term cache.
Create the class that maintain the term cache.
Python
apache-2.0
uw-it-aca/myuw,uw-it-aca/myuw,fanglinfang/myuw,fanglinfang/myuw,uw-it-aca/myuw,uw-it-aca/myuw,fanglinfang/myuw
--- +++ @@ -0,0 +1,77 @@ +from django.conf import settings +from django.core.exceptions import ObjectDoesNotExist +from datetime import datetime +from models import Term +from restclients.sws_client import SWSClient +import logging +import urllib +import re +import json + +# quarter class definition + +class Quarter:...
713b05e49b814a2a924f657294352bc5e7061638
tools/chrome_proxy/integration_tests/chrome_proxy_pagesets/reenable_after_bypass.py
tools/chrome_proxy/integration_tests/chrome_proxy_pagesets/reenable_after_bypass.py
# Copyright 2014 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. from telemetry.page import page as page_module from telemetry import story class ReenableAfterBypassPage(page_module.Page): """A test page for the re-ena...
# Copyright 2014 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. from telemetry.page import page as page_module from telemetry import story class ReenableAfterBypassPage(page_module.Page): """A test page for the re-ena...
Add trailing slash to chrome_proxy telemetry test page URL.
Add trailing slash to chrome_proxy telemetry test page URL. BUG=507797 Review URL: https://codereview.chromium.org/1229563002 Cr-Commit-Position: 972c6d2dc6dd5efdad1377c0d224e03eb8f276f7@{#337895}
Python
bsd-3-clause
hgl888/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,Chilledheart/chromium,chuan9/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,Just-D/chromium-1,Chilledheart/chromium,Chilledheart/chromium,TheTypoMaster/chromium-crosswalk,axinging/chromium-crosswalk,Just-D/chromium-1,TheTypoMaster/chromium-crosswalk,axingi...
--- +++ @@ -35,7 +35,7 @@ # Test page for "Chrome-Proxy: block=0". Loading this page should cause all # data reduction proxies to be bypassed for one to five minutes. self.AddStory(ReenableAfterBypassPage( - url="http://check.googlezip.net/block", + url="http://check.googlezip.net/block/"...
8381e50b641c3c1e94dec18bcd14e5a1eff490cf
scripts/ensure_tilesize.py
scripts/ensure_tilesize.py
#!/usr/bin/python # # This is a helper script to ensure an image has the correct tile size. # It uses pgmagick[1] to read and (if needed) correct the image. To use # it on a number of files one could use e.g. the find command: # # find <data-folder> -name *.jpg -exec scripts/ensure_tilesize.py {} 256 \; # # [1] http:...
Add script to ensure the correct tile size of a file
Add script to ensure the correct tile size of a file By @tomka
Python
agpl-3.0
htem/CATMAID,htem/CATMAID,htem/CATMAID,fzadow/CATMAID,fzadow/CATMAID,htem/CATMAID,fzadow/CATMAID,fzadow/CATMAID
--- +++ @@ -0,0 +1,48 @@ +#!/usr/bin/python +# +# This is a helper script to ensure an image has the correct tile size. +# It uses pgmagick[1] to read and (if needed) correct the image. To use +# it on a number of files one could use e.g. the find command: +# +# find <data-folder> -name *.jpg -exec scripts/ensure_t...
bfe960a8aa35cd8b0c306882b008390990fce23f
pycroft/lib/user_deletion.py
pycroft/lib/user_deletion.py
from datetime import timedelta from sqlalchemy import func, nulls_last from sqlalchemy.engine import Row from sqlalchemy.future import select from sqlalchemy.sql.elements import and_, not_ from sqlalchemy.sql.functions import current_timestamp from pycroft import config, Config from pycroft.model.property import Curr...
Add first working `get_archivable_members` function
Add first working `get_archivable_members` function
Python
apache-2.0
agdsn/pycroft,agdsn/pycroft,agdsn/pycroft,agdsn/pycroft,agdsn/pycroft
--- +++ @@ -0,0 +1,63 @@ +from datetime import timedelta + +from sqlalchemy import func, nulls_last +from sqlalchemy.engine import Row +from sqlalchemy.future import select +from sqlalchemy.sql.elements import and_, not_ +from sqlalchemy.sql.functions import current_timestamp + +from pycroft import config, Config +fr...
446dd62862127839f2803612274c93484b5ed384
greenland_climate_change/linear_or_polynomial_fit_seasonal_change.py
greenland_climate_change/linear_or_polynomial_fit_seasonal_change.py
import numpy as np import pandas as pd from scipy import interpolate, poly1d import matplotlib.pyplot as plt def main(): df = pd.read_csv('greenland-mass-change.csv') all_xs = df['year'] all_ys = df['mass change'] train = df[df['year'] < 2012] test = df[df['year'] > 2012] train_xs = t...
Determine whether linear or polynomial fit is best for seasonal change
Determine whether linear or polynomial fit is best for seasonal change
Python
mit
noelevans/sandpit,noelevans/sandpit,noelevans/sandpit,noelevans/sandpit,noelevans/sandpit,noelevans/sandpit
--- +++ @@ -0,0 +1,53 @@ +import numpy as np +import pandas as pd +from scipy import interpolate, poly1d +import matplotlib.pyplot as plt + + +def main(): + df = pd.read_csv('greenland-mass-change.csv') + all_xs = df['year'] + all_ys = df['mass change'] + + train = df[df['year'] < 2012] + test ...
8664d781bbbed5753979ff299174efc1906eaaf0
taiga/users/migrations/0018_remove_vote_issues_in_roles_permissions_field.py
taiga/users/migrations/0018_remove_vote_issues_in_roles_permissions_field.py
# -*- coding: utf-8 -*- # Generated by Django 1.9.2 on 2016-04-04 09:32 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('users', '0017_auto_20160208_1751'), ] operations = [ migrations.RunSQL( ...
Clean user role permissions: remove vote_issues in Role.permissions
Clean user role permissions: remove vote_issues in Role.permissions
Python
agpl-3.0
taigaio/taiga-back,dayatz/taiga-back,taigaio/taiga-back,xdevelsistemas/taiga-back-community,dayatz/taiga-back,dayatz/taiga-back,xdevelsistemas/taiga-back-community,taigaio/taiga-back,xdevelsistemas/taiga-back-community
--- +++ @@ -0,0 +1,18 @@ +# -*- coding: utf-8 -*- +# Generated by Django 1.9.2 on 2016-04-04 09:32 +from __future__ import unicode_literals + +from django.db import migrations + + +class Migration(migrations.Migration): + + dependencies = [ + ('users', '0017_auto_20160208_1751'), + ] + + operations = ...
2291a18db52f8a6443805736a5477e2f81158ab5
web/form/base_form.py
web/form/base_form.py
from collections import OrderedDict from flask_wtf import Form class BaseForm(Form): def __iter__(self): field_order = getattr(self, '_order', []) if field_order: ordered_fields = OrderedDict() for name in field_order: ordered_fields[name] = self._fields....
Introduce a `BaseForm` to allow customization of field order
Introduce a `BaseForm` to allow customization of field order
Python
apache-2.0
lukasjuhrich/pycroft,lukasjuhrich/pycroft,agdsn/pycroft,agdsn/pycroft,lukasjuhrich/pycroft,agdsn/pycroft,lukasjuhrich/pycroft,agdsn/pycroft,agdsn/pycroft
--- +++ @@ -0,0 +1,20 @@ +from collections import OrderedDict + +from flask_wtf import Form + + +class BaseForm(Form): + def __iter__(self): + field_order = getattr(self, '_order', []) + + if field_order: + ordered_fields = OrderedDict() + + for name in field_order: + ...
0e013b6608f36dc1ba44904d3c94faee5150f5af
st2common/tests/unit/test_resource_registrar.py
st2common/tests/unit/test_resource_registrar.py
# Licensed to the StackStorm, Inc ('StackStorm') under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use th...
Add tests for pack and config schema registrar.
Add tests for pack and config schema registrar.
Python
apache-2.0
emedvedev/st2,pixelrebel/st2,Plexxi/st2,StackStorm/st2,lakshmi-kannan/st2,nzlosh/st2,Plexxi/st2,punalpatel/st2,emedvedev/st2,peak6/st2,StackStorm/st2,StackStorm/st2,tonybaloney/st2,tonybaloney/st2,Plexxi/st2,lakshmi-kannan/st2,nzlosh/st2,pixelrebel/st2,nzlosh/st2,nzlosh/st2,Plexxi/st2,punalpatel/st2,peak6/st2,pixelrebe...
--- +++ @@ -0,0 +1,60 @@ +# Licensed to the StackStorm, Inc ('StackStorm') under one or more +# contributor license agreements. See the NOTICE file distributed with +# this work for additional information regarding copyright ownership. +# The ASF licenses this file to You under the Apache License, Version 2.0 +# (th...
7350422a1364f996b7ac362e8457e2a5e04afc7c
sympy/interactive/tests/test_ipythonprinting.py
sympy/interactive/tests/test_ipythonprinting.py
"""Tests that the IPython printing module is properly loaded. """ from sympy.interactive.session import init_ipython_session from sympy.external import import_module ipython = import_module("IPython", min_module_version="0.11") # disable tests if ipython is not present if not ipython: disabled = True def test_i...
"""Tests that the IPython printing module is properly loaded. """ from sympy.interactive.session import init_ipython_session from sympy.external import import_module ipython = import_module("IPython", min_module_version="0.11") # disable tests if ipython is not present if not ipython: disabled = True def test_i...
Make ipythonprinting test more robust
Make ipythonprinting test more robust
Python
bsd-3-clause
Vishluck/sympy,Mitchkoens/sympy,Davidjohnwilson/sympy,pandeyadarsh/sympy,hrashk/sympy,Davidjohnwilson/sympy,sahmed95/sympy,yukoba/sympy,Sumith1896/sympy,jamesblunt/sympy,moble/sympy,chaffra/sympy,Mitchkoens/sympy,Shaswat27/sympy,saurabhjn76/sympy,abhiii5459/sympy,jerli/sympy,jaimahajan1997/sympy,ahhda/sympy,sunny94/tem...
--- +++ @@ -12,8 +12,8 @@ def test_ipythonprinting(): # Initialize and setup IPython session app = init_ipython_session() - app.run_cell("from IPython.core.interactiveshell import InteractiveShell") - app.run_cell("inst = InteractiveShell.instance()") + app.run_cell("ip = get_ipython()") + app....
50c4dd5b6b911b783a29ff7e8764c113ab474d9c
tools/coverage_parser.py
tools/coverage_parser.py
import os os.chdir('tests/cmdline') lines = file('coverage.out', 'r').readlines() files = {} for line in lines: filename, lineno = line.split("----------") if filename not in files: files[filename] = set() files[filename].add(int(lineno)) filenames = files.keys() filenames.sort() for filename in filen...
Add makefile build rule for building HTML files which show which lines are covered and which are not.
Add makefile build rule for building HTML files which show which lines are covered and which are not.
Python
bsd-2-clause
Ms2ger/dom.js,andreasgal/dom.js,modulexcite/dom.js,modulexcite/dom.js,modulexcite/dom.js
--- +++ @@ -0,0 +1,43 @@ + +import os + +os.chdir('tests/cmdline') + +lines = file('coverage.out', 'r').readlines() + + +files = {} + + +for line in lines: + filename, lineno = line.split("----------") + + if filename not in files: + files[filename] = set() + + files[filename].add(int(lineno)) + + +filenames = files...
97f915187ba84f6104a4cf9fd7b54a7198a02ee7
indra/ontology/bio/__main__.py
indra/ontology/bio/__main__.py
import os import sys import glob import shutil import logging from .ontology import BioOntology, CACHE_DIR logger = logging.getLogger('indra.ontology.bio') if __name__ == '__main__': import ipdb; ipdb.set_trace() if len(sys.argv) < 2: logger.info('Operation missing. Supported operations: ' ...
Add CLI to regenerate ontology
Add CLI to regenerate ontology
Python
bsd-2-clause
bgyori/indra,johnbachman/belpy,johnbachman/belpy,johnbachman/belpy,johnbachman/indra,sorgerlab/indra,sorgerlab/belpy,bgyori/indra,sorgerlab/belpy,sorgerlab/indra,bgyori/indra,johnbachman/indra,sorgerlab/belpy,sorgerlab/indra,johnbachman/indra
--- +++ @@ -0,0 +1,34 @@ +import os +import sys +import glob +import shutil +import logging +from .ontology import BioOntology, CACHE_DIR + +logger = logging.getLogger('indra.ontology.bio') + +if __name__ == '__main__': + import ipdb; ipdb.set_trace() + if len(sys.argv) < 2: + logger.info('Operation miss...
a30fb24754fad371178207180bb064fcc5d5ca9d
patterns/factory.py
patterns/factory.py
""" Factory Pattern Definition: pass Also Known As: pass Problem: pass Wrong Solution: pass Correct Solution: pass Sources: Title: Head First Design Patterns Author(s): Eric Freeman & Elisabeth Freeman Pages: 109-168 Title: Design Patterns Author(s): Erich Gamma, Richard H...
""" Factory Pattern Definition: This pattern defines an interface for creating an object, but lets subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses. Also Known As: Virtual Constructor Problem: pass Wrong Solution: pass Correct Solut...
Add some info to Factory pattern
Add some info to Factory pattern
Python
mit
jdavis/rust-design-patterns,ianlet/rust-design-patterns,beni55/rust-design-patterns,ianlet/rust-design-patterns,jdavis/rust-design-patterns,beni55/rust-design-patterns,ianlet/rust-design-patterns,beni55/rust-design-patterns,jdavis/rust-design-patterns,jdavis/rust-design-patterns
--- +++ @@ -2,10 +2,12 @@ Factory Pattern Definition: - pass + This pattern defines an interface for creating an object, but lets + subclasses decide which class to instantiate. Factory Method lets a class + defer instantiation to subclasses. Also Known As: - pass + Virtual Constructor Pro...
d4ccc7e5bff643eae3aa3a2211169014068053a6
models/bmi_demo/bmi_models.py
models/bmi_demo/bmi_models.py
import os import shutil from indra.sources import eidos from indra.assemblers.bmi_wrapper import BMIModel from indra.assemblers import PysbAssembler def text_to_stmts(text): fname = text.replace(' ', '_') + '.jsonld' if os.path.exists(fname): ep = eidos.process_json_ld_file(fname) else: ep...
Add demo example for BMI
Add demo example for BMI
Python
bsd-2-clause
sorgerlab/belpy,johnbachman/indra,pvtodorov/indra,sorgerlab/indra,johnbachman/indra,bgyori/indra,johnbachman/belpy,bgyori/indra,bgyori/indra,johnbachman/indra,pvtodorov/indra,sorgerlab/indra,johnbachman/belpy,sorgerlab/indra,sorgerlab/belpy,sorgerlab/belpy,johnbachman/belpy,pvtodorov/indra,pvtodorov/indra
--- +++ @@ -0,0 +1,41 @@ +import os +import shutil +from indra.sources import eidos +from indra.assemblers.bmi_wrapper import BMIModel +from indra.assemblers import PysbAssembler + + +def text_to_stmts(text): + fname = text.replace(' ', '_') + '.jsonld' + if os.path.exists(fname): + ep = eidos.process_js...
aec27cf5799299c0267da8819ed836a0327ad47c
kyoukai/blueprints/regexp.py
kyoukai/blueprints/regexp.py
""" Regular-expression based blueprint for Kyoukai. This produces regex-based routes when ``wrap_route`` is called, and is the default blueprint handler for the Kyoukai blueprint tree. """ import typing from kyoukai.blueprints.base import ABCBlueprint from kyoukai.routing.base import ABCRoute from kyoukai.routing.reg...
Add stub for a regular expression based blueprint.
Add stub for a regular expression based blueprint.
Python
mit
SunDwarf/Kyoukai
--- +++ @@ -0,0 +1,54 @@ +""" +Regular-expression based blueprint for Kyoukai. + +This produces regex-based routes when ``wrap_route`` is called, and is the default blueprint handler for the Kyoukai +blueprint tree. +""" +import typing + +from kyoukai.blueprints.base import ABCBlueprint +from kyoukai.routing.base imp...
30d71d6952a46f25d40af524c9583dac50459711
util/testCamTrakParam.py
util/testCamTrakParam.py
from SimpleCV import * import time cam = Camera() try: while True: t0 = time.time() img = cam.getImage() topCropH = 60 img = img.resize(w = 200) img = img.crop(0, topCropH, img.width, img.height - topCropH) ## img.show() ## time.sleep(.5) ...
Test file to try camera tracking parameters
Test file to try camera tracking parameters
Python
mit
DrGFreeman/RasPiBot202,DrGFreeman/RasPiBot202
--- +++ @@ -0,0 +1,47 @@ +from SimpleCV import * +import time + +cam = Camera() + +try: + while True: + + t0 = time.time() + + img = cam.getImage() + + topCropH = 60 + img = img.resize(w = 200) + img = img.crop(0, topCropH, img.width, img.height - topCropH) + + ## ...
87027c6f0e0afd9b37b4c076b42735bf8092e2ca
src/ggrc_basic_permissions/migrations/versions/20150805105543_99925466d6e_add_roles_order_column.py
src/ggrc_basic_permissions/migrations/versions/20150805105543_99925466d6e_add_roles_order_column.py
"""Add roles order column Revision ID: 99925466d6e Revises: 401fb7f0184b Create Date: 2015-08-05 10:55:43.992382 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '99925466d6e' down_revision = '401fb7f0184b' def upgrade(): op.add_column("roles", sa.Column("r...
Add role_order column to roles table
Add role_order column to roles table
Python
apache-2.0
AleksNeStu/ggrc-core,NejcZupec/ggrc-core,kr41/ggrc-core,kr41/ggrc-core,hyperNURb/ggrc-core,kr41/ggrc-core,hasanalom/ggrc-core,plamut/ggrc-core,j0gurt/ggrc-core,kr41/ggrc-core,andrei-karalionak/ggrc-core,hasanalom/ggrc-core,AleksNeStu/ggrc-core,selahssea/ggrc-core,jmakov/ggrc-core,selahssea/ggrc-core,jmakov/ggrc-core,ha...
--- +++ @@ -0,0 +1,27 @@ + +"""Add roles order column + +Revision ID: 99925466d6e +Revises: 401fb7f0184b +Create Date: 2015-08-05 10:55:43.992382 + +""" + +from alembic import op +import sqlalchemy as sa + +# revision identifiers, used by Alembic. +revision = '99925466d6e' +down_revision = '401fb7f0184b' + + +def upg...
6086aed8f4c4afa6d1c345649e9dcf33e593b4a9
crypto_enigma/tests/test_utils.py
crypto_enigma/tests/test_utils.py
#!/usr/bin/env python # encoding: utf8 from __future__ import (absolute_import, print_function, division, unicode_literals) ''' Simple test file for debugging and testing at the shell. To use simply python test.py or ./test.py or run 'test' in PyCharm. ''' from ..machine import * # Test utili...
Add tests of some utilities and internals
Add tests of some utilities and internals
Python
bsd-3-clause
orome/crypto-enigma-py
--- +++ @@ -0,0 +1,39 @@ +#!/usr/bin/env python +# encoding: utf8 +from __future__ import (absolute_import, print_function, division, unicode_literals) + +''' Simple test file for debugging and testing at the shell. To use simply + python test.py + or + ./test.py + or run 'test' in PyCharm. +''' +...
323d5e907ce51c01793f52aa054d3f7a57373b22
test_billy.py
test_billy.py
import unittest import billy class TestSunlightAPI(unittest.TestCase): def test_can_get_resp_200(self): resp = billy.getresponse() self.assertEqual(resp.status, 200)
Add initial test to check response status code
Add initial test to check response status code
Python
mit
mosegontar/billybot
--- +++ @@ -0,0 +1,9 @@ +import unittest + +import billy + +class TestSunlightAPI(unittest.TestCase): + + def test_can_get_resp_200(self): + resp = billy.getresponse() + self.assertEqual(resp.status, 200)
2ce4386082773652a6da41c5f776882a77ad96ca
tests/test_environment.py
tests/test_environment.py
# -*- coding: utf-8 -*- import pytest from cookiecutter.environment import StrictEnvironment from cookiecutter.exceptions import UnknownExtension def test_env_should_raise_for_unknown_extension(): context = { '_extensions': ['foobar'] } with pytest.raises(UnknownExtension) as err: Stric...
Implement a basic test for StrictEnvironment
Implement a basic test for StrictEnvironment
Python
bsd-3-clause
michaeljoseph/cookiecutter,terryjbates/cookiecutter,luzfcb/cookiecutter,dajose/cookiecutter,willingc/cookiecutter,stevepiercy/cookiecutter,willingc/cookiecutter,audreyr/cookiecutter,audreyr/cookiecutter,Springerle/cookiecutter,hackebrot/cookiecutter,luzfcb/cookiecutter,hackebrot/cookiecutter,pjbull/cookiecutter,Springe...
--- +++ @@ -0,0 +1,17 @@ +# -*- coding: utf-8 -*- + +import pytest + +from cookiecutter.environment import StrictEnvironment +from cookiecutter.exceptions import UnknownExtension + + +def test_env_should_raise_for_unknown_extension(): + context = { + '_extensions': ['foobar'] + } + + with pytest.raise...
33023294b9ef2592397a4bffee5d492caf81e55c
content/doc/misc/_wsgi-app.py
content/doc/misc/_wsgi-app.py
# -*- coding: utf-8 -*- # content/doc/misc/_wsgi-app.py # ============================================================================= # WSGI application template. # Usage: # $ uwsgi --http :8765 --wsgi-file _wsgi-app.py # $ curl localhost:8765 # ================================================================...
Add WSGI app template to play with uWSGI server.
Add WSGI app template to play with uWSGI server.
Python
mit
rgolubtsov/rgolubtsov.github.io,rgolubtsov/rgolubtsov.github.io,rgolubtsov/rgolubtsov.github.io,rgolubtsov/rgolubtsov.github.io,rgolubtsov/rgolubtsov.github.io,rgolubtsov/rgolubtsov.github.io,rgolubtsov/rgolubtsov.github.io,rgolubtsov/rgolubtsov.github.io
--- +++ @@ -0,0 +1,29 @@ +# -*- coding: utf-8 -*- +# content/doc/misc/_wsgi-app.py +# ============================================================================= +# WSGI application template. +# Usage: +# $ uwsgi --http :8765 --wsgi-file _wsgi-app.py +# $ curl localhost:8765 +# =============================...
007d715ade7706beb56a9e03fbf3b74f596f915e
c2cgeoportal/scaffolds/update/+package+/CONST_migration/versions/009_Add_queryLayers_column.py
c2cgeoportal/scaffolds/update/+package+/CONST_migration/versions/009_Add_queryLayers_column.py
from sqlalchemy import MetaData, Table, Column, types from c2cgeoportal import schema def upgrade(migrate_engine): meta = MetaData(bind=migrate_engine) layer = Table('layer', meta, schema=schema, autoload=True) Column('queryLayers', types.Unicode).create(layer) def downgrade(migrate_engine): meta =...
Add migration script for queryLayers column
Add migration script for queryLayers column
Python
bsd-2-clause
tsauerwein/c2cgeoportal,tsauerwein/c2cgeoportal,tsauerwein/c2cgeoportal,tsauerwein/c2cgeoportal
--- +++ @@ -0,0 +1,15 @@ +from sqlalchemy import MetaData, Table, Column, types + +from c2cgeoportal import schema + + +def upgrade(migrate_engine): + meta = MetaData(bind=migrate_engine) + layer = Table('layer', meta, schema=schema, autoload=True) + Column('queryLayers', types.Unicode).create(layer) + + +de...
c105d1caddade4b2061f45e3ba4db0be0f7edb9d
tests/SaveFile/TestSaveFile.py
tests/SaveFile/TestSaveFile.py
# Copyright (c) 2015 Ultimaker B.V. # Uranium is released under the terms of the AGPLv3 or higher. import unittest import os.path import tempfile from multiprocessing import Pool from UM.SaveFile import SaveFile write_count = 0 def write_dual(path): with SaveFile(path, "w") as f: f.write("test file") ...
Add a test for SaveFile
Add a test for SaveFile Contributes to CURA-511
Python
agpl-3.0
onitake/Uranium,onitake/Uranium
--- +++ @@ -0,0 +1,52 @@ +# Copyright (c) 2015 Ultimaker B.V. +# Uranium is released under the terms of the AGPLv3 or higher. + +import unittest +import os.path +import tempfile + +from multiprocessing import Pool + +from UM.SaveFile import SaveFile + +write_count = 0 + +def write_dual(path): + with SaveFile(path,...
63633a877289f8b6641db872f4918d437ecbdc22
split_to_files.py
split_to_files.py
#!/usr/bin/env python3 # -*- coding: UTF-8 -*- import argparse argparser = argparse.ArgumentParser(description="Split text file rows to separate files") argparser.add_argument("filename", help="Filename to split") args = argparser.parse_args() with open(args.filename, 'r') as input: for index, line in enumerate...
Add a file to split text files by rows
Add a file to split text files by rows
Python
mit
dhh17/categories_norms_genres,dhh17/categories_norms_genres,dhh17/categories_norms_genres
--- +++ @@ -0,0 +1,13 @@ +#!/usr/bin/env python3 +# -*- coding: UTF-8 -*- +import argparse + +argparser = argparse.ArgumentParser(description="Split text file rows to separate files") + +argparser.add_argument("filename", help="Filename to split") +args = argparser.parse_args() + +with open(args.filename, 'r') as in...
f232d704a0c3b659b994d519c492651033a79a32
examples/gstreamer/video_pipeline.py
examples/gstreamer/video_pipeline.py
#!/usr/bin/env python import pygst pygst.require("0.10") import gst import gtk class Pipeline(object): def __init__(self): self.pipeline = gst.Pipeline("pipe") self.webcam = gst.element_factory_make("v4l2src", "webcam") self.webcam.set_property("device", "/dev/video0") self.pipeli...
Add a video pipeline example.
Add a video pipeline example.
Python
mit
peplin/astral
--- +++ @@ -0,0 +1,28 @@ +#!/usr/bin/env python + +import pygst +pygst.require("0.10") +import gst +import gtk + + +class Pipeline(object): + def __init__(self): + self.pipeline = gst.Pipeline("pipe") + self.webcam = gst.element_factory_make("v4l2src", "webcam") + self.webcam.set_property("dev...
157b8a6da669a0b1cbb7c2fc8cb761267be53f19
ureport/polls/migrations/0054_add_index_poll_question_ruleset_uuid.py
ureport/polls/migrations/0054_add_index_poll_question_ruleset_uuid.py
# Generated by Django 2.2.3 on 2019-08-14 07:55 from django.db import migrations # language=SQL INDEX_SQL = """ CREATE INDEX polls_pollquestion_ruleset_uuid ON polls_pollquestion (ruleset_uuid); """ class Migration(migrations.Migration): dependencies = [("polls", "0053_poll_backend")] operations = [migrat...
Add index on poll question ruleset UUID
Add index on poll question ruleset UUID
Python
agpl-3.0
Ilhasoft/ureport,rapidpro/ureport,rapidpro/ureport,Ilhasoft/ureport,rapidpro/ureport,rapidpro/ureport,Ilhasoft/ureport,Ilhasoft/ureport
--- +++ @@ -0,0 +1,16 @@ +# Generated by Django 2.2.3 on 2019-08-14 07:55 + +from django.db import migrations + +# language=SQL +INDEX_SQL = """ +CREATE INDEX polls_pollquestion_ruleset_uuid +ON polls_pollquestion (ruleset_uuid); +""" + + +class Migration(migrations.Migration): + + dependencies = [("polls", "0053_...
386781f1b125f6983a6aa44795dee87d86b68b56
pombola/south_africa/management/commands/south_africa_import_scraped_photos.py
pombola/south_africa/management/commands/south_africa_import_scraped_photos.py
""" Loop through images in a directory and attempt to match them to a person.""" import re import os from django.core.exceptions import ObjectDoesNotExist from django.core.exceptions import MultipleObjectsReturned from django.core.management.base import LabelCommand from django.core.files import File from django.ut...
Add script to import a folder of named images and attach to people.
Add script to import a folder of named images and attach to people.
Python
agpl-3.0
hzj123/56th,geoffkilpin/pombola,hzj123/56th,patricmutwiri/pombola,patricmutwiri/pombola,patricmutwiri/pombola,mysociety/pombola,mysociety/pombola,ken-muturi/pombola,mysociety/pombola,geoffkilpin/pombola,ken-muturi/pombola,geoffkilpin/pombola,mysociety/pombola,ken-muturi/pombola,ken-muturi/pombola,patricmutwiri/pombola,...
--- +++ @@ -0,0 +1,106 @@ +""" Loop through images in a directory and attempt to match them to a person.""" + +import re +import os + +from django.core.exceptions import ObjectDoesNotExist +from django.core.exceptions import MultipleObjectsReturned +from django.core.management.base import LabelCommand + +from django....
6990a05e360dc66d26997acc3e4095b0f3910d42
tests/ttw/test_sign_in.py
tests/ttw/test_sign_in.py
from __future__ import absolute_import, division, print_function, unicode_literals from gratipay.testing import BrowserHarness class Tests(BrowserHarness): def test_sign_in_modal_is_hidden_by_default(self): self.visit('/') assert not self.css('#sign-in-modal').visible def test_clicking_sig...
Add ttw tests for sign in modal
Add ttw tests for sign in modal
Python
mit
gratipay/gratipay.com,gratipay/gratipay.com,gratipay/gratipay.com,gratipay/gratipay.com
--- +++ @@ -0,0 +1,31 @@ +from __future__ import absolute_import, division, print_function, unicode_literals + +from gratipay.testing import BrowserHarness + + +class Tests(BrowserHarness): + + def test_sign_in_modal_is_hidden_by_default(self): + self.visit('/') + + assert not self.css('#sign-in-moda...
420a5bf5783621ab30fefdfb989c8e10ef35d7c0
usecases/places/basics.py
usecases/places/basics.py
from predicthq import Client # Please copy paste your access token here # or read our Quickstart documentation if you don't have a token yet # https://developer.predicthq.com/guides/quickstart/ ACCESS_TOKEN = 'abc123' phq = Client(access_token=ACCESS_TOKEN) # You can search places in a very similar way as for event...
Add a couple of places examples
Add a couple of places examples
Python
mit
predicthq/sdk-py
--- +++ @@ -0,0 +1,22 @@ +from predicthq import Client + +# Please copy paste your access token here +# or read our Quickstart documentation if you don't have a token yet +# https://developer.predicthq.com/guides/quickstart/ +ACCESS_TOKEN = 'abc123' + +phq = Client(access_token=ACCESS_TOKEN) + + +# You can search pla...
e90e04cb3ed57145a89d9a8a94b329a3d3fc8432
lib/gen-blocks.py
lib/gen-blocks.py
#!/usr/bin/python3 # Input: https://www.unicode.org/Public/UNIDATA/Blocks.txt import io import re class Builder(object): def __init__(self): pass def read(self, infile): names = [] for line in infile: if line.startswith('#'): continue line = li...
Add a script for generating blocks
lib: Add a script for generating blocks We'll need this too.
Python
bsd-3-clause
GNOME/gnome-characters,GNOME/gnome-characters,GNOME/gnome-characters,GNOME/gnome-characters,GNOME/gnome-characters
--- +++ @@ -0,0 +1,54 @@ +#!/usr/bin/python3 + +# Input: https://www.unicode.org/Public/UNIDATA/Blocks.txt + +import io +import re + +class Builder(object): + def __init__(self): + pass + + def read(self, infile): + names = [] + for line in infile: + if line.startswith('#'): + ...
ab077c0d2daf8af4e453384e73c830b469e56d3a
tests/test_rover_instance.py
tests/test_rover_instance.py
from unittest import TestCase from rover import Rover class TestRover(TestCase): def setUp(self): self.rover = Rover() def test_rover_compass(self): assert self.rover.compass == ['N', 'E', 'S', 'W']
Add failing test for rover compass
Add failing test for rover compass
Python
mit
authentik8/rover
--- +++ @@ -0,0 +1,11 @@ + +from unittest import TestCase +from rover import Rover + +class TestRover(TestCase): + + def setUp(self): + self.rover = Rover() + + def test_rover_compass(self): + assert self.rover.compass == ['N', 'E', 'S', 'W']
a056f27c15d388be15740ea861007a9121c27c2c
mysite/senseknocker/tests.py
mysite/senseknocker/tests.py
# {{{ Imports from mysite.base.tests import make_twill_url, TwillTests # }}} class Form(TwillTests): fixtures = ['person-paulproteus.json', 'user-paulproteus.json'] def test_form_post_handler(self): client = self.login_with_client() json = client.post('/senseknocker/handle_form', { ...
# {{{ Imports from mysite.base.tests import make_twill_url, TwillTests # }}} class Form(TwillTests): fixtures = ['person-paulproteus.json', 'user-paulproteus.json'] def test_form_post_handler(self): client = self.login_with_client() bug_data = {'before': 'I was singing "Ave Maria" to a potful ...
Test that we actually create a senseknocker bug.
Test that we actually create a senseknocker bug.
Python
agpl-3.0
waseem18/oh-mainline,sudheesh001/oh-mainline,waseem18/oh-mainline,heeraj123/oh-mainline,nirmeshk/oh-mainline,Changaco/oh-mainline,vipul-sharma20/oh-mainline,vipul-sharma20/oh-mainline,Changaco/oh-mainline,waseem18/oh-mainline,ehashman/oh-mainline,ojengwa/oh-mainline,campbe13/openhatch,sudheesh001/oh-mainline,willingc/o...
--- +++ @@ -7,10 +7,16 @@ def test_form_post_handler(self): client = self.login_with_client() - json = client.post('/senseknocker/handle_form', { - 'before': 'I was singing "Ave Maria" to a potful of dal.', + bug_data = {'before': 'I was singing "Ave Maria" to a potfu...
56f2fc4c1244c0d0bbe91158988be67d9f596542
vm.py
vm.py
#!/usr/bin/env python """ Synacor challenge for OSCON 2012. Architecture description in file arch-spec. """ import struct import sys # Memory with 15-bit address space storing 16-bit numbers. # {address: number} MEM = [] # 8 (16-bit) Registers REGS = [i for i in xrange(8)] # Unbounded stack STACK = [] def run(): ...
Read input file into "memory"
Read input file into "memory"
Python
mit
fwenzel/synacor-challenge,fwenzel/synacor-challenge
--- +++ @@ -0,0 +1,45 @@ +#!/usr/bin/env python +""" +Synacor challenge for OSCON 2012. + +Architecture description in file arch-spec. +""" +import struct +import sys + + +# Memory with 15-bit address space storing 16-bit numbers. +# {address: number} +MEM = [] +# 8 (16-bit) Registers +REGS = [i for i in xrange(8)] +...
b8d488fe854794ee1a6354536dee677b175dea9d
003.py
003.py
""" Project Euler Problem 3 ======================= The prime factors of 13195 are 5, 7, 13 and 29. What is the largest prime factor of the number 600851475143? """ def highest_prime_factor(number): """ Takes a number and returns it's highest prime factor. """ prime_factor = 1 for i in range(2, i...
Add solution and unit tests for problem 3
Add solution and unit tests for problem 3
Python
mit
BeataBak/project-euler-problems
--- +++ @@ -0,0 +1,54 @@ +""" +Project Euler Problem 3 +======================= + +The prime factors of 13195 are 5, 7, 13 and 29. + +What is the largest prime factor of the number 600851475143? +""" +def highest_prime_factor(number): + """ + Takes a number and returns it's highest prime factor. + """ + p...
4a1d72300df95c666971c14d94bf77b693581d15
problem_42.py
problem_42.py
from time import time from itertools import permutations DIGITS = '1234567890' DIVS = [2, 3, 5, 7, 11, 13, 17] def check_divs(pandigital): for i in range(1, 8): if int(pandigital[i:i+3]) % DIVS[i-1]: return False return True def main(): print sum( [int(''.join(p)) for p in p...
Add problem 42, pandigital substrings divisible by first primes
Add problem 42, pandigital substrings divisible by first primes
Python
mit
dimkarakostas/project-euler
--- +++ @@ -0,0 +1,23 @@ +from time import time +from itertools import permutations + +DIGITS = '1234567890' +DIVS = [2, 3, 5, 7, 11, 13, 17] + + +def check_divs(pandigital): + for i in range(1, 8): + if int(pandigital[i:i+3]) % DIVS[i-1]: + return False + return True + + +def main(): + pri...
41b65cc8b8cf718373209ab66710dc66ecc8b66c
options/script/jiesuan_parameter.py
options/script/jiesuan_parameter.py
#!/usr/bin/python # coding: utf-8 import sys import urllib2 import json import time from datetime import datetime CURSOR='o_cursor' RD='report_date' UD='update_date' CU='COMMODITYDELIVFEEUNIT' HL='HEDGLONGMARGINRATIO' HS='HEDGSHORTMARGINRATIO' IID='INSTRUMENTID' SP='SETTLEMENTPRICE' SL='SPECLONGMARGINRATIO' SS='SPECSH...
Add script for jiesuan parameters
Add script for jiesuan parameters
Python
apache-2.0
happy6666/stockStrategies,happy6666/stockStrategies
--- +++ @@ -0,0 +1,66 @@ +#!/usr/bin/python +# coding: utf-8 +import sys +import urllib2 +import json +import time +from datetime import datetime + +CURSOR='o_cursor' +RD='report_date' +UD='update_date' +CU='COMMODITYDELIVFEEUNIT' +HL='HEDGLONGMARGINRATIO' +HS='HEDGSHORTMARGINRATIO' +IID='INSTRUMENTID' +SP='SETTLEMEN...
00bf4796086fce1991578dc0db870cb7ce0e2011
corehq/apps/reports/management/commands/find_saved_reports_with_slug.py
corehq/apps/reports/management/commands/find_saved_reports_with_slug.py
from __future__ import absolute_import, print_function from django.conf import settings from dimagi.utils.couch.cache import cache_core from corehq.apps.reports.models import ReportConfig from django.core.management import BaseCommand class Command(BaseCommand): def add_arguments(self, parser): parser.a...
Add command to find saved reports with slug
Add command to find saved reports with slug[skip ci]
Python
bsd-3-clause
dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq,dimagi/commcare-hq
--- +++ @@ -0,0 +1,28 @@ +from __future__ import absolute_import, print_function + +from django.conf import settings +from dimagi.utils.couch.cache import cache_core +from corehq.apps.reports.models import ReportConfig + +from django.core.management import BaseCommand + + +class Command(BaseCommand): + def add_arg...
575f4678b2528bfcfb5d48fdacebd59a2abd9581
tests/slaves_expectations.py
tests/slaves_expectations.py
#!/usr/bin/env python # Copyright (c) 2015 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Dumps a list of known slaves, along with their OS and master.""" import argparse import collections import json import logging ...
Add script for generating slave expectations
Add script for generating slave expectations BUG=489880 R=friedman@chromium.org Review URL: https://codereview.chromium.org/1178383002. git-svn-id: 239fca9b83025a0b6f823aeeca02ba5be3d9fd76@295683 0039d316-1c4b-4281-b951-d872f2087c98
Python
bsd-3-clause
eunchong/build,eunchong/build,eunchong/build,eunchong/build
--- +++ @@ -0,0 +1,85 @@ +#!/usr/bin/env python +# Copyright (c) 2015 The Chromium Authors. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +"""Dumps a list of known slaves, along with their OS and master.""" + +import argparse +import col...
8854737fdec0a3ba6195ffb8bb02f62b8aabfb9e
aiozk/test/test_recipe.py
aiozk/test/test_recipe.py
import pytest from aiozk.recipes.sequential import SequentialRecipe from aiozk.exc import TimeoutError, NodeExists @pytest.mark.asyncio async def test_wait_on_not_exist_sibling(zk, path): seq_recipe = SequentialRecipe(path) seq_recipe.set_client(zk) # NO WAIT await seq_recipe.wait_on_sibling('not-exi...
Add test code for SequentialRecipe
sequential: Add test code for SequentialRecipe
Python
mit
tipsi/aiozk,tipsi/aiozk
--- +++ @@ -0,0 +1,66 @@ +import pytest + +from aiozk.recipes.sequential import SequentialRecipe +from aiozk.exc import TimeoutError, NodeExists + + +@pytest.mark.asyncio +async def test_wait_on_not_exist_sibling(zk, path): + seq_recipe = SequentialRecipe(path) + seq_recipe.set_client(zk) + # NO WAIT + aw...
7889edb12598fc0e9b004bc8df34bdc59817270c
scripts/get_shodan_banners.py
scripts/get_shodan_banners.py
import re import sys import os import pprint import click try: import shodan except ImportError: print('Install shodan: pip install shodan') sys.exit(0) SHODAN_API_KEY = os.environ['SHODAN_API_KEY'] def get_headers(text): header_string = re.findall( '^(.*?)(?:[\r\n]{3,4})', text, flags=re....
Add shodan script to get page headers to test plugins
Add shodan script to get page headers to test plugins
Python
mit
spectresearch/detectem
--- +++ @@ -0,0 +1,84 @@ +import re +import sys +import os +import pprint + +import click + +try: + import shodan +except ImportError: + print('Install shodan: pip install shodan') + sys.exit(0) + + +SHODAN_API_KEY = os.environ['SHODAN_API_KEY'] + + +def get_headers(text): + header_string = re.findall( + ...
8bd86656ca589c3da1b4da078b5cd9633c018c3c
py/serialize-and-deserialize-bst.py
py/serialize-and-deserialize-bst.py
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Codec: def serialize(self, root): """Encodes a tree to a single string. :type root: TreeNode :rtype: str "...
Add py solution for 449. Serialize and Deserialize BST
Add py solution for 449. Serialize and Deserialize BST 449. Serialize and Deserialize BST: https://leetcode.com/problems/serialize-and-deserialize-bst/
Python
apache-2.0
ckclark/leetcode,ckclark/leetcode,ckclark/leetcode,ckclark/leetcode,ckclark/leetcode,ckclark/leetcode
--- +++ @@ -0,0 +1,43 @@ +# Definition for a binary tree node. +# class TreeNode(object): +# def __init__(self, x): +# self.val = x +# self.left = None +# self.right = None + +class Codec: + + def serialize(self, root): + """Encodes a tree to a single string. + :type root:...
f146cc855c76af7a7a0ba6176e2cae09b3b26446
proj2/ethDist.py
proj2/ethDist.py
#!/usr/bin/python2 # Processes Ethernet data f = open("data/eth_data.txt", "r") # skip header lines [f.readline() for i in range(3) ] data = [] for line in f: data.append(line.split()[2]) eth_types = {'Xerox PUP':0, 'Sprite':0, 'IPv4':0, 'ARP':0, 'Reverse ARP':0, 'AppleTalk ARP':0, 'IEEE 802.1Q VLAN tagging':0, '...
Add ethernet type distribution script
Add ethernet type distribution script
Python
bsd-3-clause
sjbarag/ECE-C433,sjbarag/ECE-C433,sjbarag/ECE-C433
--- +++ @@ -0,0 +1,21 @@ +#!/usr/bin/python2 +# Processes Ethernet data + +f = open("data/eth_data.txt", "r") + +# skip header lines +[f.readline() for i in range(3) ] + +data = [] + +for line in f: + data.append(line.split()[2]) + +eth_types = {'Xerox PUP':0, 'Sprite':0, 'IPv4':0, 'ARP':0, 'Reverse ARP':0, +'AppleTa...
418b1e1176f4b4d286983f69cf4e5c1deacd4afb
sympy/core/tests/test_cache.py
sympy/core/tests/test_cache.py
from sympy.core.cache import cacheit def test_cacheit_doc(): @cacheit def testfn(): "test docstring" pass assert testfn.__doc__ == "test docstring" assert testfn.__name__ == "testfn"
Add a test for the @cachit decorator.
Add a test for the @cachit decorator. Make sure that the caching decorator correctly copies over the function docstring and function name. This fixes issue #744 from the issue tracker. Signed-off-by: Jochen Voss <1dcd5c846f3eb4984f0655fb5407be7c9e0c9079@seehuhn.de> Signed-off-by: Ondrej Certik <b816faa87b7d35274d2e5...
Python
bsd-3-clause
madan96/sympy,hargup/sympy,Gadal/sympy,cswiercz/sympy,sampadsaha5/sympy,Shaswat27/sympy,fperez/sympy,atreyv/sympy,lidavidm/sympy,Davidjohnwilson/sympy,AkademieOlympia/sympy,beni55/sympy,Mitchkoens/sympy,beni55/sympy,jbbskinny/sympy,pbrady/sympy,shikil/sympy,kmacinnis/sympy,shikil/sympy,Curious72/sympy,toolforger/sympy,...
--- +++ @@ -0,0 +1,10 @@ +from sympy.core.cache import cacheit + +def test_cacheit_doc(): + @cacheit + def testfn(): + "test docstring" + pass + + assert testfn.__doc__ == "test docstring" + assert testfn.__name__ == "testfn"
138d183d0164d31fae51f3bc00dd1ea554703b7c
tests/accounts/test_backend.py
tests/accounts/test_backend.py
import pytest from django.contrib.auth import get_user from django.http import HttpRequest from django.core import mail from components.accounts.factories import EditorFactory pytestmark = pytest.mark.django_db def test_authentication_backend(client): editor = EditorFactory(base_id=1, is_active=True, username=...
Create a test for our authentication backend.
Create a test for our authentication backend.
Python
apache-2.0
hello-base/web,hello-base/web,hello-base/web,hello-base/web
--- +++ @@ -0,0 +1,20 @@ +import pytest + +from django.contrib.auth import get_user +from django.http import HttpRequest +from django.core import mail + +from components.accounts.factories import EditorFactory + +pytestmark = pytest.mark.django_db + + +def test_authentication_backend(client): + editor = EditorFact...
e6d28d55309cdf7c25062d469646e0671e877607
nose2/tests/functional/support/scenario/tests_in_package/pkg1/test/test_things.py
nose2/tests/functional/support/scenario/tests_in_package/pkg1/test/test_things.py
import unittest class SomeTests(unittest.TestCase): def test_ok(self): pass def test_typeerr(self): raise TypeError("oops") def test_failed(self): print("Hello stdout") assert False, "I failed" def test_skippy(self): raise unittest.SkipTest("I wanted to skip"...
import unittest class SomeTests(unittest.TestCase): def test_ok(self): pass def test_typeerr(self): raise TypeError("oops") def test_failed(self): print("Hello stdout") assert False, "I failed" def test_skippy(self): raise unittest.SkipTest("I wanted to skip...
Add param test cases to func test target project
Add param test cases to func test target project
Python
bsd-2-clause
ojengwa/nose2,ezigman/nose2,ezigman/nose2,leth/nose2,leth/nose2,little-dude/nose2,ptthiem/nose2,ptthiem/nose2,little-dude/nose2,ojengwa/nose2
--- +++ @@ -1,4 +1,5 @@ import unittest + class SomeTests(unittest.TestCase): @@ -14,6 +15,16 @@ def test_skippy(self): raise unittest.SkipTest("I wanted to skip") + + def test_gen_method(self): + def check(x): + assert x == 1 + yield check, 1 + yield check, 2 ...
a9d1c124813b3248188bdcd92799555ee6704c16
tests/unit/utils/which_test.py
tests/unit/utils/which_test.py
# Import python libs import os # Import Salt Testing libs from salttesting import TestCase from salttesting.helpers import ensure_in_syspath ensure_in_syspath('../../') # Import salt libs import integration import salt.utils class TestWhich(TestCase): def test_salt_utils_which(self): ''' Tests s...
Add unit test for salt.utils.which
Add unit test for salt.utils.which This is a Linux-only test, it will need some mock love to make it suitable to test for windows paths.
Python
apache-2.0
saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt
--- +++ @@ -0,0 +1,25 @@ +# Import python libs +import os + +# Import Salt Testing libs +from salttesting import TestCase +from salttesting.helpers import ensure_in_syspath +ensure_in_syspath('../../') + +# Import salt libs +import integration +import salt.utils + + +class TestWhich(TestCase): + def test_salt_util...
58fe858cc61f15dda2f9a1ca0b3937e5968fafa1
every_election/apps/elections/migrations/0058_set-gla-a-to-ballot.py
every_election/apps/elections/migrations/0058_set-gla-a-to-ballot.py
# Generated by Django 2.2.10 on 2020-02-18 08:36 from django.db import migrations def remove_gla_a_subtype(apps, schema_editor): Election = apps.get_model("elections", "Election") qs = Election.private_objects.filter(election_id__startswith="gla.a.") qs.update(group_type=None) class Migration(migration...
Change past gla.a elections to remove subtype group
Change past gla.a elections to remove subtype group
Python
bsd-3-clause
DemocracyClub/EveryElection,DemocracyClub/EveryElection,DemocracyClub/EveryElection
--- +++ @@ -0,0 +1,16 @@ +# Generated by Django 2.2.10 on 2020-02-18 08:36 + +from django.db import migrations + + +def remove_gla_a_subtype(apps, schema_editor): + Election = apps.get_model("elections", "Election") + qs = Election.private_objects.filter(election_id__startswith="gla.a.") + qs.update(group_ty...
b5187863bb951f53ef3c61ce5097550abfd2d6e9
sara_flexbe_states/src/sara_flexbe_states/Wonderland_Add_Room.py
sara_flexbe_states/src/sara_flexbe_states/Wonderland_Add_Room.py
#!/usr/bin/env python # encoding=utf8 import json import requests from flexbe_core import EventState, Logger class Wonderland_Add_Room(EventState): ''' Add an object to Wonderland. For the room, enter only ID or Name, not both. Return the ID of the added human. #> name string name of the room #> x1 ...
Add a state for add rooms
Add a state for add rooms
Python
bsd-3-clause
WalkingMachine/sara_behaviors,WalkingMachine/sara_behaviors
--- +++ @@ -0,0 +1,70 @@ +#!/usr/bin/env python +# encoding=utf8 + +import json +import requests +from flexbe_core import EventState, Logger + + +class Wonderland_Add_Room(EventState): + ''' + Add an object to Wonderland. + For the room, enter only ID or Name, not both. + Return the ID of the added human. + + #> name...
3ea8852e504c8503da0ca921ae26e7d333d877f8
src/ggrc/migrations/versions/20170224125102_4c5be77c5da3_add_slug_to_revisions.py
src/ggrc/migrations/versions/20170224125102_4c5be77c5da3_add_slug_to_revisions.py
# Copyright (C) 2017 Google Inc. # Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file> """ Add slug to revisions Create Date: 2017-02-24 12:51:02.131671 """ # disable Invalid constant name pylint warning for mandatory Alembic variables. # pylint: disable=invalid-name import sqlalchemy as sa ...
Add resource_slug to revisions table
Add resource_slug to revisions table
Python
apache-2.0
AleksNeStu/ggrc-core,plamut/ggrc-core,AleksNeStu/ggrc-core,VinnieJohns/ggrc-core,VinnieJohns/ggrc-core,VinnieJohns/ggrc-core,plamut/ggrc-core,plamut/ggrc-core,plamut/ggrc-core,AleksNeStu/ggrc-core,AleksNeStu/ggrc-core,VinnieJohns/ggrc-core
--- +++ @@ -0,0 +1,36 @@ +# Copyright (C) 2017 Google Inc. +# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file> + +""" +Add slug to revisions + +Create Date: 2017-02-24 12:51:02.131671 +""" +# disable Invalid constant name pylint warning for mandatory Alembic variables. +# pylint: disable=i...
51f044f217da30d62320444c16259f51b66da4d1
exp/alto/tools/format_tree.py
exp/alto/tools/format_tree.py
#!/usr/bin/env python3 import sys import re def format_tree(): #converts from Penn Treebank to Stanford output regex = re.compile(r"\(([A-Za-z_$]+)") with open(sys.argv[1]) as np_lines: for line in np_lines: print(regex.sub(r"\1(", line), end="") format_tree()
Add script for converting Penn Treebank to Stanford format
Add script for converting Penn Treebank to Stanford format
Python
mit
kornai/4lang,kornai/4lang,kornai/4lang,kornai/4lang
--- +++ @@ -0,0 +1,12 @@ +#!/usr/bin/env python3 + +import sys +import re + +def format_tree(): #converts from Penn Treebank to Stanford output + regex = re.compile(r"\(([A-Za-z_$]+)") + with open(sys.argv[1]) as np_lines: + for line in np_lines: + print(regex.sub(r"\1(", line), end="") + +for...
836d02874eb8c69a51bf6f40877433d106b5057f
opentreemap/otm1_migrator/management/commands/post_migrate_validation.py
opentreemap/otm1_migrator/management/commands/post_migrate_validation.py
# -*- coding: utf-8 -*- from __future__ import print_function from __future__ import unicode_literals from __future__ import division from django.conf import settings from django.contrib.contenttypes.models import ContentType from treemap.models import Species, Instance, Tree, Plot, Audit, TreePhoto from treemap.mana...
Add mgmt command for basic otm1 migration checks
Add mgmt command for basic otm1 migration checks
Python
agpl-3.0
recklessromeo/otm-core,RickMohr/otm-core,RickMohr/otm-core,maurizi/otm-core,RickMohr/otm-core,clever-crow-consulting/otm-core,recklessromeo/otm-core,maurizi/otm-core,clever-crow-consulting/otm-core,recklessromeo/otm-core,recklessromeo/otm-core,RickMohr/otm-core,maurizi/otm-core,maurizi/otm-core,clever-crow-consulting/o...
--- +++ @@ -0,0 +1,61 @@ +# -*- coding: utf-8 -*- +from __future__ import print_function +from __future__ import unicode_literals +from __future__ import division + +from django.conf import settings +from django.contrib.contenttypes.models import ContentType + +from treemap.models import Species, Instance, Tree, Plot...
af33848acf1a4dd62525d83ea061101f54805223
tests/rules_tests/CountTest.py
tests/rules_tests/CountTest.py
#!/usr/bin/env python """ :Author Patrik Valkovic :Created 23.06.2017 16:39 :Licence GNUv3 Part of grammpy """ from unittest import main, TestCase from grammpy import Rule class CountTest(TestCase): pass if __name__ == '__main__': main()
Add file for rule's count method
Add file for rule's count method
Python
mit
PatrikValkovic/grammpy
--- +++ @@ -0,0 +1,18 @@ +#!/usr/bin/env python +""" +:Author Patrik Valkovic +:Created 23.06.2017 16:39 +:Licence GNUv3 +Part of grammpy + +""" + +from unittest import main, TestCase +from grammpy import Rule + +class CountTest(TestCase): + pass + + +if __name__ == '__main__': + main()
d4ed3b57689ad7e18f8e81ed58dc7748acc35591
wsynphot/io/cache_filters.py
wsynphot/io/cache_filters.py
import os, re from wsynphot.io.get_filter_data import (get_filter_index, get_transmission_data) from wsynphot.config import get_data_dir CACHE_DIR = os.path.join(get_data_dir(), 'cached_SVO_FPS') if not os.path.exists(CACHE_DIR): os.mkdir(CACHE_DIR) def cache_as_votable(table, file_path): """Caches the ...
Add function to download filter data & cache it on disk
Add function to download filter data & cache it on disk
Python
bsd-3-clause
wkerzendorf/wsynphot
--- +++ @@ -0,0 +1,60 @@ +import os, re + +from wsynphot.io.get_filter_data import (get_filter_index, + get_transmission_data) +from wsynphot.config import get_data_dir + +CACHE_DIR = os.path.join(get_data_dir(), 'cached_SVO_FPS') +if not os.path.exists(CACHE_DIR): + os.mkdir(CACHE_DIR) + + +def cache_as_votabl...
6f79191e7aebabf55ca0a37578dcc8b43ee018b6
real_estate_agency/new_buildings/migrations/0002_builder_and_rcfeature_filepath.py
real_estate_agency/new_buildings/migrations/0002_builder_and_rcfeature_filepath.py
# -*- coding: utf-8 -*- # Generated by Django 1.11 on 2018-08-31 20:51 from __future__ import unicode_literals from django.db import migrations, models import real_estate.models.helper class Migration(migrations.Migration): dependencies = [ ('new_buildings', '0001_initial'), ] operations = [ ...
Add missing migrations for upload_to for new_building app.
Add missing migrations for upload_to for new_building app. Change upload_to for builder and residentalcomplexfeature.
Python
mit
Dybov/real_estate_agency,Dybov/real_estate_agency,Dybov/real_estate_agency
--- +++ @@ -0,0 +1,26 @@ +# -*- coding: utf-8 -*- +# Generated by Django 1.11 on 2018-08-31 20:51 +from __future__ import unicode_literals + +from django.db import migrations, models +import real_estate.models.helper + + +class Migration(migrations.Migration): + + dependencies = [ + ('new_buildings', '0001_...
1a433d9ef7a6f89f3c11c9eb5429f5ad46af6d8a
Tools/scripts/reindent-rst.py
Tools/scripts/reindent-rst.py
#!/usr/bin/env python # Make a reST file compliant to our pre-commit hook. # Currently just remove trailing whitespace. from __future__ import with_statement import sys, re, shutil ws_re = re.compile(r'\s+(\r?\n)$') def main(argv=sys.argv): rv = 0 for filename in argv[1:]: try: with open...
Add a script to fixup rst files if the pre-commit hook rejects them.
Add a script to fixup rst files if the pre-commit hook rejects them.
Python
mit
sk-/python2.7-type-annotator,sk-/python2.7-type-annotator,sk-/python2.7-type-annotator
--- +++ @@ -0,0 +1,29 @@ +#!/usr/bin/env python + +# Make a reST file compliant to our pre-commit hook. +# Currently just remove trailing whitespace. + +from __future__ import with_statement +import sys, re, shutil + +ws_re = re.compile(r'\s+(\r?\n)$') + +def main(argv=sys.argv): + rv = 0 + for filename in argv...
8273e6561f8ba9a6fda1bbddc4e15fdcdc15096f
file_templates.py
file_templates.py
#!/usr/bin/env python def eprfile(charge, multiplicity, xyzfile): """ A default template for an EPR input file. """ return """! uks pbe0 def2-tzvpp def2-tzvpp/jk ri rijk pmodel somf(1x) noautostart tightscf grid5 %pal nprocs 1 end * xyzfile {0} {1} {2}.xyz * %eprnmr tol 1e-10 gtensor 1 ori cen...
Add starting file templates for PBS/Torque job submission, ORCA EPR calculation.
Add starting file templates for PBS/Torque job submission, ORCA EPR calculation.
Python
mpl-2.0
berquist/mbe
--- +++ @@ -0,0 +1,58 @@ +#!/usr/bin/env python + + +def eprfile(charge, multiplicity, xyzfile): + """ + A default template for an EPR input file. + """ + return """! uks pbe0 def2-tzvpp def2-tzvpp/jk ri rijk pmodel somf(1x) noautostart tightscf grid5 + +%pal + nprocs 1 + end + +* xyzfile {0} {1} {2}.xyz ...
dfdce7895396ea0b80068543ed115094d677a6e2
tests/test_simulation_plot.py
tests/test_simulation_plot.py
""" Tests Simulation class read method """ import os import yaml import numpy as np from teemof import Simulation from teemof.parameters import k_parameters k_ref_file = os.path.join(os.path.abspath(os.path.dirname(__file__)), 'thermal-conductivity.yaml') time_ref_file = os.path.join(os.path.abspath(os.path.dirname(_...
Add simulation get_plot_data test for a run
Add simulation get_plot_data test for a run
Python
mit
kbsezginel/tee_mof,kbsezginel/tee_mof
--- +++ @@ -0,0 +1,37 @@ +""" +Tests Simulation class read method +""" +import os +import yaml +import numpy as np +from teemof import Simulation +from teemof.parameters import k_parameters + + +k_ref_file = os.path.join(os.path.abspath(os.path.dirname(__file__)), 'thermal-conductivity.yaml') +time_ref_file = os.path...
ff11bdd4affc4feb57b75ddfff3f705c8f57d1ba
share.py
share.py
#!/usr/bin/python import smtplib from email.mime.text import MIMEText mailto_list="123997654@qq.com" mail_host="smtp.gmail.com" mail_user="yhhong1943" mail_pass="hyh159263." mail_postfix="gmail.com" def send_mail(to_list,sub,content): me="hello"+"<"+mail_user+"@"+mail_postfix+">" msg = MIMEText(co...
Test push to the second repository.
Test push to the second repository.
Python
apache-2.0
yhhong/android-json-http
--- +++ @@ -0,0 +1,33 @@ +#!/usr/bin/python + +import smtplib +from email.mime.text import MIMEText +mailto_list="123997654@qq.com" +mail_host="smtp.gmail.com" +mail_user="yhhong1943" +mail_pass="hyh159263." +mail_postfix="gmail.com" + +def send_mail(to_list,sub,content): + me="hello"+"<"+mail_user+"@"+...
9a2963999b2f2e974fd3a286b0e4b74b010c4ba3
python/nooploop/nooploop.py
python/nooploop/nooploop.py
import argparse import timeit def noop(): return None parser = argparse.ArgumentParser() parser.add_argument("-c", "--count", default=1000000) args = parser.parse_args() start = timeit.default_timer() for x in range(int(args.count)): noop() elapsed = timeit.default_timer() - start ops_per_second = int(args...
Add python test for simple no-op loop
Add python test for simple no-op loop
Python
mit
selvasingh/azure-sdk-for-java,Azure/azure-sdk-for-java,Azure/azure-sdk-for-java,Azure/azure-sdk-for-java,Azure/azure-sdk-for-java,selvasingh/azure-sdk-for-java,selvasingh/azure-sdk-for-java,Azure/azure-sdk-for-java
--- +++ @@ -0,0 +1,20 @@ +import argparse +import timeit + +def noop(): + return None + +parser = argparse.ArgumentParser() +parser.add_argument("-c", "--count", default=1000000) +args = parser.parse_args() + +start = timeit.default_timer() + +for x in range(int(args.count)): + noop() + +elapsed = timeit.defaul...
8493ae8c32f49ed54e685fa847c3d68916545d6e
api/test/testDocumentation.py
api/test/testDocumentation.py
''' @author: Dallas Fraser @author: 2019-03-13 @organization: MLSB API @summary: Tests all the advanced fun APIs ''' from api.routes import Routes from api.test.BaseTest import TestSetup, SUCCESSFUL_GET_CODE, INVALID_ID,\ NOT_FOUND_CODE from datetime import datetime import uuid START_OF_PLATFORM = 2016 YEAR_WITH_NO...
Add a simple test for documentation
Add a simple test for documentation
Python
apache-2.0
fras2560/mlsb-platform,fras2560/mlsb-platform,fras2560/mlsb-platform
--- +++ @@ -0,0 +1,58 @@ +''' +@author: Dallas Fraser +@author: 2019-03-13 +@organization: MLSB API +@summary: Tests all the advanced fun APIs +''' +from api.routes import Routes +from api.test.BaseTest import TestSetup, SUCCESSFUL_GET_CODE, INVALID_ID,\ + NOT_FOUND_CODE +from datetime import datetime +import uuid...
e4401ba44a5faea7efcd262fde1b5bf1085fbe30
wagtail/wagtailimages/utils.py
wagtail/wagtailimages/utils.py
import os from PIL import Image from django.core.exceptions import ValidationError from django.utils.translation import ugettext_lazy as _ from django.conf import settings def validate_image_format(f): # Check file extension extension = os.path.splitext(f.name)[1].lower()[1:] if extension == 'jpg': ...
import os from PIL import Image from django.core.exceptions import ValidationError from django.utils.translation import ugettext_lazy as _ def validate_image_format(f): # Check file extension extension = os.path.splitext(f.name)[1].lower()[1:] if extension == 'jpg': extension = 'jpeg' if ...
Revert "Reopen images for validation if they are closed"
Revert "Reopen images for validation if they are closed" This reverts commit 7d43b1cf6eda74c86209a4cae0d71557ce9bdbc0.
Python
bsd-3-clause
benemery/wagtail,serzans/wagtail,davecranwell/wagtail,hamsterbacke23/wagtail,takeshineshiro/wagtail,mjec/wagtail,nealtodd/wagtail,kurtrwall/wagtail,gasman/wagtail,stevenewey/wagtail,WQuanfeng/wagtail,100Shapes/wagtail,chimeno/wagtail,nutztherookie/wagtail,wagtail/wagtail,chimeno/wagtail,iansprice/wagtail,rv816/wagtail,...
--- +++ @@ -4,7 +4,6 @@ from django.core.exceptions import ValidationError from django.utils.translation import ugettext_lazy as _ -from django.conf import settings def validate_image_format(f): @@ -17,26 +16,12 @@ if extension not in ['gif', 'jpeg', 'png']: raise ValidationError(_("Not a vali...
1a4d3d00fea775e7adaa6ff1d40346fe9e3842d8
sandbox/samples/python/studio/plugins/basicenumerator/__init__.py
sandbox/samples/python/studio/plugins/basicenumerator/__init__.py
# # This source file is part of appleseed. # Visit http://appleseedhq.net/ for additional information and resources. # # This software is released under the MIT license. # # Copyright (c) 2017 Francois Beaune, The appleseedhq Organization # # Permission is hereby granted, free of charge, to any person obtaining a copy...
Add basicenumerator appleseed.studio Python plugin sample
Add basicenumerator appleseed.studio Python plugin sample
Python
mit
pjessesco/appleseed,Biart95/appleseed,pjessesco/appleseed,est77/appleseed,luisbarrancos/appleseed,Biart95/appleseed,appleseedhq/appleseed,Vertexwahn/appleseed,luisbarrancos/appleseed,pjessesco/appleseed,est77/appleseed,luisbarrancos/appleseed,aytekaman/appleseed,aytekaman/appleseed,Biart95/appleseed,dictoon/appleseed,a...
--- +++ @@ -0,0 +1,57 @@ + +# +# This source file is part of appleseed. +# Visit http://appleseedhq.net/ for additional information and resources. +# +# This software is released under the MIT license. +# +# Copyright (c) 2017 Francois Beaune, The appleseedhq Organization +# +# Permission is hereby granted, free of c...
dbdada2dd1b61b10f402ee8163442d2653c1876b
training/level-1-the-zen-of-python/dragon-warrior/palindrome/tmarsha1-palindrome.py
training/level-1-the-zen-of-python/dragon-warrior/palindrome/tmarsha1-palindrome.py
__author__ = 'tmarsha1' """ find largest palindrome for the product of 2 three digit numbers (100-999) or (100^2 - 999^2) Answer is 913 * 993 = 906609 """ import re class Word(object): def __init__(self, values): concat = "" for value in values: concat = concat + ...
Add homework solution for tmarsha1.
Add homework solution for tmarsha1.
Python
artistic-2.0
bigfatpanda-training/pandas-practical-python-primer,bigfatpanda-training/pandas-practical-python-primer
--- +++ @@ -0,0 +1,58 @@ +__author__ = 'tmarsha1' + +""" find largest palindrome for the product of 2 three digit numbers + (100-999) or (100^2 - 999^2) + Answer is 913 * 993 = 906609 +""" + +import re + +class Word(object): + def __init__(self, values): + concat = "" + for value in values: + ...
ab44c1615f124b558e30d5d1432876dcc60dbf3d
testrepository/repository/samba_buildfarm.py
testrepository/repository/samba_buildfarm.py
# Copyright (c) 2009, 2010 Testrepository Contributors # # Licensed under either the Apache License, Version 2.0 or the BSD 3-clause # license at the users choice. A copy of both licenses are available in the # project source as Apache-2.0 and BSD. You may not use this file except in # compliance with one of these two...
Add repository backend for samba buildfarm.
Add repository backend for samba buildfarm.
Python
apache-2.0
mtreinish/stestr,masayukig/stestr,mtreinish/stestr,masayukig/stestr
--- +++ @@ -0,0 +1,87 @@ +# Copyright (c) 2009, 2010 Testrepository Contributors +# +# Licensed under either the Apache License, Version 2.0 or the BSD 3-clause +# license at the users choice. A copy of both licenses are available in the +# project source as Apache-2.0 and BSD. You may not use this file except in +#...
3b582b60ddcf3e46529bdca52a0bbe7fbe6f117d
bin/get_gdrive_credentials.py
bin/get_gdrive_credentials.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Usage: python get_gdrive_credentials.py PATH_TO_SECRET_FILE The purpose of this script is to create google login credentials to be used by google drive writer. Expected workflow is: 1.- Get the client secret file. If you haven't one, please follow this tutorial: http...
Add script to assist in Gdrive Credentials.
Add script to assist in Gdrive Credentials.
Python
bsd-3-clause
scrapinghub/exporters
--- +++ @@ -0,0 +1,47 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +""" +Usage: python get_gdrive_credentials.py PATH_TO_SECRET_FILE + +The purpose of this script is to create google login credentials to be used by google drive +writer. + +Expected workflow is: + +1.- Get the client secret file. If you haven't ...
51101cc1ca180a7a9a494517d111d1e1186bd199
basics/numpy_structured_data.py
basics/numpy_structured_data.py
import numpy as np # old way to do it, make 3 different arrays of data. The downside of this is that it doesnt necessarily # tell us that these 3 are related data sets. Though then again its quite simple if you're not an idiot name = ["Alice", "Bob", "Cathy", "Doug"] age = [25, 45, 37, 19] weight = [55.0, 85.5, 68.0,...
Work on understanding a bit about structured arrays in NUmpy before moving on to pandas dataframes
Work on understanding a bit about structured arrays in NUmpy before moving on to pandas dataframes
Python
mit
paulmorio/grusData,paulmorio/grusData
--- +++ @@ -0,0 +1,42 @@ +import numpy as np + +# old way to do it, make 3 different arrays of data. The downside of this is that it doesnt necessarily +# tell us that these 3 are related data sets. Though then again its quite simple if you're not an idiot +name = ["Alice", "Bob", "Cathy", "Doug"] +age = [25, 45, 37...
79d1ab43d187d8ba1350965673b930fa0b3879b6
rosbridge_suite/rosbridge_library/src/rosbridge_library/internal/pngcompression.py
rosbridge_suite/rosbridge_library/src/rosbridge_library/internal/pngcompression.py
from pypng.code import png from base64 import standard_b64encode, standard_b64decode from StringIO import StringIO def encode(string): """ PNG-compress the string, return the b64 encoded bytes """ bytes = list(bytearray(string)) png_image = png.from_array([bytes], 'L') buff = StringIO() png_image....
from pypng.code import png from PIL import Image from base64 import standard_b64encode, standard_b64decode from StringIO import StringIO def encode(string): """ PNG-compress the string, return the b64 encoded bytes """ i = Image.fromstring('L', (len(string), 1), string) buff = StringIO() i.save(buff, ...
Use python imaging library to encode PNG instead of pypng
Use python imaging library to encode PNG instead of pypng
Python
bsd-3-clause
WangRobo/rosbridge_suite,vladrotea/rosbridge_suite,kbendick/rosbridge_suite,vladrotea/rosbridge_suite,RobotWebTools/rosbridge_suite,DLu/rosbridge_suite,SNU-Sigma/rosbridge_suite,DLu/rosbridge_suite,DLu/rosbridge_suite,mayfieldrobotics/rosbridge_suite,mayfieldrobotics/rosbridge_suite,WangRobo/rosbridge_suite,SNU-Sigma/r...
--- +++ @@ -1,14 +1,14 @@ from pypng.code import png +from PIL import Image from base64 import standard_b64encode, standard_b64decode from StringIO import StringIO def encode(string): """ PNG-compress the string, return the b64 encoded bytes """ - bytes = list(bytearray(string)) - png_image = png.f...
f17ce5bf794040d4193b9b3d276e2784a41dce0a
zou/app/models/output_type.py
zou/app/models/output_type.py
from zou.app import db from zou.app.models.serializer import SerializerMixin from zou.app.models.base import BaseMixin class OutputType(db.Model, BaseMixin, SerializerMixin): name = db.Column(db.String(40), unique=True, nullable=False) short_name = db.Column(db.String(20), nullable=False)
Add model for output type
Add model for output type
Python
agpl-3.0
cgwire/zou
--- +++ @@ -0,0 +1,8 @@ +from zou.app import db +from zou.app.models.serializer import SerializerMixin +from zou.app.models.base import BaseMixin + + +class OutputType(db.Model, BaseMixin, SerializerMixin): + name = db.Column(db.String(40), unique=True, nullable=False) + short_name = db.Column(db.String(20), nu...
9ce0806a5e4262b299e3bd98c8a722a309734dc3
examples/cplearning.py
examples/cplearning.py
#!/usr/bin/python # -*- coding: utf-8 -*- from semcplogic.dataset import Dataset from semcplogic.cpmodel import TableResultInterpreter from semcplogic.cpcompiler import CPCompiler, ProblogExample from semcplogic.problogresult import GnuplotDrawer import pprint #We use "breaks" because break is a reserved keyword in p...
Add example of CP-logic parameter learning
Add example of CP-logic parameter learning
Python
bsd-2-clause
verhoevenv/semcplogic,verhoevenv/semcplogic,verhoevenv/semcplogic
--- +++ @@ -0,0 +1,56 @@ +#!/usr/bin/python +# -*- coding: utf-8 -*- + +from semcplogic.dataset import Dataset +from semcplogic.cpmodel import TableResultInterpreter +from semcplogic.cpcompiler import CPCompiler, ProblogExample +from semcplogic.problogresult import GnuplotDrawer +import pprint + +#We use "breaks" bec...
e164ff0feda4be50e9d63695881b4d28a7702cc6
examples/Gauss_example.py
examples/Gauss_example.py
import sys import time import numpy as np from abcpy.core import * from abcpy.distributions import * from distributed import Client from dask.dot import dot_graph from functools import partial import matplotlib import matplotlib.pyplot as plt def normal_simu(n, mu, prng=None, latents=None): if latents is None: ...
Add script variant of the Gauss example
Add script variant of the Gauss example
Python
mit
akangasr/elfi
--- +++ @@ -0,0 +1,75 @@ +import sys +import time +import numpy as np +from abcpy.core import * +from abcpy.distributions import * +from distributed import Client +from dask.dot import dot_graph +from functools import partial + +import matplotlib +import matplotlib.pyplot as plt + +def normal_simu(n, mu, prng=None, l...
678c9849e4763d645f571a0b558394afa04477c5
bathy/make_okada.py
bathy/make_okada.py
#!/usr/bin/env python import sys import numpy import matplotlib.pyplot as plt import clawpack.geoclaw.okada2 as okada import clawpack.geoclaw.topo as topo import clawpack.geoclaw.dtopotools as dtopotools import clawpack.visclaw.colormaps as colormaps plot_fault = False if len(sys.argv) > 1: if sys.argv[1] == "p...
Add simple script for creating Okada deformations
Add simple script for creating Okada deformations
Python
mit
mandli/compsyn-geoclaw
--- +++ @@ -0,0 +1,57 @@ +#!/usr/bin/env python + +import sys + +import numpy +import matplotlib.pyplot as plt + +import clawpack.geoclaw.okada2 as okada +import clawpack.geoclaw.topo as topo +import clawpack.geoclaw.dtopotools as dtopotools +import clawpack.visclaw.colormaps as colormaps + +plot_fault = False +if le...
55bf12c80fe14b317fdc27d74c27642a144d4530
tests/test_generate_files.py
tests/test_generate_files.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ test_generate_files ------------------- Test formerly known from a unittest residing in test_generate.py named TestGenerateFiles.test_generate_files_nontemplated_exception """ def test_generate_files_nontemplated_exception(): pass
Create new test module to convert the first test
Create new test module to convert the first test
Python
bsd-3-clause
ramiroluz/cookiecutter,dajose/cookiecutter,lucius-feng/cookiecutter,terryjbates/cookiecutter,tylerdave/cookiecutter,sp1rs/cookiecutter,takeflight/cookiecutter,nhomar/cookiecutter,christabor/cookiecutter,willingc/cookiecutter,hackebrot/cookiecutter,luzfcb/cookiecutter,jhermann/cookiecutter,ramiroluz/cookiecutter,pjbull/...
--- +++ @@ -0,0 +1,14 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- + +""" +test_generate_files +------------------- + +Test formerly known from a unittest residing in test_generate.py named +TestGenerateFiles.test_generate_files_nontemplated_exception +""" + + +def test_generate_files_nontemplated_exception(): ...
29e9d3a5fbac2730acd4c2115399556b09fb83e5
tools/psycopg2_experiment.py
tools/psycopg2_experiment.py
#!/usr/bin/env python ''' A CLI tool for formulating an Abba url using data from PostgreSQL ''' from __future__ import print_function import argparse import psycopg2 import sys TOOL_DESCRIPTION = ''' Formulates an Abba url using data from PostgreSQL The query passed to this tool should return three columns, which ...
Add tool for pulling data from PostgreSQL to Abba
Add tool for pulling data from PostgreSQL to Abba
Python
bsd-3-clause
thumbtack/abba,thii/abbajs,thumbtack/abba,thumbtack/abba
--- +++ @@ -0,0 +1,74 @@ +#!/usr/bin/env python +''' +A CLI tool for formulating an Abba url using data from PostgreSQL +''' + +from __future__ import print_function + +import argparse +import psycopg2 +import sys + + +TOOL_DESCRIPTION = ''' +Formulates an Abba url using data from PostgreSQL + +The query passed to th...
5f093d9230ac65e8c9a6d8d9a43e01d06729f260
phwatch.py
phwatch.py
import requests, datetime #todo: argparse acceptable = [7.5, 8.5] #good data interval interval = 15 #minutes of samples to check (0.33 samples per minute) threshold = 2 #number of points outside interval to look for medium = "water quality" metric = "pH" def gethalbyname(data, name): for d in data: if d["...
Add script to watch a metric for unexpectedly high or low values
Add script to watch a metric for unexpectedly high or low values
Python
mit
LEWASatVT/lewas
--- +++ @@ -0,0 +1,29 @@ +import requests, datetime + +#todo: argparse +acceptable = [7.5, 8.5] #good data interval +interval = 15 #minutes of samples to check (0.33 samples per minute) +threshold = 2 #number of points outside interval to look for +medium = "water quality" +metric = "pH" + +def gethalbyname(data, nam...
06d7a2c45f6d93870fe8cba74d5fb563c6b62149
conf/init_mongodb.py
conf/init_mongodb.py
import getpass import hashlib from pymongo import MongoClient spider_db = MongoClient().spider admin_present = False for user in spider_db.auth.find(): if user["username"] == "admin": admin_present = True break if not admin_present: password1 = getpass.getpass("Give a password for the admin u...
Add initialisation script to add the admin user.
Add initialisation script to add the admin user.
Python
apache-2.0
asteroide/immo_spider,asteroide/immo_spider,asteroide/immo_spider,asteroide/immo_spider
--- +++ @@ -0,0 +1,27 @@ +import getpass +import hashlib +from pymongo import MongoClient + +spider_db = MongoClient().spider + +admin_present = False +for user in spider_db.auth.find(): + if user["username"] == "admin": + admin_present = True + break + +if not admin_present: + password1 = getpass...
6da8c10aa9cf849ec6af097c0dae85b3bef930c3
django_modelviews/templatetags/modelview_list.py
django_modelviews/templatetags/modelview_list.py
from django import template from django.db import models from django.utils.safestring import mark_safe register = template.Library() @register.filter def model_row(instance, fields): for name in fields.split(','): f = instance._meta.get_field(name) if isinstance(f, models.ForeignKey): ...
Add simple model_row template filter
Add simple model_row template filter
Python
bsd-3-clause
matthiask/towel,matthiask/towel,matthiask/towel,matthiask/towel
--- +++ @@ -0,0 +1,29 @@ +from django import template +from django.db import models +from django.utils.safestring import mark_safe + + +register = template.Library() + + +@register.filter +def model_row(instance, fields): + for name in fields.split(','): + f = instance._meta.get_field(name) + + if is...