commit
stringlengths
40
40
old_file
stringlengths
4
236
new_file
stringlengths
4
236
old_contents
stringlengths
1
3.26k
new_contents
stringlengths
16
4.43k
subject
stringlengths
16
624
message
stringlengths
17
3.29k
lang
stringclasses
5 values
license
stringclasses
13 values
repos
stringlengths
5
91.5k
cc7253020251bc96d7d7f22a991b094a60bbc104
startServers.py
startServers.py
import sys import time import subprocess import psutil def startServer(command): if sys.platform.startswith('win'): return psutil.Popen(command, creationflags=subprocess.CREATE_NEW_CONSOLE) else: linuxCommand = 'xterm -hold -e "%s"' % command return psutil.Popen(linuxCommand, shell=True) def main(baseCommand...
import sys import time import subprocess def main(baseCommand, startingPort, count): procs = [] for i in range(1,count + 1): command = baseCommand + ' ' + str(startingPort + i) if sys.platform.startswith('win'): process = subprocess.Popen(command, creationflags=subprocess.CREATE_NEW_CONSOLE) else: linux...
Revert "keep servers running for fun and profit"
Revert "keep servers running for fun and profit" This reverts commit c574ba41fb609db7a2c75340363fe1a1dcc31399.
Python
mit
IngenuityEngine/coren_proxy,IngenuityEngine/coren_proxy
6ac172843dc78ae6af87f00b260ef70f8965b3b7
start_server.py
start_server.py
#!/usr/bin/env python3 # tsuserver3, an Attorney Online server # # Copyright (C) 2016 argoneus <argoneuscze@gmail.com> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the ...
#!/usr/bin/env python3 # tsuserver3, an Attorney Online server # # Copyright (C) 2016 argoneus <argoneuscze@gmail.com> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the ...
Handle case where pip is not found
Handle case where pip is not found
Python
agpl-3.0
Attorney-Online-Engineering-Task-Force/tsuserver3,Mariomagistr/tsuserver3
e54fa97cb44557454655efd24380da5223a1c5ae
tests/random_object_id/random_object_id_test.py
tests/random_object_id/random_object_id_test.py
import contextlib import re import sys import mock from six.moves import cStringIO from random_object_id.random_object_id import \ gen_random_object_id, parse_args, main @contextlib.contextmanager def captured_output(): new_out = StringIO() old_out = sys.stdout try: sys.stdout = new_out ...
import contextlib import re import sys import mock import six from random_object_id.random_object_id import \ gen_random_object_id, parse_args, main @contextlib.contextmanager def captured_output(): old_out = sys.stdout try: sys.stdout = six.StringIO() yield sys.stdout finally: ...
Change how StringIO is imported
Change how StringIO is imported
Python
mit
mxr/random-object-id
80da397eb882622bc0bf1641bc4ee4e5813cf655
lopypi/pypi.py
lopypi/pypi.py
import re from urlparse import urlsplit from bs4 import BeautifulSoup import requests from urlparse import urldefrag, urljoin class PyPI(object): def __init__(self, index="http://pypi.python.org/simple"): self._index = index def list_packages(self): resp = requests.get(self._index) s...
import re from urlparse import urlsplit from bs4 import BeautifulSoup import requests from urlparse import urldefrag, urljoin class PyPI(object): def __init__(self, index="http://pypi.python.org/simple"): self._index = index def list_packages(self): resp = requests.get(self._index) s...
Replace reference to previously factored out variable
Replace reference to previously factored out variable
Python
mit
bwhmather/LoPyPI,bwhmather/LoPyPI
4b6ae0eb113689515ba38e85c33a2ba40e58a163
src/minerva/storage/trend/engine.py
src/minerva/storage/trend/engine.py
from contextlib import closing from operator import contains from functools import partial from minerva.util import k, identity from minerva.directory import EntityType from minerva.storage import Engine from minerva.storage.trend import TableTrendStore class TrendEngine(Engine): @staticmethod def store_cmd(...
from contextlib import closing from operator import contains from functools import partial from minerva.util import k, identity from minerva.directory import EntityType from minerva.storage import Engine from minerva.storage.trend import TableTrendStore class TrendEngine(Engine): @staticmethod def store_cmd(...
Rename parameter filter_package to a more appropriate transform_package
Rename parameter filter_package to a more appropriate transform_package
Python
agpl-3.0
hendrikx-itc/minerva,hendrikx-itc/minerva
1db5ed3fa2fbb724c480bbf52c1d40c390dc857f
examples/example1.py
examples/example1.py
import fte.encoder regex = '^(a|b)+$' fixed_slice = 512 input_plaintext = 'test' fteObj = fte.encoder.RegexEncoder(regex, fixed_slice) ciphertext = fteObj.encode(input_plaintext) output_plaintext = fteObj.decode(ciphertext) print 'regex='+regex print 'fixed_slice='+str(fixed_slice) print 'input_plaintext='+input_pl...
import regex2dfa import fte.encoder regex = '^(a|b)+$' fixed_slice = 512 input_plaintext = 'test' dfa = regex2dfa.regex2dfa(regex) fteObj = fte.encoder.DfaEncoder(dfa, fixed_slice) ciphertext = fteObj.encode(input_plaintext) [output_plaintext, remainder] = fteObj.decode(ciphertext) print 'input_plaintext='+input_pl...
Update example code to represent current FTE API and usage.
Update example code to represent current FTE API and usage.
Python
apache-2.0
kpdyer/libfte,kpdyer/libfte
f38b117316039042f3c00c73bbb7ceaeb0f2e6e1
src/python/pants/core_tasks/noop.py
src/python/pants/core_tasks/noop.py
# coding=utf-8 # Copyright 2014 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import (absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement) from pants.task.noop...
# coding=utf-8 # Copyright 2014 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import (absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement) from pants.task.noop...
Add public api markers for core_tasks
Add public api markers for core_tasks The following modules were reviewed and all api's were left as private. As far as I can tell these modules are not currently used by plugins. * pants.core_tasks.bash_completion.py * pants.core_tasks.changed_target_tasks.py * pants.core_tasks.clean.py * pants.core_tasks.deferred_s...
Python
apache-2.0
manasapte/pants,twitter/pants,fkorotkov/pants,jsirois/pants,pantsbuild/pants,peiyuwang/pants,pombredanne/pants,cevaris/pants,fkorotkov/pants,mateor/pants,baroquebobcat/pants,gmalmquist/pants,peiyuwang/pants,fkorotkov/pants,wisechengyi/pants,fkorotkov/pants,UnrememberMe/pants,wisechengyi/pants,ericzundel/pants,ericzunde...
a4184edab35890673b8b6a67e68a73e6ab7f0b89
tests/runtests.py
tests/runtests.py
#!/usr/bin/env python import os import sys from unittest import defaultTestLoader, TextTestRunner, TestSuite TESTS = ('form', 'fields', 'validators', 'widgets', 'webob_wrapper', 'translations', 'ext_csrf', 'ext_i18n') def make_suite(prefix='', extra=()): tests = TESTS + extra test_names = list(prefix + x for ...
#!/usr/bin/env python import os import sys from unittest import defaultTestLoader, TextTestRunner, TestSuite TESTS = ('form', 'fields', 'validators', 'widgets', 'webob_wrapper', 'translations', 'ext_csrf', 'ext_i18n') def make_suite(prefix='', extra=()): tests = TESTS + extra test_names = list(prefix + x for ...
Add back in running of extra tests
Add back in running of extra tests
Python
bsd-3-clause
jmagnusson/wtforms,cklein/wtforms,Xender/wtforms,pawl/wtforms,Aaron1992/wtforms,pawl/wtforms,subyraman/wtforms,wtforms/wtforms,skytreader/wtforms,hsum/wtforms,Aaron1992/wtforms,crast/wtforms
52ddec80be8e2c90807a7b07425a6f260c9e86e0
src/zeit/retresco/tests/test_tag.py
src/zeit/retresco/tests/test_tag.py
# coding: utf8 import unittest class TagTest(unittest.TestCase): """Testing ..tag.Tag.""" def test_from_code_generates_a_tag_object_equal_to_its_source(self): from ..tag import Tag tag = Tag(u'Vipraschül', 'Person') self.assertEqual(tag, Tag.from_code(tag.code))
# coding: utf8 import zeit.cms.interfaces import zeit.retresco.testing class TagTest(zeit.retresco.testing.FunctionalTestCase): """Testing ..tag.Tag.""" def test_from_code_generates_a_tag_object_equal_to_its_source(self): from ..tag import Tag tag = Tag(u'Vipraschül', 'Person') self.a...
Test that adapter in `zeit.cms` handles unicode escaped uniqueId correctly.
ZON-3199: Test that adapter in `zeit.cms` handles unicode escaped uniqueId correctly.
Python
bsd-3-clause
ZeitOnline/zeit.retresco
0b6e0e09abd007dad504693ca8cae4c7b0222765
gamernews/apps/threadedcomments/views.py
gamernews/apps/threadedcomments/views.py
from django.shortcuts import render_to_response, get_object_or_404 from django.template import RequestContext from django.contrib.auth.decorators import login_required from django.utils.translation import ugettext as _ from django.views.generic.list import ListView from core.models import Account as User from django_c...
from django.shortcuts import render_to_response, get_object_or_404 from django.template import RequestContext from django.contrib.auth.decorators import login_required from django.utils.translation import ugettext as _ from django.views.generic.list import ListView from core.models import Account as User from django_c...
Remove name, url and email from comment form
Remove name, url and email from comment form
Python
mit
underlost/GamerNews,underlost/GamerNews
716c0c4ab08266ce42f65afc0cd4bd8e0ed191e0
table_parser.py
table_parser.py
#!/usr/bin/python import sys import latex_table import table_to_file if __name__ == "__main__": # Parse arguments import argparse parser = argparse.ArgumentParser() parser.add_argument("input", help="the LaTeX input file to be parsed") # Add two mutually exclusive arguments: grouped/ungrouped ...
#!/usr/bin/python import sys import latex_table import table_to_file if __name__ == "__main__": # Parse arguments import argparse parser = argparse.ArgumentParser() parser.add_argument("input", help="the LaTeX input file to be parsed") # Add two mutually exclusive arguments: grouped/ungrouped ...
Remove exit statement and error message for tex output
Remove exit statement and error message for tex output
Python
mit
knutzk/parse_latex_table
a0fa76a7aeb3dba3b358abeab95fc03a90a0e8b6
members/views.py
members/views.py
from django.shortcuts import render def homepage(request): return render(request, "index.html", {})
from django.shortcuts import render from django.http import HttpResponse from .models import User def homepage(request): return render(request, "index.html", {}) def search(request, name): members = User.objects.filter(first_name__icontains=name) or \ User.objects.filter(last_name__icontains=name) ...
Add view for searching users and return json format
Add view for searching users and return json format
Python
mit
Hackfmi/Diaphanum,Hackfmi/Diaphanum
4e31496e1d9e0b2af2ce8aa4bb58baa86f352521
flake8_docstrings.py
flake8_docstrings.py
# -*- coding: utf-8 -*- """pep257 docstrings convention needs error code and class parser for be included as module into flake8 """ import io import pep8 import pep257 __version__ = '0.2.2' class pep257Checker(object): """flake8 needs a class to check python file.""" name = 'pep257' version = __versio...
# -*- coding: utf-8 -*- """Implementation of pep257 integration with Flake8. pep257 docstrings convention needs error code and class parser for be included as module into flake8 """ import io import pep8 import pep257 __version__ = '0.2.2' class pep257Checker(object): """Flake8 needs a class to check python fi...
Fix up a couple of minor issues
Fix up a couple of minor issues
Python
mit
PyCQA/flake8-docstrings
e5ef9ca9c089ce1da4ff363d0c5a5090785ae0c5
test_scraper.py
test_scraper.py
from scraper import search_CL from scraper import read_search_results def test_search_CL(): test_body, test_encoding = search_CL(minAsk=100) assert "<span class=\"desktop\">craigslist</span>" in test_body assert test_encoding == 'utf-8' def test_read_search_result(): test_body, test_encoding = read_...
from scraper import search_CL from scraper import read_search_results from scraper import parse_source from scraper import extract_listings import bs4 def test_search_CL(): test_body, test_encoding = search_CL(minAsk=100, maxAsk=100) assert "<span class=\"desktop\">craigslist</span>" in test_body assert t...
Add test for extract listings that asserts each listing is a bs4.element.Tag
Add test for extract listings that asserts each listing is a bs4.element.Tag
Python
mit
jefrailey/basic-scraper
aca158817c21b8baeeb64d7290d61c32a79124f9
tests/test_heat_demand.py
tests/test_heat_demand.py
""" Test the electricity demand SPDX-FileCopyrightText: Uwe Krien <krien@uni-bremen.de> SPDX-FileCopyrightText: Patrik Schönfeldt SPDX-License-Identifier: MIT """ import numpy as np from demandlib.examples import heat_demand_example def test_heat_example(): """Test the results of the heat example.""" ann...
""" Test the electricity demand SPDX-FileCopyrightText: Uwe Krien <krien@uni-bremen.de> SPDX-FileCopyrightText: Patrik Schönfeldt SPDX-License-Identifier: MIT """ import numpy as np from demandlib.examples import heat_demand_example def test_heat_example(): """Test the results of the heat example.""" ann...
Increase tollerance for heat demand test
Increase tollerance for heat demand test
Python
mit
oemof/demandlib
0060a32b58c7769ac97ac894cbaf6a2eaa1b389f
mmiisort/main.py
mmiisort/main.py
from isort import SortImports import mothermayi.colors import mothermayi.errors import mothermayi.files def plugin(): return { 'name' : 'isort', 'pre-commit' : pre_commit, } def do_sort(filename): results = SortImports(filename) return getattr(results, 'in_lines', None) and...
from isort import SortImports import mothermayi.colors import mothermayi.errors import mothermayi.files def plugin(): return { 'name' : 'isort', 'pre-commit' : pre_commit, } def do_sort(filename): results = SortImports(filename, check=True) return results.incorrectly_sorted...
Leverage isort's check mode to make our logic simpler
Leverage isort's check mode to make our logic simpler This avoids having to check for in_lines or compare against the out_lines by just asking for a check and using the results
Python
mit
EliRibble/mothermayi-isort
ed76f648f60f96216377e4f12fea7043eaed904b
tests/helpers.py
tests/helpers.py
import virtualbox def list_machines(): vbox = virtualbox.vb_get_manager() for machine in vbox.getArray(vbox, "Machines"): print "Machine '%s' logs in '%s'" % ( machine.name, machine.logFolder )
import unittest import virtualbox class VirtualboxTestCase(unittest.TestCase): def setUp(self): self.vbox = virtualbox.vb_get_manager() def assertMachineExists(self, name, msg=None): try: self.vbox.findMachine(name) except Exception as e: if msg: ...
Create a basic VirtualBoxTestCase with helper assertions
Create a basic VirtualBoxTestCase with helper assertions
Python
apache-2.0
saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt
990a3266739e5a4d763dd585f7cb722c0fe2b0f5
astroplpython/function/statistic/Maximum.py
astroplpython/function/statistic/Maximum.py
''' Created on Feb 6, 2015 @author: thomas ''' class Maximum (object): @staticmethod def calculate (measurement_list): import numpy as np ''' Find the maximum measurement value for any list of measured values. ''' x = [] for val in measurement_list: ...
''' Created on Feb 6, 2015 @author: thomas ''' class Maximum (object): @staticmethod def calculate (measurement_list): import numpy as np ''' Find the maximum measurement value for any list of measured values. ''' x = [] for val in measurement_list: ...
Remove initializer..this is a 'static' class which
Remove initializer..this is a 'static' class which we are using functional approach with, e.g. no instances if we can help it..
Python
mit
brianthomas/astroplpython,brianthomas/astroplpython
554ef995f8c4ba42d00482480bf291bac2fd96e1
utils/database.py
utils/database.py
import json class Database(dict): """Holds a dict that contains all the information about the users in a channel""" def __init__(self, irc): super(Database, self).__init__(json.load(open("userdb.json"))) self.irc = irc def remove_entry(self, event, nick): try: del self...
import json class Database(dict): """Holds a dict that contains all the information about the users in a channel""" def __init__(self, irc): super(Database, self).__init__(json.load(open("userdb.json"))) self.irc = irc def remove_entry(self, event, nick): try: del self...
Reduce code to a simpler form that checks if a user is already in the DB
Reduce code to a simpler form that checks if a user is already in the DB
Python
mit
wolfy1339/Python-IRC-Bot
12f3cc403f6ba0be957d1fb18253fb7529009764
moss/plotting.py
moss/plotting.py
import matplotlib.pyplot as plt def grid_axes_labels(f, xlabel=None, ylabel=None, **kws): axes = f.axes plt.setp(axes.flat, xlabel="", ylabel="") if xlabel is not None: for ax in axes[-1]: ax.set_xlabel(xlabel, **kws) if ylabel is not None: for ax in axes[0]: ...
import matplotlib.pyplot as plt def grid_axes_labels(axes, xlabel=None, ylabel=None, **kws): plt.setp(axes.flat, xlabel="", ylabel="") if xlabel is not None: for ax in axes[-1]: ax.set_xlabel(xlabel, **kws) if ylabel is not None: for ax in axes[0]: ax.set_ylabel(...
Use matrix of axes not figure
Use matrix of axes not figure
Python
bsd-3-clause
mwaskom/moss,mwaskom/moss
02e03748e66ebf516a4a9b24f52563362e6bb895
command_line/scale_down_images.py
command_line/scale_down_images.py
from __future__ import division def nproc(): from libtbx.introspection import number_of_processors return number_of_processors(return_value_if_unknown=-1) def joiner(args): from dials.util.scale_down_image import scale_down_image scale_down_image(*args) def scale_down_images(in_template, out_template, start,...
from __future__ import division def nproc(): from libtbx.introspection import number_of_processors return number_of_processors(return_value_if_unknown=-1) def joiner(args): from dials.util.scale_down_image import scale_down_image scale_down_image(*args) print args[1] def scale_down_images(in_template, out_...
Print out file name after writing
Print out file name after writing
Python
bsd-3-clause
dials/dials,dials/dials,dials/dials,dials/dials,dials/dials
49ce9aa1bdd3479c31b8aa2e606b1768a444aea2
irrigator_pro/farms/templatetags/today_filters.py
irrigator_pro/farms/templatetags/today_filters.py
from django import template from datetime import date, datetime, timedelta register = template.Library() @register.filter(expects_localtime=True) def is_today(value): if isinstance(value, datetime): value = value.date() return value == date.today() @register.filter(expects_localtime=True) def is_past...
from django import template from datetime import date, datetime, timedelta register = template.Library() @register.filter(expects_localtime=True) def is_today(value): if isinstance(value, datetime): value = value.date() return value == date.today() @register.filter(expects_localtime=True) def is_past...
Add new filter to determine if today is within the time period for a season.
Add new filter to determine if today is within the time period for a season.
Python
mit
warnes/irrigatorpro,warnes/irrigatorpro,warnes/irrigatorpro,warnes/irrigatorpro
0e0b96d0d800716102204cfdca7317ccb92cee95
pytextql/util.py
pytextql/util.py
# -*- coding: utf-8 -*- import csv import itertools def grouper(iterable, n): """ Slice up `iterable` into iterables of `n` items. :param iterable: Iterable to splice. :param n: Number of items per slice. :returns: iterable of iterables """ it = iter(iterable) while True: chun...
# -*- coding: utf-8 -*- import csv import itertools def grouper(iterable, n): """ Slice up `iterable` into iterables of `n` items. :param iterable: Iterable to splice. :param n: Number of items per slice. :returns: iterable of iterables """ it = iter(iterable) while True: chun...
Add a simple UnicodeCSVWriter, probably flawed.
Add a simple UnicodeCSVWriter, probably flawed.
Python
mit
TkTech/pytextql
c67acb72d5ddea8a1e4fb8a12aa3a6913629e0cb
Lib/setup.py
Lib/setup.py
def configuration(parent_package='',top_path=None): from numpy.distutils.misc_util import Configuration config = Configuration('scipy',parent_package,top_path) #config.add_subpackage('cluster') #config.add_subpackage('fftpack') #config.add_subpackage('integrate') #config.add_subpackage('interpo...
def configuration(parent_package='',top_path=None): from numpy.distutils.misc_util import Configuration config = Configuration('scipy',parent_package,top_path) config.add_subpackage('cluster') config.add_subpackage('fftpack') config.add_subpackage('integrate') config.add_subpackage('interpolate...
Fix problem with __all__ variable and update weave docs a bit. Update compiler_cxx too.
Fix problem with __all__ variable and update weave docs a bit. Update compiler_cxx too. git-svn-id: 003f22d385e25de9cff933a5ea4efd77cb5e7b28@2022 d6536bca-fef9-0310-8506-e4c0a848fbcf
Python
bsd-3-clause
lesserwhirls/scipy-cwt,scipy/scipy-svn,lesserwhirls/scipy-cwt,jasonmccampbell/scipy-refactor,scipy/scipy-svn,scipy/scipy-svn,jasonmccampbell/scipy-refactor,lesserwhirls/scipy-cwt,jasonmccampbell/scipy-refactor,scipy/scipy-svn,lesserwhirls/scipy-cwt,jasonmccampbell/scipy-refactor
1441654c46e08b7286999b6887e59c56fa238ff7
python/piling-up.py
python/piling-up.py
from collections import deque def isVerticallyStackable(pile): vertical_stack = [] while pile: largest_cube, cube_sizes = remove_largest_cube_from_pile(pile) if vertical_stack == []: vertical_stack.append(largest_cube) else: top_of_stack = vertical_stack[-1] ...
from collections import deque def isVerticallyStackable(pile): vertical_stack = [] while pile: largest_cube = remove_largest_cube_from_pile(pile) if vertical_stack == []: vertical_stack.append(largest_cube) else: top_of_stack = vertical_stack[-1] if(...
Remove returned pile b/c mutating directly
Remove returned pile b/c mutating directly
Python
mit
rootulp/hackerrank,rootulp/hackerrank,rootulp/hackerrank,rootulp/hackerrank,rootulp/hackerrank,rootulp/hackerrank
bb229be50e37bb710c32541cec7b159da9508335
tests/functional/subcommands/test_subcommands.py
tests/functional/subcommands/test_subcommands.py
import subprocess def test_subcommand(): """ Test that a command from the example project is registered. """ output = subprocess.check_output(['textx'], stderr=subprocess.STDOUT) assert b'testcommand' in output def test_subcommand_group(): """ Test that a command group is registered. ...
import sys import pytest import subprocess if (3, 6) <= sys.version_info < (3, 8): pytest.skip("Temporary workaround for Travis problems", allow_module_level=True) def test_subcommand(): """ Test that a command from the example project is registered. """ output = subprocess.check_output(['textx'...
Add workaround for Travis CI problems
Add workaround for Travis CI problems
Python
mit
igordejanovic/textX,igordejanovic/textX,igordejanovic/textX
b0e5dff69b9e40b916ad8a6655624de7fa85d247
chmvh_website/team/migrations/0002_auto_20161024_2338.py
chmvh_website/team/migrations/0002_auto_20161024_2338.py
# -*- coding: utf-8 -*- # Generated by Django 1.10.1 on 2016-10-24 23:38 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('team', '0001_initial'), ] operations = [ migrations.AlterModelOptions( ...
# -*- coding: utf-8 -*- # Generated by Django 1.10.1 on 2016-10-24 23:38 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('team', '0001_initial'), ] operations = [ migrations.AddField( m...
Change order of migration operations.
Change order of migration operations.
Python
mit
cdriehuys/chmvh-website,cdriehuys/chmvh-website,cdriehuys/chmvh-website
85fce5f5ab57b6c2144c92ec0d9b185740d7dc91
pyinform/__init__.py
pyinform/__init__.py
# Copyright 2016 ELIFE. All rights reserved. # Use of this source code is governed by a MIT # license that can be found in the LICENSE file. from ctypes import CDLL def get_libpath(): """ Get the library path of the the distributed inform binary. """ import os import re from os.path import dirn...
# Copyright 2016 ELIFE. All rights reserved. # Use of this source code is governed by a MIT # license that can be found in the LICENSE file. from ctypes import CDLL def get_libpath(): """ Get the library path of the the distributed inform binary. """ import os import re from os.path import dirn...
Resolve the library on windows
Resolve the library on windows
Python
mit
ELIFE-ASU/PyInform
4551732c93b248e669b63d8ea6a9705c52b69dc3
projects/urls.py
projects/urls.py
from django.conf.urls import patterns, url urlpatterns = patterns('projects.views', url(r'^add/$', 'add_project', name='add_project'), url(r'^edit/(?P<project_id>\d+)/$', 'edit_project', name='edit_project'), url(r'^status/(?P<project_id>\d+)/$', 'edit_status', name='edit_status'), url(r'^archive/$', ...
from django.conf.urls import patterns, url urlpatterns = patterns('projects.views', url(r'^add/$', 'add_project', name='add_project'), url(r'^edit/(?P<project_id>\d+)/$', 'edit_project', name='edit_project'), url(r'^edit_status/(?P<project_id>\d+)/$', 'edit_status', name='edit_status'), url(r'^status/...
Add url for project_status_edit option
Add url for project_status_edit option
Python
mit
Hackfmi/Diaphanum,Hackfmi/Diaphanum
1cc68fee10975f85ca5a2e2a63b972314a1b62d9
tests/test_redis_storage.py
tests/test_redis_storage.py
import unittest import datetime import hiro import redis from sifr.span import Minute, Day from sifr.storage import MemoryStorage, RedisStorage class RedisStorageTests(unittest.TestCase): def setUp(self): self.redis = redis.Redis() self.redis.flushall() def test_incr_simple_minute(self): ...
import unittest import datetime import hiro import redis from sifr.span import Minute, Day from sifr.storage import MemoryStorage, RedisStorage class RedisStorageTests(unittest.TestCase): def setUp(self): self.redis = redis.Redis() self.redis.flushall() def test_incr_simple_minute(self): ...
Remove old extra argument from track tests
Remove old extra argument from track tests
Python
mit
alisaifee/sifr,alisaifee/sifr
9f1783ac694d91b287dcb5840f54fb3df746a963
bot/action/core/action.py
bot/action/core/action.py
from bot.api.api import Api from bot.multithreading.scheduler import SchedulerApi from bot.storage import Config, State, Cache class Action: def __init__(self): pass def get_name(self): return self.__class__.__name__ def setup(self, api: Api, config: Config, state: State, cache: Cache, s...
from bot.api.api import Api from bot.multithreading.scheduler import SchedulerApi from bot.storage import Config, State, Cache class Action: def __init__(self): pass def get_name(self): return self.__class__.__name__ def setup(self, api: Api, config: Config, state: State, cache: Cache, s...
Add shutdown callback support to Action
Add shutdown callback support to Action
Python
agpl-3.0
alvarogzp/telegram-bot,alvarogzp/telegram-bot
2bcc941b015c443c64f08a13012e8caf70028754
ideascube/search/migrations/0001_initial.py
ideascube/search/migrations/0001_initial.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models import ideascube.search.models class Migration(migrations.Migration): dependencies = [ ] operations = [ migrations.CreateModel( name='Search', fields=[ ...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations from ideascube.search.utils import create_index_table class CreateSearchModel(migrations.CreateModel): def database_forwards(self, *_): # Don't run the parent method, we create the table our own way c...
Fix the initial search migration
Fix the initial search migration There is no point in creating the model in this way, that's just not how it's used: instead we want to use the FTS4 extension from SQLite.
Python
agpl-3.0
ideascube/ideascube,ideascube/ideascube,ideascube/ideascube,ideascube/ideascube
fc818ccd0d83ff6b37b38e5e9d03abcae408b503
froide/problem/templatetags/problemreport_tags.py
froide/problem/templatetags/problemreport_tags.py
from collections import defaultdict from django import template from ..models import ProblemReport from ..forms import ProblemReportForm register = template.Library() @register.inclusion_tag('problem/message_toolbar_item.html') def render_problem_button(message): if not hasattr(message, 'problemreports'): ...
from collections import defaultdict from django import template from ..models import ProblemReport from ..forms import ProblemReportForm register = template.Library() @register.inclusion_tag('problem/message_toolbar_item.html') def render_problem_button(message): if not hasattr(message, 'problemreports'): ...
Fix overriding variable in problem report tag
Fix overriding variable in problem report tag
Python
mit
stefanw/froide,stefanw/froide,stefanw/froide,fin/froide,fin/froide,stefanw/froide,stefanw/froide,fin/froide,fin/froide
af5eae0b477c73c1c8d1bbce646d94858d157142
whip/web.py
whip/web.py
#!/usr/bin/env python import socket from flask import Flask, abort, make_response, request from whip.db import Database app = Flask(__name__) app.config.from_envvar('WHIP_SETTINGS', silent=True) db = None @app.before_first_request def _open_db(): global db db = Database(app.config['DATABASE_DIR']) @ap...
#!/usr/bin/env python import socket from flask import Flask, abort, make_response, request from whip.db import Database app = Flask(__name__) app.config.from_envvar('WHIP_SETTINGS', silent=True) db = None @app.before_first_request def _open_db(): global db db = Database(app.config['DATABASE_DIR']) @ap...
Return empty responses (not HTTP 404) in REST API for missing data
Return empty responses (not HTTP 404) in REST API for missing data
Python
bsd-3-clause
wbolster/whip
a5b73a7ded0e277662308e0b4d38ac0429c404fb
django_facebook/models.py
django_facebook/models.py
from django.db import models class FacebookProfileModel(models.Model): ''' Abstract class to add to your profile model. NOTE: If you don't use this this abstract class, make sure you copy/paste the fields in. ''' about_me = models.TextField(blank=True, null=True) facebook_id = models.I...
from django.db import models from django.contrib.auth.models import User class FacebookProfileModel(models.Model): ''' Abstract class to add to your profile model. NOTE: If you don't use this this abstract class, make sure you copy/paste the fields in. ''' user = models.OneToOneField(User)...
Add reference to user model and __unicode__() method to FacebookProfileModel
Add reference to user model and __unicode__() method to FacebookProfileModel
Python
bsd-3-clause
pjdelport/Django-facebook,QLGu/Django-facebook,Shekharrajak/Django-facebook,VishvajitP/Django-facebook,troygrosfield/Django-facebook,QLGu/Django-facebook,cyrixhero/Django-facebook,rafaelgontijo/Django-facebook-fork,fyndsi/Django-facebook,jcpyun/Django-facebook,abendleiter/Django-facebook,danosaure/Django-facebook,cyrix...
3122736e0eccd4d4b1f003faa1db6ec05710883f
addstr.py
addstr.py
#!/usr/bin/python import argparse from dx.dex import Dex from sha1 import update_signature from adler32 import update_checksum def main(): parser = argparse.ArgumentParser(description="Parse and reconstruct dex file") parser.add_argument('target',help='Target DEX file') parser.add_argument('string',hel...
#!/usr/bin/python import argparse from dx.dex import Dex from dx.hash import update_signature, update_checksum def main(): parser = argparse.ArgumentParser(description="Parse and reconstruct dex file") parser.add_argument('target',help='Target DEX file') parser.add_argument('string',help='String to be ...
Fix attempted import from non-existent module.
Fix attempted import from non-existent module.
Python
bsd-3-clause
strazzere/dexterity,strazzere/dexterity,rchiossi/dexterity,strazzere/dexterity,rchiossi/dexterity,rchiossi/dexterity
edd50431f9c99bcbc765cc85786ead60ba8ba6e4
admin/base/migrations/0002_groups.py
admin/base/migrations/0002_groups.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations from django.contrib.auth.models import Group import logging logger = logging.getLogger(__file__) def add_groups(*args): group, created = Group.objects.get_or_create(name='nodes_and_users') if created: lo...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations from django.contrib.auth.models import Group import logging logger = logging.getLogger(__file__) def add_groups(*args): group, created = Group.objects.get_or_create(name='nodes_and_users') if created: lo...
Add reverse migration for new groups
Add reverse migration for new groups
Python
apache-2.0
brianjgeiger/osf.io,chennan47/osf.io,CenterForOpenScience/osf.io,sloria/osf.io,Johnetordoff/osf.io,leb2dg/osf.io,brianjgeiger/osf.io,monikagrabowska/osf.io,binoculars/osf.io,acshi/osf.io,chrisseto/osf.io,acshi/osf.io,crcresearch/osf.io,aaxelb/osf.io,erinspace/osf.io,brianjgeiger/osf.io,chrisseto/osf.io,erinspace/osf.io...
eef28c81f19d7e5eb72635cc2e6bf3b74331c743
quilt/patch.py
quilt/patch.py
# vim: fileencoding=utf-8 et sw=4 ts=4 tw=80: # python-quilt - A Python implementation of the quilt patch system # # Copyright (C) 2012 Björn Ricks <bjoern.ricks@googlemail.com> # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as ...
# vim: fileencoding=utf-8 et sw=4 ts=4 tw=80: # python-quilt - A Python implementation of the quilt patch system # # Copyright (C) 2012 Björn Ricks <bjoern.ricks@googlemail.com> # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as ...
Patch parameter --prefix does need a path seperator
Patch parameter --prefix does need a path seperator The --prefix parameter of the patch command needs a path seperator at the end to store the backup in a directory.
Python
mit
vadmium/python-quilt,bjoernricks/python-quilt
a37ac8daad8eee1f044d3e19a80a172138460ec3
google_analytics/models.py
google_analytics/models.py
from django.db import models from django.conf import settings from django.contrib.sites.admin import SiteAdmin from django.contrib.sites.models import Site from django.contrib import admin if getattr(settings, 'GOOGLE_ANALYTICS_MODEL', False): class Analytic(models.Model): site = models.ForeignKey(Site, u...
from django.contrib import admin from django.contrib.sites.models import Site from django.db import models class Analytic(models.Model): site = models.ForeignKey(Site, unique=True) analytics_code = models.CharField(blank=True, max_length=100)
Fix django version problem with new menu options in admin app.
Fix django version problem with new menu options in admin app.
Python
agpl-3.0
OSSystems/lava-server,Linaro/lava-server,Linaro/lava-server,Linaro/lava-server,OSSystems/lava-server,Linaro/lava-server,OSSystems/lava-server
2b99108a817a642c86be06a14ac8d71cdc339555
scripts/speak.py
scripts/speak.py
#!/usr/bin/env python import rospy from sound_play.msg import SoundRequest from sound_play.libsoundplay import SoundClient from std_msgs.msg import String class ChatbotSpeaker: def __init__(self): rospy.init_node('chatbot_speaker') self._client = SoundClient() rospy.Subscriber('chatbot_responses', Strin...
#!/usr/bin/env python import os import rospy from sound_play.msg import SoundRequest from sound_play.libsoundplay import SoundClient from std_msgs.msg import String import urllib tts_cmd = ( 'wget -q -U "Mozilla/5.0" -O - "http://translate.google.com/translate_tts?tl=en-uk&q={}" > /tmp/speech.mp3' ) sox_cmd = 'so...
Use Google Translate API to get a female TTS
Use Google Translate API to get a female TTS
Python
mit
jstnhuang/chatbot
11be4b77e84c721ef8de583b0dcf1035367d4b25
libtmux/__about__.py
libtmux/__about__.py
__title__ = 'libtmux' __package_name__ = 'libtmux' __version__ = '0.8.0' __description__ = 'scripting library / orm for tmux' __email__ = 'tony@git-pull.com' __author__ = 'Tony Narlock' __github__ = 'https://github.com/tmux-python/libtmux' __license__ = 'MIT' __copyright__ = 'Copyright 2016-2018 Tony Narlock'
__title__ = 'libtmux' __package_name__ = 'libtmux' __version__ = '0.8.0' __description__ = 'scripting library / orm for tmux' __email__ = 'tony@git-pull.com' __author__ = 'Tony Narlock' __github__ = 'https://github.com/tmux-python/libtmux' __pypi__ = 'https://pypi.python.org/pypi/libtmux' __license__ = 'MIT' __copyrigh...
Add __pypi__ url to metadata
Add __pypi__ url to metadata
Python
bsd-3-clause
tony/libtmux
f3fef8dab576ef5d7a4120a4041ade326868f0ca
flexget/plugins/ui/execute.py
flexget/plugins/ui/execute.py
import logging from flask import render_template, request, Response, redirect, flash from flask import Module, escape from flexget.webui import register_plugin, manager, BufferQueue from Queue import Empty from flask.helpers import jsonify execute = Module(__name__, url_prefix='/execute') log = logging.getLo...
import logging from flask import render_template, request, Response, redirect, flash from flask import Module, escape from flexget.webui import register_plugin, manager, BufferQueue from Queue import Empty from flask.helpers import jsonify execute = Module(__name__, url_prefix='/execute') log = logging.getLo...
Fix an issue with repeated messages in json execution output provider.
Fix an issue with repeated messages in json execution output provider. git-svn-id: 555d7295f8287ebc42f8316c6775e40d702c4756@1726 3942dd89-8c5d-46d7-aeed-044bccf3e60c
Python
mit
oxc/Flexget,tsnoam/Flexget,offbyone/Flexget,malkavi/Flexget,ibrahimkarahan/Flexget,ratoaq2/Flexget,asm0dey/Flexget,sean797/Flexget,OmgOhnoes/Flexget,ibrahimkarahan/Flexget,drwyrm/Flexget,jawilson/Flexget,thalamus/Flexget,tarzasai/Flexget,tvcsantos/Flexget,tarzasai/Flexget,Danfocus/Flexget,drwyrm/Flexget,xfouloux/Flexge...
9346b34c68fc08dfba0002e907d73829000068cd
labmanager/shell.py
labmanager/shell.py
import cmd class LMShell(cmd.Cmd): def __init__(self, lmapi, completekey='tab', stdin=None, stdout=None): cmd.Cmd.__init__(self, completekey, stdin, stdout) self._lmapi = lmapi def do_list(self, line): configs = self._lmapi.list_library_configurations() print configs def ...
import cmd class LMShell(cmd.Cmd): def __init__(self, lmapi, completekey='tab', stdin=None, stdout=None): cmd.Cmd.__init__(self, completekey, stdin, stdout) self._lmapi = lmapi def do_list(self, line): configs = self._lmapi.list_library_configurations() print configs def ...
Add 'quit' command to lmsh
Add 'quit' command to lmsh
Python
bsd-3-clause
jamesls/labmanager-shell
713fcc3f86b4be4d35f0c5ba081a4f786648320a
vim/pythonx/elixir_helpers.py
vim/pythonx/elixir_helpers.py
""" Elixir-related Ultisnips snippet helper functions. NOTE: Changes to this file require restarting Vim! """ import re _DASHES_AND_UNDERSCORES = re.compile("[-_]") _MODULE_FILEPATH = re.compile(r"lib\/([^\/]+)\/([\w+\/]+)*\/([^\/]+).ex") def closing_character(tabstop): """ Return closing character for a tabs...
""" Elixir-related Ultisnips snippet helper functions. NOTE: Changes to this file require restarting Vim! """ import re _DASHES_AND_UNDERSCORES = re.compile("[-_]") _MODULE_FILEPATH = re.compile(r"lib\/([^\/]+)\/([\w+\/]+)*\/([^\/]+).ex") _CLOSING_CHARACTERS = { "(": ")", "{": "}", "[": "]", "\"": "\""...
Refactor python if statement into dictionary
Refactor python if statement into dictionary
Python
mit
paulfioravanti/dotfiles,paulfioravanti/dotfiles,paulfioravanti/dotfiles
4e3f10cc417f28badc34646cc89fcd9d0307b4be
utility/lambdas/s3-static-site-deploy/lambda_function.py
utility/lambdas/s3-static-site-deploy/lambda_function.py
# import boto3 def lambda_handler(event, context): pass
# Invoked by: CloudFormation # Returns: A `Data` object to a pre-signed URL # # Deploys the contents of a versioned zip file object from one bucket in S3 # to a another bucket import sys import boto3 from botocore.client import Config import io import zipfile import os import urllib.request import json import tracebac...
Add S3 static deploy custom resource Lambda function
Add S3 static deploy custom resource Lambda function
Python
mit
PRX/Infrastructure,PRX/Infrastructure,PRX/Infrastructure,PRX/Infrastructure,PRX/Infrastructure
aed82bc0995cf4175c0ab8c521dfc8e89d776a7e
Mac/scripts/zappycfiles.py
Mac/scripts/zappycfiles.py
# Zap .pyc files import os import sys doit = 1 def main(): if os.name == 'mac': import macfs fss, ok = macfs.GetDirectory('Directory to zap pyc files in') if not ok: sys.exit(0) dir = fss.as_pathname() zappyc(dir) else: if not sys.argv[1:]: print 'Usage: zappyc dir ...' sys.exit(1) for dir in...
#!/usr/local/bin/python """Recursively zap all .pyc files""" import os import sys # set doit true to actually delete files # set doit false to just print what would be deleted doit = 1 def main(): if not sys.argv[1:]: if os.name == 'mac': import macfs fss, ok = macfs.GetDirectory('Directory to zap pyc files ...
Patch by Russel Owen: if we have command line arguments zap pyc files in the directories given.
Patch by Russel Owen: if we have command line arguments zap pyc files in the directories given.
Python
mit
sk-/python2.7-type-annotator,sk-/python2.7-type-annotator,sk-/python2.7-type-annotator
db04d6884c68b1f673a785866155427af86fad65
apps/predict/templatetags/jsonify.py
apps/predict/templatetags/jsonify.py
"""Add a template tag to turn python objects into JSON""" import types import json from django import template from django.utils.safestring import mark_safe register = template.Library() @register.filter def jsonify(obj): if isinstance(obj, types.GeneratorType): obj = list(obj) return mark_safe(json....
"""Add a template tag to turn python objects into JSON""" import types import json from django import template from django.utils.safestring import mark_safe register = template.Library() @register.filter def jsonify(obj): """Turn object into a json instance""" if isinstance(obj, types.GeneratorType): ...
Remove single quote marks from jsonif
Remove single quote marks from jsonif
Python
agpl-3.0
IQSS/gentb-site,IQSS/gentb-site,IQSS/gentb-site,IQSS/gentb-site,IQSS/gentb-site,IQSS/gentb-site,IQSS/gentb-site,IQSS/gentb-site
8ed2aa1a8108ae3a678ff18f4e8fda3539f4b603
avalonstar/components/games/admin.py
avalonstar/components/games/admin.py
# -*- coding: utf-8 -*- from django.contrib import admin from .models import Game, Platform class GameAdmin(admin.ModelAdmin): list_display = ['name', 'platform', 'gbid', 'is_abandoned', 'is_completed'] raw_id_fields = ['platform'] autocomplete_lookup_fields = { 'fk': ['platform'] } admin.site.register(...
# -*- coding: utf-8 -*- from django.contrib import admin from .models import Game, Platform class GameAdmin(admin.ModelAdmin): list_display = ['name', 'platform', 'gbid', 'is_abandoned', 'is_completed'] list_editable = ['is_abandoned', 'is_completed'] raw_id_fields = ['platform'] autocomplete_lookup...
Make the game booleans editable.
Make the game booleans editable.
Python
apache-2.0
bryanveloso/avalonstar-tv,bryanveloso/avalonstar-tv,bryanveloso/avalonstar-tv
12683ea64a875b624230f2dd84609a77eaec1095
cd_wizard.py
cd_wizard.py
#!/usr/bin/env python """Wizard to guide user to: - insert cd - please rip with eac - check for a good rip - upload with metadata (freedb, musicmind) """ from PyQt4 import QtGui def createIntroPage(): page = QtGui.QWizardPage() page.setTitle("Introduction") page.setSubTitle("This wizard will help y...
#!/usr/bin/env python """Wizard to guide user to: - insert cd - please rip with eac - check for a good rip - upload with metadata (freedb, musicmind) """ from PyQt4 import QtGui def createIntroPage(): page = QtGui.QWizardPage() page.setTitle("Introduction") page.setSubTitle("This wizard will help y...
Add file browser to choose a CD.
Add file browser to choose a CD.
Python
agpl-3.0
brewsterkahle/archivecd
e7cb5b0be49bc5e811809c56eb4ad3c0dc861cdf
examples/child_watcher.py
examples/child_watcher.py
import logging import random from tornado import gen from zoonado import exc log = logging.getLogger() def arguments(parser): parser.add_argument( "--path", "-p", type=str, default="/examplewatcher", help="ZNode path to use for the example." ) def watcher_callback(children): children.so...
import logging import random from tornado import gen from zoonado import exc log = logging.getLogger() def arguments(parser): parser.add_argument( "--path", "-p", type=str, default="/examplewatcher", help="ZNode path to use for the example." ) def watcher_callback(children): children.so...
Fix up to the child watcher example.
Fix up to the child watcher example. Without yielding to the ioloop after each call to client.delete() the child znodes would be deleted but that would never be reported.
Python
apache-2.0
wglass/zoonado
615e57fefa2b3b52ce351ef1d8039216927dc891
Parallel/Testing/Cxx/TestSockets.py
Parallel/Testing/Cxx/TestSockets.py
""" Driver script for testing sockets Unix only """ import os, sys, time # Fork, run server in child, client in parent pid = os.fork() if pid == 0: # exec the parent os.execv(sys.argv[1], ('-D', sys.argv[3])) else: # wait a little to make sure that the server is ready time.sleep(10) # run the c...
""" Driver script for testing sockets Unix only """ import os, sys, time # Fork, run server in child, client in parent pid = os.fork() if pid == 0: # exec the parent os.execv(sys.argv[1], ('-D', sys.argv[3])) else: # wait a little to make sure that the server is ready time.sleep(10) # run the c...
Fix space problem and put try around os.kill
ERR: Fix space problem and put try around os.kill
Python
bsd-3-clause
SimVascular/VTK,johnkit/vtk-dev,gram526/VTK,daviddoria/PointGraphsPhase1,sankhesh/VTK,hendradarwin/VTK,jeffbaumes/jeffbaumes-vtk,ashray/VTK-EVM,msmolens/VTK,SimVascular/VTK,arnaudgelas/VTK,gram526/VTK,berendkleinhaneveld/VTK,johnkit/vtk-dev,Wuteyan/VTK,aashish24/VTK-old,mspark93/VTK,hendradarwin/VTK,collects/VTK,collec...
e8d57ef08616b06e5f94da7e01ba96c13b9124d7
perfrunner/celeryremote.py
perfrunner/celeryremote.py
BROKER_URL = 'amqp://couchbase:couchbase@172.23.97.73:5672/broker' CELERY_RESULT_BACKEND = 'amqp' CELERY_RESULT_EXCHANGE = 'perf_results' CELERY_RESULT_PERSISTENT = False
BROKER_URL = 'amqp://couchbase:couchbase@172.23.97.73:5672/broker' CELERY_RESULT_BACKEND = 'amqp' CELERY_RESULT_EXCHANGE = 'perf_results' CELERY_RESULT_PERSISTENT = False CELERYD_HIJACK_ROOT_LOGGER = False
Disable hijacking of previously configured log handlers
Disable hijacking of previously configured log handlers See also: http://docs.celeryproject.org/en/3.1/configuration.html#celeryd-hijack-root-logger Change-Id: Ibf4618e8bfeb28f877db4a40b4a911ff00442cc9 Reviewed-on: http://review.couchbase.org/82543 Tested-by: Build Bot <80754af91bfb6d1073585b046fe0a474ce868509@couch...
Python
apache-2.0
couchbase/perfrunner,pavel-paulau/perfrunner,couchbase/perfrunner,pavel-paulau/perfrunner,couchbase/perfrunner,couchbase/perfrunner,pavel-paulau/perfrunner,couchbase/perfrunner,pavel-paulau/perfrunner,pavel-paulau/perfrunner,couchbase/perfrunner
dc883b81a2c5714d9401fb113101639e13e396f5
integration_tests/tests/hello_world_sleep_and_time.py
integration_tests/tests/hello_world_sleep_and_time.py
integration_test = True timeout = 2 SLEEP_INTERVAL = int(100e6) def check_state(state): import re from functools import partial from operator import is_not r = re.compile('^(\d+) \[.*\] Hello World!') lines = map(r.match, state.console.split('\n')) lines = filter(partial(is_not, None), lines...
integration_test = True timeout = 2 SLEEP_INTERVAL = int(100e6) MIN_TIME = 1451606400000000000 # 2016-1-1 0:0:0.0 UTC def check_state(state): import re from functools import partial from operator import is_not r = re.compile('^(\d+) \[.*\] Hello World!') lines = map(r.match, state.console.split(...
Make sure current date is late enough
Make sure current date is late enough
Python
bsd-2-clause
unigornel/unigornel,unigornel/unigornel
f3fb5bd0dbb3e19e58558af015aaee5ec120af71
portal/template_helpers.py
portal/template_helpers.py
""" Module for helper functions used inside jinja2 templates """ # NB, each blueprint must individually load any functions defined below # for them to appear in the namespace when invoked from respective blueprint # See @<blueprint>.context_processor decorator for more info. def split_string(s, delimiter=','): re...
""" Module for helper functions used inside jinja2 templates """ # NB, each blueprint must individually load any functions defined below # for them to appear in the namespace when invoked from respective blueprint # See @<blueprint>.context_processor decorator for more info. def split_string(s, delimiter=','): ""...
Allow for list/tuples in config files when looking for comma delimited strings.
Allow for list/tuples in config files when looking for comma delimited strings.
Python
bsd-3-clause
uwcirg/true_nth_usa_portal,uwcirg/true_nth_usa_portal,uwcirg/true_nth_usa_portal,uwcirg/true_nth_usa_portal
674f6e0b9fbb76684a9b05d16a5da0d4cc732b1d
scripts/analysis/plot_tracking_vector_estimator_stats.py
scripts/analysis/plot_tracking_vector_estimator_stats.py
#!/usr/bin/env python2 import numpy as np import matplotlib.pyplot as plt import argparse import sys import os parser = argparse.ArgumentParser( prog='plot_tracking_vector_estimator') parser.add_argument('directory', type=str, help='Data directory') args = parser.parse_args() data = np.genfromtxt( os.path.join...
#!/usr/bin/env python2 import numpy as np import matplotlib.pyplot as plt import argparse import sys import os parser = argparse.ArgumentParser( prog='plot_tracking_vector_estimator') parser.add_argument('directory', type=str, help='Data directory') args = parser.parse_args() data = np.genfromtxt( os.path.join...
Change estimator script based on modifications to estimator
Change estimator script based on modifications to estimator
Python
mpl-2.0
jhu-asco/aerial_autonomy,jhu-asco/aerial_autonomy,jhu-asco/aerial_autonomy,jhu-asco/aerial_autonomy,jhu-asco/aerial_autonomy,jhu-asco/aerial_autonomy
a0aa74d9e6295e34f02b4eefd76e7eb9a1e6425f
node/floor_divide.py
node/floor_divide.py
#!/usr/bin/env python from nodes import Node class FloorDiv(Node): char = "f" args = 2 results = 1 @Node.test_func([3,2], [1]) @Node.test_func([6,-3], [-2]) def func(self, a:Node.number,b:Node.number): """a/b. Rounds down, returns an int.""" return a//b @Node.test...
#!/usr/bin/env python from nodes import Node class FloorDiv(Node): char = "f" args = 2 results = 1 @Node.test_func([3,2], [1]) @Node.test_func([6,-3], [-2]) def func(self, a:Node.number,b:Node.number): """a/b. Rounds down, returns an int.""" return a//b @Node.test...
Add a group chunk, chunks a list into N groups
Add a group chunk, chunks a list into N groups
Python
mit
muddyfish/PYKE,muddyfish/PYKE
9361af556cfa7f4fb6bb3c53b4e74e2c115cd7d7
annict/client.py
annict/client.py
# -*- coding: utf-8 -*- from operator import methodcaller import requests from furl import furl class Client(object): def __init__(self, access_token, base_url='https://api.annict.com', api_version='v1'): self.access_token = access_token self.base_url = base_url self.api_version = api_ve...
# -*- coding: utf-8 -*- from operator import methodcaller import requests from furl import furl class Client(object): def __init__(self, access_token, base_url='https://api.annict.com', api_version='v1'): self.access_token = access_token self.base_url = base_url self.api_version = api_ve...
Fix Client returns requests's response.
Fix Client returns requests's response.
Python
mit
kk6/python-annict
dffbc7d79c67c3629f718c7a0330f9922499640d
examples/translations/portuguese_test_1.py
examples/translations/portuguese_test_1.py
# Portuguese Language Test - Python 3 Only! from seleniumbase.translate.portuguese import CasoDeTeste class MinhaClasseDeTeste(CasoDeTeste): def test_exemplo_1(self): self.abrir_url("https://pt.wikipedia.org/wiki/") self.verificar_texto("Wikipédia") self.verificar_elemento('[title="Visita...
# Portuguese Language Test - Python 3 Only! from seleniumbase.translate.portuguese import CasoDeTeste class MinhaClasseDeTeste(CasoDeTeste): def test_exemplo_1(self): self.abrir_url("https://pt.wikipedia.org/wiki/") self.verificar_texto("Wikipédia") self.verificar_elemento('[title="Língua...
Update the Portuguese example test
Update the Portuguese example test
Python
mit
mdmintz/SeleniumBase,seleniumbase/SeleniumBase,seleniumbase/SeleniumBase,mdmintz/SeleniumBase,seleniumbase/SeleniumBase,mdmintz/SeleniumBase,seleniumbase/SeleniumBase,mdmintz/SeleniumBase
135c84189720aa2b7c07e516c782f7fab7b4d8fe
astropy/units/format/base.py
astropy/units/format/base.py
# Licensed under a 3-clause BSD style license - see LICENSE.rst class _FormatterMeta(type): registry = {} def __new__(mcls, name, bases, members): if 'name' in members: formatter_name = members['name'].lower() else: formatter_name = members['name'] = name.lower() ...
# Licensed under a 3-clause BSD style license - see LICENSE.rst class Base: """ The abstract base class of all unit formats. """ registry = {} def __new__(cls, *args, **kwargs): # This __new__ is to make it clear that there is no reason to # instantiate a Formatter--if you try to y...
Remove use of metaclass for unit formats
Remove use of metaclass for unit formats
Python
bsd-3-clause
astropy/astropy,saimn/astropy,mhvk/astropy,lpsinger/astropy,saimn/astropy,lpsinger/astropy,mhvk/astropy,pllim/astropy,astropy/astropy,lpsinger/astropy,saimn/astropy,aleksandr-bakanov/astropy,pllim/astropy,astropy/astropy,pllim/astropy,lpsinger/astropy,larrybradley/astropy,mhvk/astropy,pllim/astropy,StuartLittlefair/ast...
52ef9217f954617283be54c889a317b2432651d7
licensing/models.py
licensing/models.py
from django.db import models class License(models.Model): name = models.CharField(max_length=80, unique=True) symbols = models.CharField(max_length=5) url = models.URLField(unique=True) def __unicode__(self): return self.name def get_absolute_url(self): return self.url class Lic...
from django.db import models class License(models.Model): name = models.CharField(max_length=80, unique=True) symbols = models.CharField(max_length=5) url = models.URLField(unique=True) def __unicode__(self): return self.name def __str__(self): return self.name def get_absol...
Add __str__() method to license model
Add __str__() method to license model __unicode__() is not used in python3
Python
unlicense
editorsnotes/django-licensing,editorsnotes/django-licensing
49d831a61c5770d02609ff2df8fed3effc3869c2
avalonstar/components/games/admin.py
avalonstar/components/games/admin.py
# -*- coding: utf-8 -*- from django.contrib import admin from .models import Game, Platform class GameAdmin(admin.ModelAdmin): list_display = ['name', 'platform', 'gbid'] raw_id_fields = ['platform'] autocomplete_lookup_fields = { 'fk': ['platform'] } admin.site.register(Game, GameAdmin) class Platfor...
# -*- coding: utf-8 -*- from django.contrib import admin from .models import Game, Platform class GameAdmin(admin.ModelAdmin): list_display = ['name', 'platform', 'gbid', 'is_abandoned', 'is_completed'] raw_id_fields = ['platform'] autocomplete_lookup_fields = { 'fk': ['platform'] } admin.site.register(...
Add booleans in for games.
Add booleans in for games.
Python
apache-2.0
bryanveloso/avalonstar-tv,bryanveloso/avalonstar-tv,bryanveloso/avalonstar-tv
0e766eb66eba099071b6cfae49bf79492e29e648
ibmcnx/doc/DataSources.py
ibmcnx/doc/DataSources.py
###### # Check ExId (GUID) by Email through JDBC # # Author: Christoph Stoettner # Mail: christoph.stoettner@stoeps.de # Documentation: http://scripting101.stoeps.de # # Version: 2.0 # Date: 2014-06-04 # # License: Apache 2.0 # # Check ExId of a User in all Connections Appli...
###### # Check ExId (GUID) by Email through JDBC # # Author: Christoph Stoettner # Mail: christoph.stoettner@stoeps.de # Documentation: http://scripting101.stoeps.de # # Version: 2.0 # Date: 2014-06-04 # # License: Apache 2.0 # # Check ExId of a User in all Connections Appli...
Create documentation of DataSource Settings
8: Create documentation of DataSource Settings Task-Url: http://github.com/stoeps13/ibmcnx2/issues/issue/8
Python
apache-2.0
stoeps13/ibmcnx2,stoeps13/ibmcnx2
aecff9764ef8d18b7016a6acba41e74a43e66085
clio/utils.py
clio/utils.py
import json from bson import json_util from flask.wrappers import Request, cached_property def getBoolean(string): return { '1': True, 'yes': True, 'true': True, 'on': True, '0': False, 'no': False, 'false': False, 'off': False, '': False, None: False }[string.lower()] class ExtRequest(Requ...
import json from bson import json_util from flask.wrappers import Request, cached_property def getBoolean(string): if string is None: return False return { '1': True, 'yes': True, 'true': True, 'on': True, '0': False, 'no': False, 'false': False, 'off': False, '': False, None: False ...
Add support to getBoolean function for None objects.
Add support to getBoolean function for None objects.
Python
apache-2.0
geodelic/clio,geodelic/clio
58d73429952a942d03b232242424946895ec3e8c
multi_schema/middleware.py
multi_schema/middleware.py
""" Middleware to automatically set the schema (namespace). if request.user.is_superuser, then look for a ?schema=XXX and set the schema to that. Otherwise, set the schema to the one associated with the logged in user. """ from models import Schema class SchemaMiddleware: def process_request(self, request): ...
""" Middleware to automatically set the schema (namespace). if request.user.is_superuser, then look for a ?schema=XXX and set the schema to that. Otherwise, set the schema to the one associated with the logged in user. """ from django.core.exceptions import ObjectDoesNotExist from models import Schema class Schem...
Add some data into the request context. Better handling of missing Schema objects when logging in (should we raise an error?).
Add some data into the request context. Better handling of missing Schema objects when logging in (should we raise an error?).
Python
bsd-3-clause
schinckel/django-boardinghouse,schinckel/django-boardinghouse,schinckel/django-boardinghouse
b98e86ad9b3120dce9f163236b5e28f564547c27
TWLight/resources/factories.py
TWLight/resources/factories.py
# -*- coding: utf-8 -*- import factory import random from django.conf import settings from TWLight.resources.models import Partner, Stream, Video, Suggestion class PartnerFactory(factory.django.DjangoModelFactory): class Meta: model = Partner strategy = factory.CREATE_STRATEGY company_name =...
# -*- coding: utf-8 -*- import factory import random from django.conf import settings from TWLight.resources.models import Partner, Stream, Video, Suggestion class PartnerFactory(factory.django.DjangoModelFactory): class Meta: model = Partner strategy = factory.CREATE_STRATEGY company_name =...
Change suggested_company_name factory var to pystr
Change suggested_company_name factory var to pystr
Python
mit
WikipediaLibrary/TWLight,WikipediaLibrary/TWLight,WikipediaLibrary/TWLight,WikipediaLibrary/TWLight,WikipediaLibrary/TWLight
bf5307afe52415960d0ffc794f687b0ecebb48da
app/__init__.py
app/__init__.py
from flask import Flask from flask.ext.login import login_user, logout_user, current_user, login_required, LoginManager from flask.ext.sqlalchemy import SQLAlchemy from flask import Flask, session from flask.ext.session import Session from flask.ext.mail import Mail app = Flask(__name__) # Configuration file reading ...
from flask import Flask from flask.ext.login import login_user, logout_user, current_user, login_required, LoginManager from flask.ext.sqlalchemy import SQLAlchemy from flask import Flask, session from flask.ext.session import Session from flask.ext.mail import Mail import logging from logging.handlers import RotatingF...
Enable file logging for the application.
Enable file logging for the application.
Python
mit
ptitoliv/cineapp,ptitoliv/cineapp,ptitoliv/cineapp
04328bb0ed84180aa9e5ce7f749eafb1ab96d4fc
app/api/auth.py
app/api/auth.py
from urllib import urlencode from datetime import datetime from django.http import HttpResponseForbidden from django.contrib.auth.models import AnonymousUser from django.utils.timezone import now from api.models import AuthAPIKey, AuthAPILog class APIKeyAuthentication(object): """ Validats a request by API key ...
from urllib import urlencode from datetime import datetime from django.http import HttpResponseForbidden from django.contrib.auth.models import AnonymousUser from django.utils.timezone import now from api.models import AuthAPIKey, AuthAPILog class APIKeyAuthentication(object): """ Validats a request by API key ...
Use create instead of instance and save
Use create instead of instance and save
Python
bsd-3-clause
nikdoof/test-auth
6091fccc90bb6b90c47a2e4fb7ee6821876eb1a1
synthnotes/generators/lengthgenerator.py
synthnotes/generators/lengthgenerator.py
from pkg_resources import resource_filename import pandas as pd import numpy as np class LengthGenerator(object): def __init__(self, length_file=resource_filename(__name__, 'resources/note_lengths.csv')): # print(length_file) df = pd...
from pkg_resources import resource_filename import pandas as pd import numpy as np class LengthGenerator(object): def __init__(self, length_file=resource_filename('synthnotes.resources', 'note_lengths.csv')): # print(length_file) df ...
Change LengthGenerator to get appropriate file path
Change LengthGenerator to get appropriate file path
Python
mit
ebegoli/SynthNotes
fc7cadecb95fa798a8e8aaeb544ad5464f13a533
nanomon/registry.py
nanomon/registry.py
from weakref import WeakValueDictionary class DuplicateEntryError(Exception): def __init__(self, name, obj, registry): self.name = name self.obj = obj self.registry = registry def __str__(self): return "Duplicate entry in '%s' registry for '%s'." % ( self.regist...
from weakref import WeakValueDictionary class DuplicateEntryError(Exception): def __init__(self, name, obj, registry): self.name = name self.obj = obj self.registry = registry def __str__(self): return "Duplicate entry in '%s' registry for '%s'." % ( self.regist...
Clean up some commented out code
Clean up some commented out code
Python
bsd-2-clause
cloudtools/nymms
d9f03ad1c73cc18276666f28e9a9360c71139a0d
nib/plugins/time.py
nib/plugins/time.py
import datetime import time from nib import jinja @jinja('time') def timeformat(t=None, f='%Y-%m-%d %I:%M %p'): if t is None: t = time.gmtime() elif isinstance(t, datetime.date) or isinstance(t, datetime.datetime): t = t.timetuple() elif isinstance(t, float): t = time.gmtime(t) ...
import datetime import time from nib import jinja @jinja('time') def timeformat(t=None, f='%Y-%m-%d %I:%M %p'): if t is None: t = time.gmtime() elif isinstance(t, datetime.date) or isinstance(t, datetime.datetime): t = t.timetuple() elif isinstance(t, float): t = time.gmtime(t) ...
Add 'longdate' filter for readable dates in templates
Add 'longdate' filter for readable dates in templates
Python
mit
jreese/nib
43a515ddfbe38686672fe00d4765d3f2e1bc5346
scarlet/assets/settings.py
scarlet/assets/settings.py
from django.conf import settings # Main Assets Directory. This will be a subdirectory within MEDIA_ROOT. # Set to None to use MEDIA_ROOT directly DIRECTORY = getattr(settings, "ASSETS_DIR", 'assets') # Which size should be used as CMS thumbnail for images. CMS_THUMBNAIL_SIZE = getattr(settings, 'ASSETS_CMS_THUMBNAIL...
from django.conf import settings # Main Assets Directory. This will be a subdirectory within MEDIA_ROOT. # Set to None to use MEDIA_ROOT directly DIRECTORY = getattr(settings, "ASSETS_DIR", 'assets') # Which size should be used as CMS thumbnail for images. CMS_THUMBNAIL_SIZE = getattr(settings, 'ASSETS_CMS_THUMBNAIL...
Set upscale to True by default for admin asset
Set upscale to True by default for admin asset
Python
mit
ff0000/scarlet,ff0000/scarlet,ff0000/scarlet,ff0000/scarlet,ff0000/scarlet
b57d5ecf56640c9d0a69b565006e2240662d6b46
profile_collection/startup/11-temperature-controller.py
profile_collection/startup/11-temperature-controller.py
from ophyd import PVPositioner, EpicsSignal, EpicsSignalRO from ophyd import Component as C from ophyd.device import DeviceStatus class CS700TemperatureController(PVPositioner): setpoint = C(EpicsSignal, 'T-SP') readback = C(EpicsSignalRO, 'T-I') done = C(EpicsSignalRO, 'Cmd-Busy') stop_signal = C(Epi...
from ophyd import PVPositioner, EpicsSignal, EpicsSignalRO from ophyd import Component as C from ophyd.device import DeviceStatus class CS700TemperatureController(PVPositioner): setpoint = C(EpicsSignal, 'T-SP') readback = C(EpicsSignalRO, 'T-I') done = C(EpicsSignalRO, 'Cmd-Busy') stop_signal = C(Epi...
Remove settle_time kwarg from c700
Remove settle_time kwarg from c700 This kwarg has been removed from ophyd, but will be coming back (and be functional) soon. Revert these changes when that happens: ophyd 0.2.1)
Python
bsd-2-clause
NSLS-II-XPD/ipython_ophyd,NSLS-II-XPD/ipython_ophyd
28627a41918be15037ba22e930a45d022e88388d
opps/articles/adminx.py
opps/articles/adminx.py
# -*- coding: utf-8 -*- #from django.contrib import admin from .models import Post, Album, Link from opps.contrib import admin admin.site.register(Post) admin.site.register(Album) admin.site.register(Link)
# -*- coding: utf-8 -*- from django.utils.translation import ugettext_lazy as _ from .models import Post, Album, Link from opps.containers.models import ContainerSource, ContainerImage from opps.contrib import admin from opps.contrib.admin.layout import * from xadmin.plugins.inline import Inline class ImageInline(ob...
Add Inline example on post model xadmin
Add Inline example on post model xadmin
Python
mit
jeanmask/opps,opps/opps,YACOWS/opps,williamroot/opps,opps/opps,jeanmask/opps,williamroot/opps,YACOWS/opps,opps/opps,williamroot/opps,jeanmask/opps,opps/opps,jeanmask/opps,williamroot/opps,YACOWS/opps,YACOWS/opps
e72c7fb4249895f2d6f4c9f36153786b75d5e8fa
chainer/functions/reshape.py
chainer/functions/reshape.py
import numpy from chainer import function from chainer.utils import type_check class Reshape(function.Function): type_check_prod = type_check.Variable(numpy.prod, 'prod') """Reshapes an input array without copy.""" def __init__(self, shape): self.shape = shape def check_type_forward(self, ...
import numpy from chainer import function from chainer.utils import type_check _type_check_prod = type_check.Variable(numpy.prod, 'prod') class Reshape(function.Function): """Reshapes an input array without copy.""" def __init__(self, shape): self.shape = shape def check_type_forward(self, i...
Move type_chack_prod module level variable and change its name to _type_check_prod
Move type_chack_prod module level variable and change its name to _type_check_prod
Python
mit
kikusu/chainer,niboshi/chainer,sou81821/chainer,elviswf/chainer,anaruse/chainer,okuta/chainer,okuta/chainer,AlpacaDB/chainer,tkerola/chainer,ktnyt/chainer,wkentaro/chainer,chainer/chainer,woodshop/complex-chainer,jfsantos/chainer,keisuke-umezawa/chainer,yanweifu/chainer,truongdq/chainer,niboshi/chainer,aonotas/chainer,...
737bf244f36b73a54b5b4f89f0c7e604d3f34b72
tests/grammar_term-nonterm_test/NonterminalGetTest.py
tests/grammar_term-nonterm_test/NonterminalGetTest.py
#!/usr/bin/env python """ :Author Patrik Valkovic :Created 23.06.2017 16:39 :Licence GNUv3 Part of grammpy """ from unittest import TestCase, main from grammpy import Grammar from grammpy import Nonterminal class TempClass(Nonterminal): pass class Second(Nonterminal): pass class Th...
#!/usr/bin/env python """ :Author Patrik Valkovic :Created 23.06.2017 16:39 :Licence GNUv3 Part of grammpy """ from unittest import TestCase, main from grammpy import Grammar from grammpy import Nonterminal class TempClass(Nonterminal): pass class Second(Nonterminal): pass class Th...
Add tests of get nonterms
Add tests of get nonterms
Python
mit
PatrikValkovic/grammpy
0b1702314fca978db1d0475ff3bc14977e7675a2
hxl_proxy/__init__.py
hxl_proxy/__init__.py
""" Top-level Flask application for HXL Proxy David Megginson January 2015 License: Public Domain Documentation: http://hxlstandard.org """ import os import requests_cache from flask import Flask, g, request from flask_cache import Cache import werkzeug.datastructures # Main application object app = Flask(__name__...
""" Top-level Flask application for HXL Proxy David Megginson January 2015 License: Public Domain Documentation: http://hxlstandard.org """ import os import requests_cache from flask import Flask, g, request from flask_cache import Cache import werkzeug.datastructures # Main application object app = Flask(__name__...
Add 1-hour expiry to requests_cache (formerly 5 minutes).
Add 1-hour expiry to requests_cache (formerly 5 minutes).
Python
unlicense
HXLStandard/hxl-proxy,HXLStandard/hxl-proxy,HXLStandard/hxl-proxy,HXLStandard/hxl-proxy
093b08f6bd03bd938ae7b7a18297708faa353766
django_lightweight_queue/middleware/transaction.py
django_lightweight_queue/middleware/transaction.py
from django.db import transaction, connection class TransactionMiddleware(object): def process_job(self, job): if not connection.in_atomic_block: transaction.set_autocommit(False) def process_result(self, job, result, duration): if not connection.in_atomic_block: transa...
from django.db import transaction, connection class TransactionMiddleware(object): def process_job(self, job): transaction.atomic(savepoint=False).__enter__() def process_result(self, job, result, duration): transaction.atomic(savepoint=False).__exit__(None, None, None) def process_except...
Use Django's Atomic decorator logic
Use Django's Atomic decorator logic We now keep Autocommit on it’s new default of True, as we only need the ability to rollback the contents of a queue job. By setting savepoint=False, the whole job will roll back if anything fails, rather than just up to the containing savepoint.
Python
bsd-3-clause
thread/django-lightweight-queue,thread/django-lightweight-queue,prophile/django-lightweight-queue,prophile/django-lightweight-queue
9eec7f7f39dc7e1af6e78e4be8d01b50626a4eb5
tests/acceptance/test_scoring.py
tests/acceptance/test_scoring.py
import shelve def test_shows_player_rating(browser, test_server, database_url): with shelve.open(database_url) as db: db.clear() db['p1'] = 1000 app = ScoringApp(browser, test_server) app.visit('/') app.shows('P1 1000') def test_user_adding(browser, test_server): app = ScoringAp...
import shelve from whatsmyrank.players import START_RANK from whatsmyrank.players import PlayerRepository def test_shows_player_rating(browser, test_server, database_url): player_repo = PlayerRepository(database_url, START_RANK) player_repo.create('p1') app = ScoringApp(browser, test_server) app.vis...
Remove database details from acceptance test
Remove database details from acceptance test
Python
bsd-2-clause
abele/whatsmyrank,abele/whatsmyrank
d436bcc20be8eb81960a53d442f699e42e2f9ea7
src/tkjoincsv.py
src/tkjoincsv.py
import tkFileDialog import joincsv import os.path import sys if __name__ == '__main__': filetypes=[("Spreadsheets", "*.csv"), ("Spreadsheets", "*.xls"), ("Spreadsheets", "*.xlsx")] if len(sys.argv) == 2: input_filename = sys.argv[1] else: input_filename =...
import tkFileDialog import joincsv import os.path import sys if __name__ == '__main__': filetypes=[("Spreadsheets", "*.csv"), ("Spreadsheets", "*.xls"), ("Spreadsheets", "*.xlsx")] if len(sys.argv) == 2: input_filename = sys.argv[1] else: input_filename =...
Allow saving to a file that does not already exist again.
Allow saving to a file that does not already exist again.
Python
apache-2.0
peterSW/corow
342d62a42bb4e1993bbe9d755e6daabcaffe4122
chdb.py
chdb.py
import sqlite3 DB_FILENAME = 'citationhunt.sqlite3' def init_db(): return sqlite3.connect(DB_FILENAME) def reset_db(): db = init_db() with db: db.execute(''' DROP TABLE categories ''') db.execute(''' DROP TABLE articles ''') db.execute(''' ...
import sqlite3 DB_FILENAME = 'citationhunt.sqlite3' def init_db(): return sqlite3.connect(DB_FILENAME) def reset_db(): db = init_db() with db: db.execute(''' DROP TABLE IF EXISTS categories ''') db.execute(''' DROP TABLE IF EXISTS articles ''') ...
Revert "Remove IF EXISTS from DROP TABLE when resetting the db."
Revert "Remove IF EXISTS from DROP TABLE when resetting the db." This reverts commit 271668a20a2262fe6211b9f61146ad90d8096486 [formerly a7dce25964cd740b0d0db86b255ede60c913e73d]. Former-commit-id: 08199327c411663a199ebf36379e88a514935399
Python
mit
eggpi/citationhunt,guilherme-pg/citationhunt,eggpi/citationhunt,eggpi/citationhunt,guilherme-pg/citationhunt,guilherme-pg/citationhunt,eggpi/citationhunt,guilherme-pg/citationhunt
8b3ca76b980f126912de1bc8ffa067c199693eb3
cinder/db/sqlalchemy/migrate_repo/versions/061_add_snapshot_id_timestamp_to_backups.py
cinder/db/sqlalchemy/migrate_repo/versions/061_add_snapshot_id_timestamp_to_backups.py
# Copyright (c) 2015 EMC Corporation # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless requi...
# Copyright (c) 2015 EMC Corporation # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless requi...
Fix race conditions in migration 061
Fix race conditions in migration 061 Migration 061 is supposed to add new `data_timestamp` field and populate it with value of `created_at` column. This was done by selecting all the backups and doing updates one-by-one. As it wasn't done in transaction solution was prone to race condition when a new backup is added w...
Python
apache-2.0
phenoxim/cinder,cloudbase/cinder,j-griffith/cinder,phenoxim/cinder,Nexenta/cinder,Datera/cinder,mahak/cinder,mahak/cinder,j-griffith/cinder,ge0rgi/cinder,Nexenta/cinder,openstack/cinder,cloudbase/cinder,eharney/cinder,eharney/cinder,Hybrid-Cloud/cinder,bswartz/cinder,NetApp/cinder,Hybrid-Cloud/cinder,Datera/cinder,open...
960ce03fc6d861c8df8d7aef5042f71c101794ca
pavement.py
pavement.py
# -*- coding: utf-8 -*- from paver.easy import * @task def test(options): info("Running tests for Python 2") sh('python2 tests.py') info("Running tests for Python 3") sh('python3 tests.py') @task def coverage(options): info("Running coverage for Python 2") sh('coverage2 run --source ldapom ./...
# -*- coding: utf-8 -*- from paver.easy import * @task def test(options): info("Running tests for Python 2") sh('python2 -m unittest -v tests') info("Running tests for Python 3") sh('python3 -m unittest -v tests') @task def coverage(options): info("Running coverage for Python 2") sh('coverage...
Make paver unittest run more verbose
Make paver unittest run more verbose
Python
mit
HaDiNet/ldapom
f69ea0232881c923e71bd2716fb6faa5d0d99491
yithlibraryserver/tests/test_views.py
yithlibraryserver/tests/test_views.py
# Yith Library Server is a password storage server. # Copyright (C) 2012 Yaco Sistemas # Copyright (C) 2012 Alejandro Blanco Escudero <alejandro.b.e@gmail.com> # Copyright (C) 2012 Lorenzo Gil Sanchez <lorenzo.gil.sanchez@gmail.com> # # This file is part of Yith Library Server. # # Yith Library Server is free software:...
# Yith Library Server is a password storage server. # Copyright (C) 2012 Yaco Sistemas # Copyright (C) 2012 Alejandro Blanco Escudero <alejandro.b.e@gmail.com> # Copyright (C) 2012 Lorenzo Gil Sanchez <lorenzo.gil.sanchez@gmail.com> # # This file is part of Yith Library Server. # # Yith Library Server is free software:...
Test the new tos view
Test the new tos view
Python
agpl-3.0
lorenzogil/yith-library-server,Yaco-Sistemas/yith-library-server,lorenzogil/yith-library-server,Yaco-Sistemas/yith-library-server,Yaco-Sistemas/yith-library-server,lorenzogil/yith-library-server
a3f1bd9b27bb605fe363a69a34a92862a1899da1
notifications/alliance_selections.py
notifications/alliance_selections.py
from consts.notification_type import NotificationType from helpers.model_to_dict import ModelToDict from notifications.base_notification import BaseNotification class AllianceSelectionNotification(BaseNotification): def __init__(self, event): self.event = event self._event_feed = event.key_name ...
from consts.notification_type import NotificationType from helpers.model_to_dict import ModelToDict from notifications.base_notification import BaseNotification class AllianceSelectionNotification(BaseNotification): def __init__(self, event): self.event = event self._event_feed = event.key_name ...
Add event name and key to alliance selection notifications
Add event name and key to alliance selection notifications This info is already included in 'event', but adding for consistency
Python
mit
jaredhasenklein/the-blue-alliance,synth3tk/the-blue-alliance,jaredhasenklein/the-blue-alliance,the-blue-alliance/the-blue-alliance,synth3tk/the-blue-alliance,bdaroz/the-blue-alliance,synth3tk/the-blue-alliance,tsteward/the-blue-alliance,jaredhasenklein/the-blue-alliance,jaredhasenklein/the-blue-alliance,the-blue-allian...
30a2a16aff030235941eac3786cc49b42e0ed868
bootstrap/conf/salt/state/run-tracking-db/scripts/import_sample_data.py
bootstrap/conf/salt/state/run-tracking-db/scripts/import_sample_data.py
import pandas as pd import sys df = pd.read_csv(sys.argv[1]) df.columns = [c.lower() for c in df.columns] from sqlalchemy import create_engine engine = create_engine('postgresql://localhost:5432/germline_genotype_tracking') try: df.to_sql("pcawg_samples", engine) except ValueError as e: if str(e) != "Table ...
import pandas as pd import sys df = pd.read_csv(sys.argv[1]) df.columns = [c.lower() for c in df.columns] from sqlalchemy import create_engine engine = create_engine('postgresql://localhost:5432/germline_genotype_tracking') try: df.to_sql("pcawg_samples", engine) except ValueError as e: if str(e) != "Table ...
Print an error message when table already exists without failing the script.
Print an error message when table already exists without failing the script.
Python
mit
llevar/germline-regenotyper,llevar/germline-regenotyper
6113b60187da1da42b26bee81556aad3efef57c4
nipype/interfaces/tests/test_afni.py
nipype/interfaces/tests/test_afni.py
from nipype.interfaces import afni from nose.tools import assert_equal def test_To3d(): cmd = afni.To3d() cmd._compile_command() yield assert_equal, cmd.cmdline, 'to3d' cmd = afni.To3d(anat=True) cmd._compile_command() yield assert_equal, cmd.cmdline, 'to3d -anat' cmd = afni.To3d() cm...
from nipype.interfaces import afni from nose.tools import assert_equal def test_To3d(): cmd = afni.To3d() cmd._compile_command() yield assert_equal, cmd.cmdline, 'to3d' cmd = afni.To3d(anat=True) cmd._compile_command() yield assert_equal, cmd.cmdline, 'to3d -anat' cmd = afni.To3d() cm...
Add tests to afni To3d.
Add tests to afni To3d. git-svn-id: 24f545668198cdd163a527378499f2123e59bf9f@165 ead46cd0-7350-4e37-8683-fc4c6f79bf00
Python
bsd-3-clause
rameshvs/nipype,grlee77/nipype,dmordom/nipype,glatard/nipype,fprados/nipype,rameshvs/nipype,wanderine/nipype,mick-d/nipype_source,dgellis90/nipype,sgiavasis/nipype,arokem/nipype,Leoniela/nipype,pearsonlab/nipype,pearsonlab/nipype,FCP-INDI/nipype,mick-d/nipype,satra/NiPypeold,gerddie/nipype,FredLoney/nipype,dgellis90/ni...
e2bac19e08197dc33756d7b7cf1f88e4ba808ae1
PyFVCOM/__init__.py
PyFVCOM/__init__.py
""" The FVCOM Python toolbox (PyFVCOM) """ __version__ = '1.4.1' __author__ = 'Pierre Cazenave' __credits__ = ['Pierre Cazenave'] __license__ = 'MIT' __maintainer__ = 'Pierre Cazenave' __email__ = 'pica@pml.ac.uk' import inspect from warnings import warn # Import everything! from PyFVCOM import buoy_tools from PyFV...
""" The FVCOM Python toolbox (PyFVCOM) """ __version__ = '1.4.1' __author__ = 'Pierre Cazenave' __credits__ = ['Pierre Cazenave'] __license__ = 'MIT' __maintainer__ = 'Pierre Cazenave' __email__ = 'pica@pml.ac.uk' import inspect from warnings import warn # Import everything! from PyFVCOM import buoy_tools from PyFV...
Add missing module to the project.
Add missing module to the project.
Python
mit
pwcazenave/PyFVCOM
bf1bafbbebeab86a213e4c4bed0be6f1b18404c6
python/grizzly/grizzly/lazy_op.py
python/grizzly/grizzly/lazy_op.py
"""Summary """ from weld.weldobject import * def to_weld_type(weld_type, dim): """Summary Args: weld_type (TYPE): Description dim (TYPE): Description Returns: TYPE: Description """ for i in xrange(dim): weld_type = WeldVec(weld_type) return weld_type class L...
"""Summary """ from weld.weldobject import * def to_weld_type(weld_type, dim): """Summary Args: weld_type (TYPE): Description dim (TYPE): Description Returns: TYPE: Description """ for i in xrange(dim): weld_type = WeldVec(weld_type) return weld_type class L...
Add passes to Grizzly's lazyOp
Add passes to Grizzly's lazyOp
Python
bsd-3-clause
rahulpalamuttam/weld,rahulpalamuttam/weld,weld-project/weld,sppalkia/weld,weld-project/weld,weld-project/weld,rahulpalamuttam/weld,weld-project/weld,sppalkia/weld,sppalkia/weld,sppalkia/weld,sppalkia/weld,weld-project/weld,rahulpalamuttam/weld,rahulpalamuttam/weld
d12907dd681c1d16c623b9dcceed9ff5e85c2ac6
views.py
views.py
from django.shortcuts import render def intro(request, template='intro.html'): response = render(request, template) response['X-Frame-Options'] = 'SAMEORIGIN' return response
from django.shortcuts import render from django.views.decorators.clickjacking import xframe_options_sameorigin @xframe_options_sameorigin def intro(request, template='intro.html'): response = render(request, template) return response
Use X-Frame-Options decorator to override middleware.
Use X-Frame-Options decorator to override middleware.
Python
bsd-3-clause
m8ttyB/pontoon-intro,mathjazz/pontoon-intro,mathjazz/pontoon-intro,Osmose/pontoon-intro,jotes/pontoon-intro,Osmose/pontoon-intro,jotes/pontoon-intro,m8ttyB/pontoon-intro,jotes/pontoon-intro,mathjazz/pontoon-intro,m8ttyB/pontoon-intro,Osmose/pontoon-intro
32a831d575b5354468a8f9c2a815f9f1aa03f2fb
api/caching/listeners.py
api/caching/listeners.py
from api.caching.tasks import ban_url from framework.tasks.handlers import enqueue_task from modularodm import signals @signals.save.connect def log_object_saved(sender, instance, fields_changed, cached_data): abs_url = None if hasattr(instance, 'absolute_api_v2_url'): abs_url = instance.absolute_api_v...
from functools import partial from api.caching.tasks import ban_url from framework.tasks.postcommit_handlers import enqueue_postcommit_task from modularodm import signals @signals.save.connect def log_object_saved(sender, instance, fields_changed, cached_data): abs_url = None if hasattr(instance, 'absolute_a...
Switch cache ban request to new postcommit synchronous method
Switch cache ban request to new postcommit synchronous method
Python
apache-2.0
kwierman/osf.io,amyshi188/osf.io,baylee-d/osf.io,felliott/osf.io,chrisseto/osf.io,amyshi188/osf.io,felliott/osf.io,samchrisinger/osf.io,cslzchen/osf.io,icereval/osf.io,cwisecarver/osf.io,sloria/osf.io,kwierman/osf.io,kch8qx/osf.io,asanfilippo7/osf.io,TomHeatwole/osf.io,DanielSBrown/osf.io,cslzchen/osf.io,CenterForOpenS...
90963666f22bea81d433724d232deaa0f3e2fec1
st2common/st2common/exceptions/db.py
st2common/st2common/exceptions/db.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...
# 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 a special exception for capturing object conflicts.
Add a special exception for capturing object conflicts.
Python
apache-2.0
jtopjian/st2,StackStorm/st2,StackStorm/st2,emedvedev/st2,dennybaa/st2,StackStorm/st2,alfasin/st2,pixelrebel/st2,nzlosh/st2,Itxaka/st2,StackStorm/st2,dennybaa/st2,punalpatel/st2,Plexxi/st2,lakshmi-kannan/st2,lakshmi-kannan/st2,grengojbo/st2,Itxaka/st2,jtopjian/st2,alfasin/st2,punalpatel/st2,peak6/st2,tonybaloney/st2,pin...
39b57462b69d78825fd217822d9be2f1eea5a06d
src/ansible/models.py
src/ansible/models.py
from django.db import models from django.conf import settings class Playbook(models.Model): name = models.CharField(max_length=200) inventory = models.CharField(max_length=200, default="hosts") user = models.CharField(max_length=200, default="ubuntu") directory = models.CharField(max_length=200, editab...
from django.db import models from django.conf import settings class Playbook(models.Model): name = models.CharField(max_length=200) inventory = models.CharField(max_length=200, default="hosts") user = models.CharField(max_length=200, default="ubuntu") directory = models.CharField(max_length=200, editab...
Set default value for Registry.playbook
Set default value for Registry.playbook
Python
bsd-3-clause
lozadaOmr/ansible-admin,lozadaOmr/ansible-admin,lozadaOmr/ansible-admin
c7512104dce2e9ca83e8400b399b4f77113f9368
packs/travisci/actions/lib/action.py
packs/travisci/actions/lib/action.py
import requests from st2actions.runners.pythonrunner import Action API_URL = 'https://api.travis-ci.org' HEADERS_ACCEPT = 'application/vnd.travis-ci.2+json' CONTENT_TYPE = 'application/json' class TravisCI(Action): def _get_auth_headers(self): headers = {} headers['Authorization'] = self.config[...
import httplib import requests from st2actions.runners.pythonrunner import Action API_URL = 'https://api.travis-ci.org' HEADERS_ACCEPT = 'application/vnd.travis-ci.2+json' CONTENT_TYPE = 'application/json' class TravisCI(Action): def _get_auth_headers(self): headers = {} headers['Authorization'...
Throw on invalid / missing credentials.
Throw on invalid / missing credentials.
Python
apache-2.0
pidah/st2contrib,lmEshoo/st2contrib,psychopenguin/st2contrib,psychopenguin/st2contrib,armab/st2contrib,StackStorm/st2contrib,tonybaloney/st2contrib,pidah/st2contrib,pearsontechnology/st2contrib,tonybaloney/st2contrib,StackStorm/st2contrib,pearsontechnology/st2contrib,pidah/st2contrib,armab/st2contrib,armab/st2contrib,S...
fa3ec9a764ca0d646588e908395367ce553981e1
tca/chat/views.py
tca/chat/views.py
from django.shortcuts import render from rest_framework import viewsets from chat.models import Member from chat.models import ChatRoom from chat.serializers import MemberSerializer from chat.serializers import ChatRoomSerializer class MemberViewSet(viewsets.ModelViewSet): model = Member serializer_class = ...
from django.shortcuts import render from django.shortcuts import get_object_or_404 from rest_framework import viewsets from rest_framework import status from rest_framework.decorators import action from rest_framework.response import Response from chat.models import Member from chat.models import ChatRoom from chat.s...
Add an action for adding members to a chat room
Add an action for adding members to a chat room Even though django-rest-framework supports a Ruby-on-Rails style of updating existing resources by issuing a PATCH or PUT request, such updates are unsafe and can cause race-conditions to lose some state. The implementation of this action isn't fully RESTful, but neither...
Python
bsd-3-clause
mlalic/TumCampusAppBackend,mlalic/TumCampusAppBackend
01e911926d37fa981fd7703f751ff91f052313e2
tkLibs/__init__.py
tkLibs/__init__.py
__all__ = ['autoScrollbar', 'button', 'combobox', 'listbox', 'window'] from .autoScrollbar import autoScrollbar from .button import button from .combobox import combobox from .listbox import listbox from .window import window
__all__ = ['autoScrollbar', 'button', 'combobox', 'entry', 'frame', 'label', 'listbox', 'toplevel', 'window'] from .autoScrollbar import autoScrollbar from .button import button from .combobox import combobox from .entry import entry from .frame import frame from .label import label from .listbox import listbox from ....
Add import of new widgets.
Add import of new widgets.
Python
mit
Kyle-Fagan/tkLibs
71cb7a3d83cbb352a358ba8ac260584a6666b5ad
seleniumbase/config/proxy_list.py
seleniumbase/config/proxy_list.py
""" Proxy Server "Phone Book". Simplify running browser tests through a proxy server by adding your frequently-used proxies here. Now you can do something like this on the command line: "pytest SOME_TEST.py --proxy=proxy1" Format of PROXY_LIST server entries: * "ip_address:port" OR "username:password@ip_address:po...
""" Proxy Server "Phone Book". Simplify running browser tests through a proxy server by adding your frequently-used proxies here. Now you can do something like this on the command line: "pytest SOME_TEST.py --proxy=proxy1" Format of PROXY_LIST server entries: * "ip_address:port" OR "username:password@ip_address:po...
Update the example proxy list
Update the example proxy list
Python
mit
seleniumbase/SeleniumBase,seleniumbase/SeleniumBase,seleniumbase/SeleniumBase,seleniumbase/SeleniumBase
1d88ea54d1f4ce63893b906a5b79faa4dd25243f
grow/commands/convert.py
grow/commands/convert.py
from grow.pods import pods from grow.pods import storage from grow.conversion import * import click import os @click.command() @click.argument('pod_path', default='.') @click.option('--type', type=click.Choice(['content_locale_split'])) def convert(pod_path, type): """Converts pod files from an earlier version of...
from grow.pods import pods from grow.pods import storage from grow.conversion import content_locale_split import click import os @click.command() @click.argument('pod_path', default='.') @click.option('--type', type=click.Choice(['content_locale_split'])) def convert(pod_path, type): """Converts pod files from an...
Adjust import to fix build with PyInstaller.
Adjust import to fix build with PyInstaller.
Python
mit
grow/pygrow,grow/pygrow,grow/pygrow,grow/grow,grow/grow,grow/grow,grow/grow
688bec4dc00dd1040901ca446c6b6cc7fa6fbbcb
downstream-farmer/utils.py
downstream-farmer/utils.py
#!/usr/bin/env python # -*- coding: utf-8 -*- try: from urllib import urlencode except ImportError: from urllib.parse import urlencode def urlencode(string): return urlencode(string)
#!/usr/bin/env python # -*- coding: utf-8 -*- try: from urllib import quote_plus except ImportError: from urllib.parse import quote_plus def urlify(string): """ You might be wondering: why is this here at all, since it's basically doing exactly what the quote_plus function in urllib does. Well, to k...
Add documentation and py3k compat
Add documentation and py3k compat
Python
mit
Storj/downstream-farmer
30e567adb809810930616493fd92ef1c40c9207b
dthm4kaiako/users/forms.py
dthm4kaiako/users/forms.py
"""Forms for user application.""" from django.forms import ModelForm from django.contrib.auth import get_user_model, forms User = get_user_model() class SignupForm(ModelForm): """Sign up for user registration.""" class Meta: """Metadata for SignupForm class.""" model = get_user_model() ...
"""Forms for user application.""" from django.forms import ModelForm from django.contrib.auth import get_user_model, forms from captcha.fields import ReCaptchaField from captcha.widgets import ReCaptchaV3 User = get_user_model() class SignupForm(ModelForm): """Sign up for user registration.""" captcha = Re...
Add recaptcha to signup page
Add recaptcha to signup page Signup page is currently not used, but doing it now in case it is forgotten later.
Python
mit
uccser/cs4teachers,uccser/cs4teachers,uccser/cs4teachers,uccser/cs4teachers
c0eb0f902b0fcbea29c8a3bf70f80ca9384cce9f
scripts/remove_after_use/send_mendeley_reauth_email.py
scripts/remove_after_use/send_mendeley_reauth_email.py
# -*- coding: utf-8 -*- import sys import logging from website.app import setup_django setup_django() from website import mails from osf.models import OSFUser from addons.mendeley.models import UserSettings import progressbar from scripts import utils as script_utils logger = logging.getLogger(__name__) def main(d...
# -*- coding: utf-8 -*- import sys import logging from website.app import setup_django setup_django() from website import mails from osf.models import OSFUser from addons.mendeley.models import UserSettings import progressbar from scripts import utils as script_utils logger = logging.getLogger(__name__) def main(d...
Remove junk and add more logging
Remove junk and add more logging
Python
apache-2.0
cslzchen/osf.io,icereval/osf.io,brianjgeiger/osf.io,mattclark/osf.io,pattisdr/osf.io,Johnetordoff/osf.io,baylee-d/osf.io,adlius/osf.io,cslzchen/osf.io,mattclark/osf.io,saradbowman/osf.io,brianjgeiger/osf.io,CenterForOpenScience/osf.io,adlius/osf.io,mfraezz/osf.io,brianjgeiger/osf.io,CenterForOpenScience/osf.io,baylee-d...