commit stringlengths 40 40 | subject stringlengths 4 1.73k | repos stringlengths 5 127k | old_file stringlengths 2 751 | new_file stringlengths 2 751 | new_contents stringlengths 1 8.98k | old_contents stringlengths 0 6.59k | license stringclasses 13
values | lang stringclasses 23
values |
|---|---|---|---|---|---|---|---|---|
107b89c29d7fb30024c7bc620121f5ba3fc2d47e | Improve the error message of exit_with_status | dmtucker/gjtk-py | gjtk/test/test_cli.py | gjtk/test/test_cli.py | # coding: utf-8
"""Tests for gjtk.cli"""
from __future__ import absolute_import
import os
import decorator
import gjtk.cli
def exit_with_status(comp=None):
"""
Expect a test to raise a SystemExit, optionally with a code that satisfies the given expression.
"""
def _decorator(test_func):
"... | # coding: utf-8
"""Tests for gjtk.cli"""
from __future__ import absolute_import
import os
import decorator
import gjtk.cli
def exit_with_status(expr=None):
"""
Expect a test to raise a SystemExit, optionally with a code that satisfies the given expression.
"""
def _decorator(test_func):
"... | lgpl-2.1 | Python |
e5d85ce9c2945567d2c37468a56370508806b26a | Fix batch_symeig cuda index issue | jrg365/gpytorch,jrg365/gpytorch,jrg365/gpytorch | gpytorch/utils/eig.py | gpytorch/utils/eig.py | #!/usr/bin/env python3
import torch
def batch_symeig(mat):
"""
"""
mat_orig = mat
dtkwargs = {"device": mat.device, "dtype": mat.dtype}
batch_shape = mat_orig.shape[:-2]
matrix_shape = mat_orig.shape[-2:]
# Smaller matrices are faster on the CPU than the GPU
if mat.size(-1) <= 32:
... | #!/usr/bin/env python3
import torch
def batch_symeig(mat):
"""
"""
mat_orig = mat
batch_shape = torch.Size(mat_orig.shape[:-2])
matrix_shape = torch.Size(mat_orig.shape[-2:])
# Smaller matrices are faster on the CPU than the GPU
if mat.size(-1) <= 32:
mat = mat.cpu()
mat = m... | mit | Python |
c3671786fead3cf8529bff78301bc870be342b00 | fix crash when no log | cielpy/build_ipa | filter_log.py | filter_log.py | #! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
# Copyright © 2017 ciel <ciel@cieldeMBP>
#
# Distributed under terms of the MIT license.
"""
filter git log
"""
from call_cmd import call, runPipe
import config
import time
import os
def filter_log(last_commit):
git_logs_cmd = '''git -C {} log --p... | #! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
# Copyright © 2017 ciel <ciel@cieldeMBP>
#
# Distributed under terms of the MIT license.
"""
filter git log
"""
from call_cmd import call, runPipe
import config
import time
import os
def filter_log(last_commit):
git_logs_cmd = '''git -C {} log --p... | mit | Python |
11eb0c45f825594a291d09f86541d6080ebcc5fc | Make sure getlist returns lists for JSON data | rackerlabs/graphite-api,michaelrice/graphite-api,brutasse/graphite-api,raintank/graphite-api,hubrick/graphite-api,cybem/graphite-api-iow,absalon-james/graphite-api,alphapigger/graphite-api,cybem/graphite-api-iow,GeorgeJahad/graphite-api,Knewton/graphite-api,winguru/graphite-api,tpeng/graphite-api,rackerlabs/graphite-ap... | graphite_api/utils.py | graphite_api/utils.py | """Copyright 2008 Orbitz WorldWide
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, softwa... | """Copyright 2008 Orbitz WorldWide
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, softwa... | apache-2.0 | Python |
b0db5267a3dd1d6edfaac9583e617532c4f0951b | Add GPIO.setmode line. (#59) | JeetShetty/GreenPiThumb,JeetShetty/GreenPiThumb | greenpithumb/pi_io.py | greenpithumb/pi_io.py | class IO(object):
"""Wrapper for input and output on a Raspberry Pi board.
This wraps the board and allows the caller to read or send signals to
the Raspberry Pi's pins. No more than one instance of this class should
exist at any given time.
"""
def __init__(self, gpio):
"""Creates a n... | #import RPi.GPIO as GPIO
class IO(object):
"""Wrapper for input and output on a Raspberry Pi board.
This wraps the board and allows the caller to read or send signals to
the Raspberry Pi's pins. No more than one instance of this class should
exist at any given time.
"""
def __init__(self, gp... | apache-2.0 | Python |
7c02e103a0af86016500625e20a4d7667e568265 | Add metadata to jsonify json input filename | Connexions/cte,Connexions/cnx-rulesets,Connexions/cnx-recipes,Connexions/cte,Connexions/cnx-rulesets,Connexions/cnx-recipes,Connexions/cnx-recipes,Connexions/cnx-recipes,Connexions/cnx-recipes,Connexions/cnx-rulesets,Connexions/cnx-rulesets | script/jsonify-book.py | script/jsonify-book.py | import sys
from glob import glob
from os.path import basename
import json
book_dir, out_dir = sys.argv[1:3]
files = [basename(x).rstrip(".xhtml") for x in glob(f"{book_dir}/*.xhtml")]
json_data = {}
for path in files:
with open(f"{book_dir}/{path}-metadata.json", "r") as meta_part:
json_data = json.load... | import sys
from glob import glob
from os.path import basename
import json
book_dir, out_dir = sys.argv[1:3]
files = [basename(x).rstrip(".xhtml") for x in glob(f"{book_dir}/*.xhtml")]
json_data = {}
for path in files:
with open(f"{book_dir}/{path}.json", "r") as meta_part:
json_data = json.load(meta_par... | lgpl-2.1 | Python |
e8c3e64048be876a97a618235720cdfecde87000 | Fix submission | sloria/wtfhack,sloria/wtfhack,sloria/wtfhack,sloria/wtfhack,sloria/wtfhack | wtfhack/base/urls.py | wtfhack/base/urls.py | """urlconf for the base application"""
from django.conf.urls.defaults import url, patterns
from wtfhack.base.views import *
urlpatterns = patterns('wtfhack.base.views',
url(r'^$', 'home', name='home'),
url(r'^submit/choose/$', 'submit', name='submit'),
# ex: language/scala/
url(r'^(?P<language>[\w\-\+]+... | """urlconf for the base application"""
from django.conf.urls.defaults import url, patterns
from wtfhack.base.views import *
urlpatterns = patterns('wtfhack.base.views',
url(r'^$', 'home', name='home'),
url(r'^submit/$', 'submit', name='submit'),
# ex: language/scala/
url(r'^(?P<language>[\w\-\+]+)/$', g... | bsd-3-clause | Python |
ada67f64c7eb6c1536b5173fd2d938cad5ee7d85 | DROP TABLE if they already exist | dubzzz/py-run-tracking,dubzzz/py-run-tracking,dubzzz/py-run-tracking | scripts/generate_db.py | scripts/generate_db.py | #!/usr/bin/python
# This script has to generate the sqlite database
#
# Requirements (import from):
# - sqlite3
#
# Syntax:
# ./generate_db.py
import sqlite3
DEFAULT_DB = "run-tracking.db"
def generate_tables(db=DEFAULT_DB):
conn = sqlite3.connect(db)
with conn:
c = conn.cursor()
... | #!/usr/bin/python
# This script has to generate the sqlite database
#
# Requirements (import from):
# - sqlite3
#
# Syntax:
# ./generate_db.py
import sqlite3
DEFAULT_DB = "run-tracking.db"
def generate_tables(db=DEFAULT_DB):
conn = sqlite3.connect(db)
with conn:
c = conn.cursor()
... | mit | Python |
0afa2bba5ef240bcfff2e4e454cf9f980b373aad | Add "3:14 every night." | juanrossi/abadbot | tweets.py | tweets.py | # -*- coding: utf-8 -*-
tweets = [
{'type': 'text', 'text': u'Un chirlo no es violencia'},
{'type': 'text', 'text': u'Are you watching closely?'},
{'type': 'text', 'text': u'Una novia que me traiga Mc a la cama'},
{'type': 'text', 'text': u'( •—• ) Tadashi is here'},
{'type': 'image', 'text': u'Mi f... | # -*- coding: utf-8 -*-
tweets = [
{'type': 'text', 'text': u'Un chirlo no es violencia'},
{'type': 'text', 'text': u'Are you watching closely?'},
{'type': 'text', 'text': u'Una novia que me traiga Mc a la cama'},
{'type': 'text', 'text': u'( •—• ) Tadashi is here'},
{'type': 'image', 'text': u'Mi f... | mit | Python |
c225366d592985721f951cb5612947ecfce69d24 | Fix path to demo | amperser/proselint,amperser/proselint,jstewmon/proselint,amperser/proselint,amperser/proselint,jstewmon/proselint,amperser/proselint,jstewmon/proselint | scripts/insert_demo.py | scripts/insert_demo.py | """Insert the demo into the codemirror site."""
import os
import fileinput
import shutil
proselint_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
code_mirror_path = os.path.join(
proselint_path,
"plugins",
"webeditor")
code_mirror_demo_path = os.path.join(code_mirror_path, "index.ht... | """Insert the demo into the codemirror site."""
import os
import fileinput
import shutil
proselint_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
code_mirror_path = os.path.join(
proselint_path,
"plugins",
"webeditor")
code_mirror_demo_path = os.path.join(code_mirror_path, "index.ht... | bsd-3-clause | Python |
5fa0629f1c16f59ca9df0b35be259d6bd9f641ce | refactor test_game_table | IanDCarroll/xox | tests/test_game_table.py | tests/test_game_table.py | import unittest
from source.game_table import *
class TableTopTestCase(unittest.TestCase):
def setUp(self):
self.table_top = TableTop()
self.empty_board = [0,0,0, 0,0,0, 0,0,0]
self.changed_board = [0,0,1, 0,0,0, 0,0,0]
def test_that_board_returns_a_list(self):
self.assertEq... | import unittest
from source.game_table import *
class TableTopTestCase(unittest.TestCase):
def setUp(self):
self.table_top = TableTop()
self.empty_board = [0,0,0, 0,0,0, 0,0,0]
self.changed_board = [0,0,1, 0,0,0, 0,0,0]
def test_that_board_returns_a_list(self):
test = isinst... | mit | Python |
bbdf6500313120501e93eded560d8fa8e88a0fe7 | update display functions | ACarfi/Regularization-networks | tests/KernelRegularizedLeastSquares.py | tests/KernelRegularizedLeastSquares.py | import os
import matplotlib as mpl
if os.environ.get('DISPLAY', '') == '':
print('no display found. Using non-interactive Agg backend')
mpl.use('Agg')
from regularizationNetworks.regularizedKernLSTrain import regularizedkernlstrain
from regularizationNetworks.separatingFKernRLS import separatingfkernrls
from re... | from regularizationNetworks.regularizedKernLSTrain import regularizedkernlstrain
from regularizationNetworks.separatingFKernRLS import separatingfkernrls
from regularizationNetworks.plotDataSet import plotdataset
from regularizationNetworks.flipLabels import fliplabels
from regularizationNetworks.two_moons import two_m... | mit | Python |
c95e028f6fdf991c8be9f77bf29bb786b91f3908 | Fix end of errors.py | wk-tech/python-smsfly | src/smsfly/errors.py | src/smsfly/errors.py | class XMLError(SyntaxError):
"""Incorrect XML was sent to API"""
pass
class PhoneError(ValueError):
"""Incorrect phone of recipient"""
pass
class StartTimeError(ValueError):
"""Incorrect start time for sending messages"""
pass
class EndTimeError(ValueError):
"""Incorrect end time of ca... | class XMLError(SyntaxError):
"""Incorrect XML was sent to API"""
pass
class PhoneError(ValueError):
"""Incorrect phone of recipient"""
pass
class StartTimeError(ValueError):
"""Incorrect start time for sending messages"""
pass
class EndTimeError(ValueError):
"""Incorrect end time of ca... | mit | Python |
887b4697b548598f57ba1245345786784e723b5a | Patch settings to enable SSL when running hilbert tests. Fixes #7. | mlavin/django-hilbert,mlavin/django-hilbert | hilbert/tests/base.py | hilbert/tests/base.py | """
Base test cases for Django-Hilbert.
"""
from django.conf import settings
from django.contrib.auth import models as auth
from hilbert.test import TestCase
class HilbertBaseTestCase(TestCase):
urls = 'hilbert.tests.urls'
username = 'hilbert'
password = 'test'
def setUp(self):
super(Hilber... | """
Base test cases for Django-Hilbert.
"""
from django.contrib.auth import models as auth
from hilbert.test import TestCase
class HilbertBaseTestCase(TestCase):
urls = 'hilbert.tests.urls'
username = 'hilbert'
password = 'test'
def create_user(self, data=None):
data = data or {}
de... | bsd-2-clause | Python |
363eda3124771cef83ae16ed802c2172f5a016d6 | Test case for writing external package references | spdx/tools-python | tests/test_rdf_writer.py | tests/test_rdf_writer.py | import os
import pytest
from rdflib import URIRef
from spdx.document import Document, License
from spdx.package import Package, ExternalPackageRef
from spdx.parsers.loggers import StandardLogger
from spdx.parsers.parse_anything import parse_file
from spdx.parsers.rdf import Parser
from spdx.parsers.rdfbuilders import... | import os
import pytest
from rdflib import URIRef
from spdx.document import Document
from spdx.package import Package
from spdx.parsers.loggers import StandardLogger
from spdx.parsers.rdf import Parser
from spdx.parsers.rdfbuilders import Builder
from spdx.utils import NoAssert
from spdx.writers.rdf import Writer
@... | apache-2.0 | Python |
0c3eec453a042eb2ef8b16914e898303f47aae9f | switch to x86_64 test_signed_div | axt/angr,tyb0807/angr,schieb/angr,iamahuman/angr,f-prettyland/angr,schieb/angr,chubbymaggie/angr,schieb/angr,angr/angr,chubbymaggie/angr,axt/angr,iamahuman/angr,angr/angr,tyb0807/angr,angr/angr,iamahuman/angr,chubbymaggie/angr,f-prettyland/angr,f-prettyland/angr,axt/angr,tyb0807/angr | tests/test_signed_div.py | tests/test_signed_div.py | import nose
import angr
import subprocess
import logging
l = logging.getLogger('angr.tests.test_signed_div')
import os
test_location = str(os.path.dirname(os.path.realpath(__file__)))
def run_signed_div():
test_bin = os.path.join(test_location, "../../binaries/tests/x86_64/test_signed_div")
b = angr.Project... | import nose
import angr
import subprocess
import logging
l = logging.getLogger('angr.tests.test_signed_div')
import os
test_location = str(os.path.dirname(os.path.realpath(__file__)))
def run_signed_div():
test_bin = os.path.join(test_location, "../../binaries/tests/i386/test_signed_div")
b = angr.Project(t... | bsd-2-clause | Python |
e88ccd53a12cd5674eb0dca5c5a144280eb725ed | make it possible to capture the disco#info query in a race-free way | mlundblad/telepathy-gabble,jku/telepathy-gabble,mlundblad/telepathy-gabble,Ziemin/telepathy-gabble,jku/telepathy-gabble,Ziemin/telepathy-gabble,Ziemin/telepathy-gabble,Ziemin/telepathy-gabble,jku/telepathy-gabble,mlundblad/telepathy-gabble | tests/twisted/mucutil.py | tests/twisted/mucutil.py | """
Utility functions for tests that need to interact with MUCs.
"""
import dbus
from servicetest import call_async, wrap_channel, EventPattern
from gabbletest import make_muc_presence, request_muc_handle
import constants as cs
import ns
def join_muc(q, bus, conn, stream, muc, request=None,
also_capture=[])... | """
Utility functions for tests that need to interact with MUCs.
"""
import dbus
from servicetest import call_async, wrap_channel
from gabbletest import make_muc_presence, request_muc_handle
import constants as cs
def join_muc(q, bus, conn, stream, muc, request=None):
"""
Joins 'muc', returning the muc's ha... | lgpl-2.1 | Python |
aea8f4ca51f331ba5da5381d38d3321690cebafb | add PYTHONPATH in cython. | cournape/Bento,cournape/Bento,abadger/Bento,cournape/Bento,cournape/Bento,abadger/Bento,abadger/Bento,abadger/Bento | yaku/tools/cython.py | yaku/tools/cython.py | import os
import sys
from yaku.task_manager \
import \
extension, get_extension_hook
from yaku.task \
import \
task_factory
from yaku.compiled_fun \
import \
compile_fun
from yaku.utils \
import \
ensure_dir, find_program
import yaku.errors
@extension(".pyx")
def cython... | import os
import sys
from yaku.task_manager \
import \
extension, get_extension_hook
from yaku.task \
import \
task_factory
from yaku.compiled_fun \
import \
compile_fun
from yaku.utils \
import \
ensure_dir, find_program
import yaku.errors
@extension(".pyx")
def cython... | bsd-3-clause | Python |
d7bf1217d8f2d3fc0549f9a2b1bb80af3b3b093a | Add enviroment variable db_host | jhbez/ProjectV,jhbez/ProjectV,jhbez/ProjectV | flaskapp.py | flaskapp.py | # -*- coding: utf-8 -*-
# © 2016. by Zero 1/0.
from flask import Flask, request, render_template, send_from_directory, g
from AoL.Utils.Db import PsqlAoL
from flask_restful import Api
from AoL.Auth.Auth import Auth
from AoL.Auth.User import User
from AoL.Habit.Habit import Habit, HabitList
from AoL.Habit.HabitHistory ... | # -*- coding: utf-8 -*-
# © 2016. by Zero 1/0.
from flask import Flask, request, render_template, send_from_directory, g
from AoL.Utils.Db import PsqlAoL
from flask_restful import Api
from AoL.Auth.Auth import Auth
from AoL.Auth.User import User
from AoL.Habit.Habit import Habit, HabitList
from AoL.Habit.HabitHistory ... | apache-2.0 | Python |
09002f8f2e23e2bdbc87d1cee04d7226b4c6ecac | remove old | raklove/hello-world | flaskapp.py | flaskapp.py | from flask import Flask
app = Flask(__name__)
from pymongo import MongoClient
connection = MongoClient()
@app.route("/")
def hello():
return connection.essa.users.find({}).next()['name']
@app.route('/halla/<username>')
def hi(username):
return "Halla " + username
@app.route('/add/<int:x>/<int:y>/'... | from flask import Flask
app = Flask(__name__)
from pymongo import MongoClient
connection = MongoClient()
@app.route("/")
def hello():
return connection.essa.users.find({}).next()['name']
def check():
return "new"
@app.route('/halla/<username>')
def hi(username):
return "Halla " + username
@app.rou... | apache-2.0 | Python |
cdc7e2dcdf650ccf3597ce646e1c665b3fa5383a | Make server accessible outside of start() | Metastruct/hal1320 | gamechat.py | gamechat.py | import socket
import threading
import SocketServer
from willie.module import commands
class ThreadedTCPRequestHandler(SocketServer.BaseRequestHandler):
def handle(self):
data = self.request.recv(1024)
cur_thread = threading.current_thread()
response = "{}: {}".format(cur_thread.name, data)... | import socket
import threading
import SocketServer
from willie.module import commands
class ThreadedTCPRequestHandler(SocketServer.BaseRequestHandler):
def handle(self):
data = self.request.recv(1024)
cur_thread = threading.current_thread()
response = "{}: {}".format(cur_thread.name, data)... | mit | Python |
c50d9231b75b01769e4ccd0571d28fe023cc3a6c | Update loading_test.py | aaron-parsons/repoNoData | tests/loading_test.py | tests/loading_test.py | '''
test to se if we can load the data at least
'''
import unittest
import tempfile
from . import image_operations as im
from . import test_utils as tu
class LoadingTest(unittest.TestCase):
def test_load_relativity(self):
out = im.LinearOperations(
tu.get_test_data_path("220px-Escher's_Relat... | '''
test to se if we can load the data at least
'''
import unittest
import tempfile
import image_operations as im
import test_utils as tu
class LoadingTest(unittest.TestCase):
def test_load_relativity(self):
out = im.LinearOperations(
tu.get_test_data_path("220px-Escher's_Relativity.jpg"))
... | apache-2.0 | Python |
9a33ac3f563ad657129d64cb591f08f9fd2a00a2 | Add command test for '--version' option | ma8ma/yanico | tests/test_command.py | tests/test_command.py | """Unittest of command entry point."""
# Copyright 2015 Masayuki Yamamoto
#
# 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 r... | """Unittest of command entry point."""
# Copyright 2015 Masayuki Yamamoto
#
# 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 r... | apache-2.0 | Python |
c266939b0bbd2da77bb523874baa60247d80a02f | Reorganize unit tests | riggsd/davies | tests/test_compass.py | tests/test_compass.py |
import unittest
import datetime
from davies import compass
# Example Compass Project with:
# - NAD83 UTM Zone 13 base location
# - Two imported Data Files
# - One with 25 cave surveys, four fixed stations
# - One with 4 surface surveys
TESTFILE = 'tests/data/compass/FULFORDS.MAK'
class CompassParsingTestCase(... |
import unittest
import datetime
from davies import compass
# Example Compass Project with:
# - NAD83 UTM Zone 13 base location
# - Two imported Data Files
# - One with 25 cave surveys, four fixed stations
# - One with 4 surface surveys
TESTFILE = 'tests/data/compass/FULFORDS.MAK'
class CompassParsingTestCase(... | mit | Python |
80296556935801ca46e4396eea5083d9a500ba4a | Remove unused trajectory change atoms name methods. | kbsezginel/tee_mof,kbsezginel/tee_mof | thermof/trajectory/io.py | thermof/trajectory/io.py | # Date: August 2017
# Author: Kutay B. Sezginel
"""
Read, write Lammps trajectory in xyz format.
"""
import os
def read_trajectory(traj_path):
""" Read xyz trajectory and return coordinates as a list """
with open(traj_path, 'r') as t:
traj = t.readlines()
n_atoms = int(traj[0].strip()) ... | # Date: August 2017
# Author: Kutay B. Sezginel
"""
Read, write Lammps trajectory in xyz format.
"""
import os
def read_trajectory(traj_path):
""" Read xyz trajectory and return coordinates as a list """
with open(traj_path, 'r') as t:
traj = t.readlines()
n_atoms = int(traj[0].strip()) ... | mit | Python |
6e3d3e8d8b985382d5e7120b4fa62bf0201eba67 | Update test | mikalyoung/recurrent-entity-networks,mikalyoung/recurrent-entity-networks,jimfleming/recurrent-entity-networks,jimfleming/recurrent-entity-networks | tests/test_dataset.py | tests/test_dataset.py | from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
import json
import tensorflow as tf
from entity_networks.dataset import Dataset
class DatasetTest(tf.test.TestCase):
def test_dataset(self):
with self.test_session() as sess:
dataset ... | from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
import json
import tensorflow as tf
from entity_networks.dataset import Dataset
class DatasetTest(tf.test.TestCase):
def test_dataset(self):
with self.test_session() as sess:
dataset ... | mit | Python |
9d23940c430a4f95ec11b33362141ec2ffc3f533 | Add is_editable and done_editable functions to Entry | fajran/tempel | src/tempel/models.py | src/tempel/models.py | from datetime import datetime, timedelta
from django.db import models
from django.conf import settings
from tempel import utils
def default_edit_expires():
return datetime.now() + timedelta(seconds=60*settings.TEMPEL_EDIT_AGE)
class Entry(models.Model):
content = models.TextField()
language = models.Cha... | from datetime import datetime, timedelta
from django.db import models
from django.conf import settings
from tempel import utils
def default_edit_expires():
return datetime.now() + timedelta(seconds=60*settings.TEMPEL_EDIT_AGE)
class Entry(models.Model):
content = models.TextField()
language = models.Cha... | agpl-3.0 | Python |
778923fab86d423b6ed254c569fddee1b9650f56 | Add tests for upload_to_pypi | relekang/python-semantic-release,jvrsantacruz/python-semantic-release,relekang/python-semantic-release,wlonk/python-semantic-release,riddlesio/python-semantic-release | tests/test_helpers.py | tests/test_helpers.py | from unittest import TestCase, mock
import semantic_release
from semantic_release.helpers import get_current_version, get_new_version, upload_to_pypi
class GetCurrentVersionTests(TestCase):
def test_should_return_correct_version(self):
self.assertEqual(get_current_version(), semantic_release.__version__... | from unittest import TestCase
import semantic_release
from semantic_release.helpers import get_current_version, get_new_version
class GetCurrentVersionTests(TestCase):
def test_should_return_correct_version(self):
self.assertEqual(get_current_version(), semantic_release.__version__)
class GetNewVersio... | mit | Python |
e40600be30e06d17f2cf745424ea1c9e815021ea | make can_create, can_view_list class methods | cceit/cce-toolkit,cceit/cce-toolkit,cceit/cce-toolkit | toolkit/models/mixins.py | toolkit/models/mixins.py |
class ModelPermissionsMixin(object):
"""
Defines the permissions methods that most models need,
:raises NotImplementedError: if they have not been overridden.
"""
@classmethod
def can_create(cls, user_obj):
"""
CreateView needs permissions at class (table) level.
We'll... |
class ModelPermissionsMixin(object):
"""
Defines the permissions methods that most models need,
:raises NotImplementedError: if they have not been overridden.
"""
def can_create(self, user_obj):
"""
CreateView needs permissions at class (table) level.
We'll try it at insta... | bsd-3-clause | Python |
58447cb4ff259d9a08db4f076623dba58c2c6e9b | Check nestability of context manager | treyhunner/patchio | tests/test_patchio.py | tests/test_patchio.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
test_patchio
----------------------------------
Tests for `patchio` module.
"""
import unittest
import sys
from patchio import patch_args
class TestPatchArgs(unittest.TestCase):
"""Tests for patch_args utility."""
def setUp(self):
self.new_args =... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
test_patchio
----------------------------------
Tests for `patchio` module.
"""
import unittest
import sys
from patchio import patch_args
class TestPatchArgs(unittest.TestCase):
"""Tests for patch_args utility."""
def setUp(self):
self.new_args =... | isc | Python |
52c4c47afc0f6943531c6460acc1f02183245639 | rewrite TestPlugins using pytest fixtures | chhe/streamlink,gravyboat/streamlink,bastimeyer/streamlink,streamlink/streamlink,bastimeyer/streamlink,gravyboat/streamlink,streamlink/streamlink,chhe/streamlink | tests/test_plugins.py | tests/test_plugins.py | import pkgutil
import pytest
import streamlink.plugins
from streamlink.plugin.plugin import Matcher, Plugin
from streamlink.utils.module import load_module
plugins_path = streamlink.plugins.__path__[0]
plugins = [
pname
for finder, pname, ispkg in pkgutil.iter_modules([plugins_path])
if not pname.starts... | import os.path
import pkgutil
import unittest
import streamlink.plugins
from streamlink.plugin.plugin import Matcher, Plugin
from streamlink.utils.module import load_module
class PluginTestMeta(type):
def __new__(mcs, name, bases, dict):
plugin_path = os.path.dirname(streamlink.plugins.__file__)
... | bsd-2-clause | Python |
d2d736311dce8d5685a8895a7c106bb65392c3f6 | Fix NameError and database connection errors in travis-setup.py | ollien/Timpani,ollien/Timpani,ollien/Timpani | tests/travis-setup.py | tests/travis-setup.py | import bcrypt
import sys
sys.path.insert(0, "..")
import timpani
connection = timpani.database.DatabaseConnection())
timpani.database.ConnectionManager.addConnection("main", connection)
hashedPassword = bcrypt.hashpw(bytes("password", "utf-8"), bcrypt.gensalt()).decode("utf-8")
timpani.auth.createUser("tests", hashedP... | import bcrypt
import sys
import os
sys.path.insert(0, "..")
import timpani
hashedpassword = bcrypt.hashpw(bytes("password", "utf-8"), bcrypt.gensalt()).decode("utf-8")
timpani.auth.createUser("tests", hashedPassword, True, True)
connection.close()
| mit | Python |
4fa155674c54dd961c144105839e4ead9f6dff8d | add request customization for tet raven. | tetframework/tet_raven,tetframework/tet_raven | tet_raven/__init__.py | tet_raven/__init__.py | from __future__ import absolute_import
from pyramid.request import Request
from raven import Client as RavenClient
from raven.utils.wsgi import get_current_url, get_headers, get_environ
def raven_tween_factory(handler, registry):
client = registry.raven
exception_filter = registry.tet_raven.exception_filter
... | from __future__ import absolute_import
from pyramid.request import Request
from raven import Client as RavenClient
from raven.utils.wsgi import get_current_url, get_headers, get_environ
def raven_tween_factory(handler, registry):
client = registry.raven
def raven_tween(request):
client.http_context(... | bsd-3-clause | Python |
c6b8062f74c249ce81c871cc80a3e50bfe07c4cd | Increment version to 1.13.1. | GrahamDumpleton/wrapt,GrahamDumpleton/wrapt | src/wrapt/__init__.py | src/wrapt/__init__.py | __version_info__ = ('1', '13', '1')
__version__ = '.'.join(__version_info__)
from .wrappers import (ObjectProxy, CallableObjectProxy, FunctionWrapper,
BoundFunctionWrapper, WeakFunctionProxy, PartialCallableObjectProxy,
resolve_path, apply_patch, wrap_object, wrap_object_attribute,
function_wra... | __version_info__ = ('1', '13', '0')
__version__ = '.'.join(__version_info__)
from .wrappers import (ObjectProxy, CallableObjectProxy, FunctionWrapper,
BoundFunctionWrapper, WeakFunctionProxy, PartialCallableObjectProxy,
resolve_path, apply_patch, wrap_object, wrap_object_attribute,
function_wra... | bsd-2-clause | Python |
93d4a4fc3a129fd0c49719d0242bbfbab76e62e3 | fix sudo.py for macport | Clpsplug/thefuck,scorphus/thefuck,Clpsplug/thefuck,nvbn/thefuck,SimenB/thefuck,nvbn/thefuck,scorphus/thefuck,mlk/thefuck,mlk/thefuck,SimenB/thefuck | thefuck/rules/sudo.py | thefuck/rules/sudo.py | patterns = ['permission denied',
'eacces',
'pkg: insufficient privileges',
'you cannot perform this operation unless you are root',
'non-root users cannot',
'operation not permitted',
'root privilege',
'this command has to be run under ... | patterns = ['permission denied',
'eacces',
'pkg: insufficient privileges',
'you cannot perform this operation unless you are root',
'non-root users cannot',
'operation not permitted',
'root privilege',
'this command has to be run under ... | mit | Python |
92cb6cbe8ff65775e725bd7c8f9dfb908bb46975 | remove dumb nose stuff | Geosyntec/python-tidegates | tidegates/__init__.py | tidegates/__init__.py | from .tidegates import *
from . import toolbox
from . import utils
| from .tidegates import *
from . import toolbox
from . import utils
from .testing import NoseWrapper
test = NoseWrapper().test
| bsd-3-clause | Python |
fa270c75e77f5f12eace6d9629c203af7407cbce | Update module meta data | Matt-Deacalion/django-ssl-admin | ssladmin/__init__.py | ssladmin/__init__.py | """
Django middleware to make the admin https only.
"""
__author__ = 'Matt Deacalion Stevens'
__version__ = '1.0'
| mit | Python | |
6cd1528655548ea2d6388d0485ed5568067509c9 | change version number | free-free/tornasess | tornasess/__init__.py | tornasess/__init__.py | #-*- coding=utf-8 -*-
__author___ = "HUANGBIAO"
__email__ = "19941222hb@gmail.com"
__version__ = "0.5"
from .tornado_session import *
| #-*- coding=utf-8 -*-
__author___ = "HUANGBIAO"
__email__ = "19941222hb@gmail.com"
__version__ = "0.4"
from .tornado_session import *
| mit | Python |
26696d68e6d2cf0ac65556bd35729c1c7dbe3fe1 | change version number | free-free/tornasess | tornasess/__init__.py | tornasess/__init__.py | #-*- coding=utf-8 -*-
__author___ = "HUANGBIAO"
__email__ = "19941222hb@gmail.com"
__version__ = "0.4"
from .tornado_session import *
| #-*- coding=utf-8 -*-
__author___ = "HUANGBIAO"
__email__ = "19941222hb@gmail.com"
__version__ = "0.3"
from .tornado_session import *
from .tornado_hbredis import *
| mit | Python |
3c2319c01ff8fa26795f2149b20e21ffc2adadd2 | change the creation of the database to adopt 0.2 tourbillon version | tourbillonpy/tourbillon-log | tourbillon/log/log.py | tourbillon/log/log.py | import logging
import re
import time
logger = logging.getLogger(__name__)
def get_logfile_metrics(agent):
def follow(thefile, run_event):
thefile.seek(0, 2)
while run_event.is_set():
line = thefile.readline()
if not line:
time.sleep(config['frequency'])
... | import logging
import re
import time
logger = logging.getLogger(__name__)
def get_logfile_metrics(agent):
def follow(thefile, run_event):
thefile.seek(0, 2)
while run_event.is_set():
line = thefile.readline()
if not line:
time.sleep(config['frequency'])
... | apache-2.0 | Python |
02ca3946662fd996f77c30d9e61d8fc8d9243de7 | Make db upgrade step 20 more robust. | exocad/exotrac,dokipen/trac,moreati/trac-gitsvn,exocad/exotrac,dokipen/trac,dafrito/trac-mirror,dafrito/trac-mirror,moreati/trac-gitsvn,dafrito/trac-mirror,dafrito/trac-mirror,exocad/exotrac,dokipen/trac,moreati/trac-gitsvn,exocad/exotrac,moreati/trac-gitsvn | trac/upgrades/db20.py | trac/upgrades/db20.py | from trac.db import Table, Column, Index, DatabaseManager
from trac.core import TracError
from trac.versioncontrol.cache import CACHE_YOUNGEST_REV
def do_upgrade(env, ver, cursor):
"""Modify the repository cache scheme (if needed)
Now we use the 'youngest_rev' entry in the system table
to explicitly store... | from trac.db import Table, Column, Index, DatabaseManager
from trac.core import TracError
from trac.versioncontrol.cache import CACHE_YOUNGEST_REV
def do_upgrade(env, ver, cursor):
"""Modify the repository cache scheme (if needed)
Now we use the 'youngest_rev' entry in the system table
to explicit... | bsd-3-clause | Python |
12075a7ee4d4e03be7125026a67895adf7247b8b | return computeNodeName in vOLT object | jermowery/xos,cboling/xos,cboling/xos,xmaruto/mcord,xmaruto/mcord,jermowery/xos,cboling/xos,jermowery/xos,xmaruto/mcord,cboling/xos,jermowery/xos,cboling/xos,xmaruto/mcord | xos/core/xoslib/methods/volttenant.py | xos/core/xoslib/methods/volttenant.py | from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework.reverse import reverse
from rest_framework import serializers
from rest_framework import generics
from core.models import *
from django.forms import widgets
from cord.models import VOLTTenant, VOLTService
fro... | from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework.reverse import reverse
from rest_framework import serializers
from rest_framework import generics
from core.models import *
from django.forms import widgets
from cord.models import VOLTTenant, VOLTService
fro... | apache-2.0 | Python |
2eb828df506f26a037af827f5f1e83caadbe06a3 | add sockets | NotHandsFree/NotHandsFree,NotHandsFree/NotHandsFree | NotHandsFree/views.py | NotHandsFree/views.py | from NotHandsFree import app, backend, sockets
from flask import render_template, jsonify
@app.route("/")
def home():
return render_template("home.html")
@app.route("/input", methods=['POST'])
def recv_input():
return jsonify(ok="ok")
@sockets.route('/ws')
def ws_receive(ws):
backend.register(ws)
wh... | from NotHandsFree import app, backend
from flask import render_template, jsonify
@app.route("/")
def home():
return render_template("home.html")
@app.route("/input", methods=['POST'])
def recv_input():
return jsonify(ok="ok")
@sockets.route('/ws')
def ws_receive(ws):
backend.register(ws)
while not w... | mit | Python |
9503dcd4949c4d78ccf2333c2d5e8e4ac930edad | Add code for disabling add/remove objects and settings view when Tor is running | neelchauhan/OnionLauncher | OnionLauncher/main.py | OnionLauncher/main.py | import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QMessageBox
from PyQt5.uic import loadUi
from var import values, version
import torctl
from fn_handle import detect_filename
class MainWindow(QMainWindow):
def __init__(self, *args):
super(MainWindow, self).__init__(*args)
# Load .ui file
loadUi... | import sys
from PyQt5.QtWidgets import QApplication, QMainWindow, QMessageBox
from PyQt5.uic import loadUi
from var import values, version
import torctl
from fn_handle import detect_filename
class MainWindow(QMainWindow):
def __init__(self, *args):
super(MainWindow, self).__init__(*args)
# Load .ui file
loadUi... | bsd-2-clause | Python |
94ade19de56cd9df3b32f672d2b59287bf1cc80d | deploy fix for 2 digit minor version | route360/r360-py | deploy.py | deploy.py | ### publish new version of this library to PyPI
### Read more about publishing here: http://peterdowns.com/posts/first-time-with-pypi.html
import git
from shutil import copyfile
import fileinput
import sys
import os
yesOrNo = input('Have you commited all changes? Yes (Y) or no (n)?')
if "Y" == yesOrNo:
copyfile(... | ### publish new version of this library to PyPI
### Read more about publishing here: http://peterdowns.com/posts/first-time-with-pypi.html
import git
from shutil import copyfile
import fileinput
import sys
import os
yesOrNo = input('Have you commited all changes? Yes (Y) or no (n)?')
if "Y" == yesOrNo:
copyfile(... | mit | Python |
82f6ab678f98f2423e68ae869256978ec544a9af | clean vendorized remoto on version mismatch | osynge/ceph-deploy,alfredodeza/ceph-deploy,SUSE/ceph-deploy-to-be-deleted,branto1/ceph-deploy,Vicente-Cheng/ceph-deploy,jumpstarter-io/ceph-deploy,trhoden/ceph-deploy,shenhequnying/ceph-deploy,osynge/ceph-deploy,ghxandsky/ceph-deploy,imzhulei/ceph-deploy,ddiss/ceph-deploy,isyippee/ceph-deploy,trhoden/ceph-deploy,codenr... | vendor.py | vendor.py | import subprocess
import os
from os import path
import traceback
error_msg = """
This library depends on sources fetched when packaging that failed to be
retrieved.
This means that it will *not* work as expected. Errors encountered:
"""
def run(cmd):
print '[vendoring] Running command: %s' % ' '.join(cmd)
... | import subprocess
import os
from os import path
import traceback
error_msg = """
This library depends on sources fetched when packaging that failed to be
retrieved.
This means that it will *not* work as expected. Errors encountered:
"""
def run(cmd):
print '[vendoring] Running command: %s' % ' '.join(cmd)
... | mit | Python |
de39f25891710ea68b3b8b0ec119dd7b2f2a7015 | Update wiggle-sort.py | tudennis/LeetCode---kamyu104-11-24-2015,githubutilities/LeetCode,tudennis/LeetCode---kamyu104-11-24-2015,kamyu104/LeetCode,jaredkoontz/leetcode,yiwen-luo/LeetCode,yiwen-luo/LeetCode,tudennis/LeetCode---kamyu104-11-24-2015,jaredkoontz/leetcode,jaredkoontz/leetcode,kamyu104/LeetCode,yiwen-luo/LeetCode,githubutilities/Lee... | Python/wiggle-sort.py | Python/wiggle-sort.py | # Time: O(n)
# Space: O(1)
class Solution(object):
def wiggleSort(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
for i in xrange(1, len(nums)):
if ((i % 2) and nums[i - 1] > nums[i]) or \
... | # Time: O(n)
# Space: O(1)
class Solution(object):
def wiggleSort(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
for i in xrange(1, len(nums)):
if ((i % 2) and nums[i - 1] > nums[i]) or \
... | mit | Python |
8f10724e59e1a1603710bfc957f12a371c86643f | add function to translate character offsets to byte offsets | cdht/GoSublime,simman/GoSublime,FWennerdahl/GoSublime,dlclark/GoSublime,anacrolix/GoSublime,simman/GoSublime,alexmullins/GoSublime,cdht/GoSublime,alexmullins/GoSublime,DisposaBoy/GoSublime-next,simman/GoSublime,DisposaBoy/GoSublime,dlclark/GoSublime,FWennerdahl/GoSublime,Mistobaan/GoSublime,DisposaBoy/GoSublime,nathany... | gscommon.py | gscommon.py | import sublime
import subprocess
from subprocess import Popen, PIPE
try:
STARTUP_INFO = subprocess.STARTUPINFO()
STARTUP_INFO.dwFlags |= subprocess.STARTF_USESHOWWINDOW
STARTUP_INFO.wShowWindow = subprocess.SW_HIDE
except (AttributeError):
STARTUP_INFO = None
GLOBAL_SNIPPETS = [
(u'\u0282 func: Fun... | import sublime
import subprocess
from subprocess import Popen, PIPE
try:
STARTUP_INFO = subprocess.STARTUPINFO()
STARTUP_INFO.dwFlags |= subprocess.STARTF_USESHOWWINDOW
STARTUP_INFO.wShowWindow = subprocess.SW_HIDE
except (AttributeError):
STARTUP_INFO = None
GLOBAL_SNIPPETS = [
(u'\u0282 func: Fun... | mit | Python |
ed7e17e437b5a08a3b12ecfa9ff28d2aa29de340 | Change order full name. | nabetama/gimei | gimei/name.py | gimei/name.py | # -*- coding: utf-8 -*-
import random
import yaml
class name(object):
def is_male(self):
from gimei import MALE
return self.gender == MALE
def is_female(self):
from gimei import FEMALE
return self.gender == FEMALE
@property
def kanji(self):
return self.all[0]... | # -*- coding: utf-8 -*-
import random
import yaml
class name(object):
def is_male(self):
from gimei import MALE
return self.gender == MALE
def is_female(self):
from gimei import FEMALE
return self.gender == FEMALE
@property
def kanji(self):
return self.all[0]... | mit | Python |
76b9ac8adac4b55995ab358ae6e5b9017e6e7621 | correct stdout2 | smartshark/serverSHARK,smartshark/serverSHARK,smartshark/serverSHARK,smartshark/serverSHARK | smartshark/management/commands/delete_project.py | smartshark/management/commands/delete_project.py | from django.core.management.base import BaseCommand
from smartshark.models import Project
from smartshark.utils import projectUtils
from bson.objectid import ObjectId
import sys
class Command(BaseCommand):
help = 'Deletes all data of a project'
def handle(self, *args, **options):
for p in Project.obj... | from django.core.management.base import BaseCommand
from smartshark.models import Project
from smartshark.utils import projectUtils
from bson.objectid import ObjectId
import sys
class Command(BaseCommand):
help = 'Deletes all data of a project'
def handle(self, *args, **options):
for p in Project.obj... | apache-2.0 | Python |
ceb75d6f58ab16e3afdf3c7b00de539012d790d5 | Make the lib imports work on other computers than Simon's | brutasse/djangopeople,django/djangopeople,polinom/djangopeople,brutasse/djangopeople,polinom/djangopeople,brutasse/djangopeople,polinom/djangopeople,django/djangopeople,polinom/djangopeople,django/djangopeople,brutasse/djangopeople | djangopeoplenet/manage.py | djangopeoplenet/manage.py | #!/usr/bin/env python
import sys, os
root = os.path.dirname(__file__)
paths = (
os.path.join(root),
os.path.join(root, "djangopeople", "lib"),
)
for path in paths:
if not path in sys.path:
sys.path.insert(0, path)
from django.core.management import execute_manager
try:
import settings # Assume... | #!/usr/bin/env python
import sys
paths = (
'/home/simon/sites/djangopeople.net',
'/home/simon/sites/djangopeople.net/djangopeoplenet',
'/home/simon/sites/djangopeople.net/djangopeoplenet/djangopeople/lib',
)
for path in paths:
if not path in sys.path:
sys.path.insert(0, path)
from django.core.m... | mit | Python |
a6e3fe0a63694427e5f0f17f494b369632292c24 | Update to 0.0.55 | KerkhoffTechnologies/django-connectwise,KerkhoffTechnologies/django-connectwise | djconnectwise/__init__.py | djconnectwise/__init__.py | # -*- coding: utf-8 -*-
VERSION = (0, 0, 55, 'alpha')
# pragma: no cover
if VERSION[-1] != "final":
__version__ = '.'.join(map(str, VERSION))
else:
# pragma: no cover
__version__ = '.'.join(map(str, VERSION[:-1]))
| # -*- coding: utf-8 -*-
VERSION = (0, 0, 54, 'alpha')
# pragma: no cover
if VERSION[-1] != "final":
__version__ = '.'.join(map(str, VERSION))
else:
# pragma: no cover
__version__ = '.'.join(map(str, VERSION[:-1]))
| mit | Python |
39208dc8127d3446cec27d896e165b1370d61f2c | Remove stale import for locator | adamfast/geodjango-uscampgrounds,adamfast/geodjango-uscampgrounds | uscampgrounds/load.py | uscampgrounds/load.py | import csv
import os
from decimal import Decimal
from django.contrib.gis.geos import Point
from uscampgrounds.models import Campground
LON = 0
LAT = 1
CAMPGROUND_CODE = 3
CAMPGROUND_NAME = 4
TYPE = 5
PHONE = 6
COMMENTS = 7
SITES = 8
ELEVATION = 9
HOOKUPS = 10
AMENITIES = 11
def scrub_chars(input):
input = input.r... | import csv
import os
from decimal import Decimal
from django.contrib.gis.geos import Point
from uscampgrounds.models import Campground
from locator.objects.models import *
LON = 0
LAT = 1
CAMPGROUND_CODE = 3
CAMPGROUND_NAME = 4
TYPE = 5
PHONE = 6
COMMENTS = 7
SITES = 8
ELEVATION = 9
HOOKUPS = 10
AMENITIES = 11
def sc... | bsd-3-clause | Python |
737e7d24d36d87567737dc3d7a1433964f673599 | fix progress cleaning on order.get | jasonkeene/python-ubersmith,jasonkeene/python-ubersmith,hivelocity/python-ubersmith,hivelocity/python-ubersmith | ubersmith/calls/order.py | ubersmith/calls/order.py | """Order call classes.
These classes implement any response cleaning and validation needed. If a
call class isn't defined for a given method then one is created using
ubersmith.calls.BaseCall.
"""
from ubersmith.calls import BaseCall, GroupCall, _rename_key, _CLEANERS
from ubersmith.utils import prepend_base
__all... | """Order call classes.
These classes implement any response cleaning and validation needed. If a
call class isn't defined for a given method then one is created using
ubersmith.calls.BaseCall.
"""
from ubersmith.calls import BaseCall, GroupCall, _rename_key, _CLEANERS
from ubersmith.utils import prepend_base
__all... | mit | Python |
c02928ec35fc5edab3f0d2eafbb5e4936f31c955 | bump version to 1.9.6 | kumar303/amo-validator,mozilla/amo-validator,magopian/amo-validator,kumar303/amo-validator,mozilla/amo-validator,mozilla/amo-validator,wagnerand/amo-validator,diox/amo-validator,kumar303/amo-validator,magopian/amo-validator,diox/amo-validator,mstriemer/amo-validator,magopian/amo-validator,mstriemer/amo-validator,mozill... | validator/__init__.py | validator/__init__.py | __version__ = '1.9.6'
class ValidationTimeout(Exception):
"""Validation has timed out.
May be replaced by the exception type raised by an external timeout
handler when run in a server environment."""
def __init__(self, timeout):
self.timeout = timeout
def __str__(self):
return '... | __version__ = '1.9.5'
class ValidationTimeout(Exception):
"""Validation has timed out.
May be replaced by the exception type raised by an external timeout
handler when run in a server environment."""
def __init__(self, timeout):
self.timeout = timeout
def __str__(self):
return '... | bsd-3-clause | Python |
9022fa64035682373bcf61f9b31e2d608c331b05 | Bump version to v0.6.8 | Yelp/kafka-utils,Yelp/kafka-utils | kafka_utils/__init__.py | kafka_utils/__init__.py | # -*- coding: utf-8 -*-
# Copyright 2016 Yelp Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ... | # -*- coding: utf-8 -*-
# Copyright 2016 Yelp Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ... | apache-2.0 | Python |
2aea029d66419a3f3d348960feb147ea9d9fe36a | remove duplicate ReconnectingPBClientFactory code | markrwilliams/kontiki,matthewnorman/kon_tiki | kontiki/fundamentals.py | kontiki/fundamentals.py | from heapq import heapify, heappop
def nlargest(n, l):
if not l:
return l
leastL = [-el for el in l]
heapify(leastL)
return [-heappop(leastL) for _ in xrange(min(n, len(l)))]
def majorityMedian(l):
if not l:
raise ValueError("no median for empty data")
return nlargest(len(l) ... | from twisted.spread.pb import PBClientFactory
from twisted.internet.protocol import ReconnectingClientFactory
from heapq import heapify, heappop
def nlargest(n, l):
if not l:
return l
leastL = [-el for el in l]
heapify(leastL)
return [-heappop(leastL) for _ in xrange(min(n, len(l)))]
def maj... | bsd-3-clause | Python |
bfeaec9ca217e227131c132b5d5cfac6af3b99e6 | Change default full width to false (#404) | UTNkar/moore,UTNkar/moore,UTNkar/moore,UTNkar/moore | src/home/migrations/0035_manual_sections_data.py | src/home/migrations/0035_manual_sections_data.py | # Generated by Django 2.2.10 on 2020-04-04 11:30
from django.db import migrations
from itertools import chain
from django.core.serializers.json import DjangoJSONEncoder
from json import dumps
from wagtail.core.blocks.stream_block import StreamValue
def body_to_section(stream_field):
section = {
'type': '... | # Generated by Django 2.2.10 on 2020-04-04 11:30
from django.db import migrations
from itertools import chain
from django.core.serializers.json import DjangoJSONEncoder
from json import dumps
from wagtail.core.blocks.stream_block import StreamValue
def body_to_section(stream_field):
section = {
'type': '... | agpl-3.0 | Python |
ab4ceb6024d311f5e15080b72758f46da26175eb | Add some LT | mph-/lcapy | doc/laplace_transforms.py | doc/laplace_transforms.py | from lcapy import *
alpha = symbol('alpha')
t0 = symbol('t0')
f0 = symbol('f0')
w0 = 2 * pi * f0
sigs = [texpr('x(t)'), texpr('x(a * t)'), texpr('x(t - tau)'),
cos(w0 * t), sin(w0 * t), exp(j * w0 * t),
texpr(1), t, t**2, delta(t), delta(t - t0),
H(t), t * H(t), sign(t),
exp(-abs(t)), ... | from lcapy import *
alpha = symbol('alpha')
t0 = symbol('t0')
f0 = symbol('f0')
w0 = 2 * pi * f0
sigs = [texpr('x(t)'), texpr('x(a * t)'), texpr('x(t - tau)'),
cos(w0 * t), sin(w0 * t), exp(j * w0 * t),
texpr(1), t, t**2, delta(t), delta(t - t0),
H(t), t * H(t), sign(t),
exp(-abs(t)), ... | lgpl-2.1 | Python |
349bc738d3d0bda531d6bdf0b3f50464e2ec9975 | fix externals/abi/common test for msvc | iamrekcah/clay,jckarter/clay,mario-campos/clay,aep/clay,aep/clay,jckarter/clay,iamrekcah/clay,aep/clay,mario-campos/clay,jckarter/clay,mario-campos/clay,iamrekcah/clay,aep/clay,jckarter/clay,mario-campos/clay,iamrekcah/clay,iamrekcah/clay,jckarter/clay,aep/clay,mario-campos/clay,aep/clay,jckarter/clay | test/externals/abi/common/run.py | test/externals/abi/common/run.py | from subprocess import check_call, CalledProcessError
from sys import argv, platform
import os
clayobj = argv[1]
buildFlags = argv[2:]
linkFlags = [];
if platform == 'linux' or platform == 'linux2':
linkFlags += ['-lm']
NULL = open(os.devnull, 'w')
try:
if platform == 'win32':
os.rename(clayobj, "te... | from subprocess import check_call, CalledProcessError
from sys import argv, platform
import os
clayobj = argv[1]
buildFlags = argv[2:]
linkFlags = [];
if platform == 'linux' or platform == 'linux2':
linkFlags += ['-lm']
try:
if platform == 'win32':
os.rename(clayobj, "temp-main.obj")
check_ca... | bsd-2-clause | Python |
bb34b21ebd2378f944498708ac4f13d16aa61aa1 | Rename Behave steps for api tests | johnnyWalnut/mist.io,DimensionDataCBUSydney/mist.io,zBMNForks/mist.io,afivos/mist.io,Lao-liu/mist.io,Lao-liu/mist.io,munkiat/mist.io,kelonye/mist.io,kelonye/mist.io,afivos/mist.io,Lao-liu/mist.io,Lao-liu/mist.io,DimensionDataCBUSydney/mist.io,johnnyWalnut/mist.io,zBMNForks/mist.io,DimensionDataCBUSydney/mist.io,Dimensi... | src/mist/io/tests/api/features/steps/backends.py | src/mist/io/tests/api/features/steps/backends.py | from behave import *
@given(u'"{text}" backend added through api')
def given_backend(context, text):
backends = context.client.list_backends()
for backend in backends:
if text in backend['title']:
return
@when(u'I list backends')
def list_backends(context):
context.backends = contex... | from behave import *
@given(u'"{text}" backend added')
def given_backend(context, text):
backends = context.client.list_backends()
for backend in backends:
if text in backend['title']:
return
@when(u'I list backends')
def list_backends(context):
context.backends = context.client.lis... | agpl-3.0 | Python |
cc624aff5816a4a2e7a6d1d85b5eac368aa6bc0d | Clear error message on payment form validation | joeirimpan/shop,joeirimpan/shop,joeirimpan/shop | shop/checkout/forms.py | shop/checkout/forms.py | # -*- coding: utf-8 -*-
"""Checkout forms."""
from flask_login import current_user
from flask_wtf import Form
from shop.checkout.models import PaymentProfile
from shop.user.forms import AddressForm
from shop.user.models import Address
from wtforms import IntegerField, PasswordField, RadioField, StringField, BooleanFie... | # -*- coding: utf-8 -*-
"""Checkout forms."""
from flask_login import current_user
from flask_wtf import Form
from shop.checkout.models import PaymentProfile
from shop.user.forms import AddressForm
from shop.user.models import Address
from wtforms import IntegerField, PasswordField, RadioField, StringField, BooleanFie... | bsd-3-clause | Python |
6f42f03f950e4c3967eb1efd7feb9364c9fbaf1f | Use userinfo URI for user profile info | singingwolfboy/flask-dance-google | google.py | google.py | import os
from werkzeug.contrib.fixers import ProxyFix
from flask import Flask, redirect, url_for
from flask_dance.contrib.google import make_google_blueprint, google
from raven.contrib.flask import Sentry
app = Flask(__name__)
app.wsgi_app = ProxyFix(app.wsgi_app)
sentry = Sentry(app)
app.secret_key = os.environ.get(... | import os
from werkzeug.contrib.fixers import ProxyFix
from flask import Flask, redirect, url_for
from flask_dance.contrib.google import make_google_blueprint, google
from raven.contrib.flask import Sentry
app = Flask(__name__)
app.wsgi_app = ProxyFix(app.wsgi_app)
sentry = Sentry(app)
app.secret_key = os.environ.get(... | mit | Python |
2bb8ee6ae30e233f28ea0ae0fb01c0e4a1f8d9f1 | Sort imports for the greater good | xavfernandez/pip,sbidoul/pip,pypa/pip,rouge8/pip,rouge8/pip,pfmoore/pip,xavfernandez/pip,sbidoul/pip,pypa/pip,pradyunsg/pip,xavfernandez/pip,pradyunsg/pip,pfmoore/pip,rouge8/pip | tests/functional/test_warning.py | tests/functional/test_warning.py | import textwrap
import pytest
@pytest.fixture
def warnings_demo(tmpdir):
demo = tmpdir.joinpath('warnings_demo.py')
demo.write_text(textwrap.dedent('''
from logging import basicConfig
from pip._internal.utils import deprecation
deprecation.install_warning_logger()
basicConfig... | import pytest
import textwrap
@pytest.fixture
def warnings_demo(tmpdir):
demo = tmpdir.joinpath('warnings_demo.py')
demo.write_text(textwrap.dedent('''
from logging import basicConfig
from pip._internal.utils import deprecation
deprecation.install_warning_logger()
basicConfig(... | mit | Python |
6752b5179dbd390faa10a50b2c267867e0683922 | send more message to client | pengzhangdev/slackbot,pengzhangdev/slackbot | slackbot/plugins/fm.py | slackbot/plugins/fm.py | #! /usr/bin/env python
#
# fm.py ---
#
# Filename: fm.py
# Description:
# Author: Werther Zhang
# Maintainer:
# Created: Sat Oct 21 20:24:01 2017 (+0800)
#
# Change Log:
#
#
import sys
import difflib
from component.filemanager import FileManager
from slackbot.bot import plugin_init
from slackbot.bot import respond_... | #! /usr/bin/env python
#
# fm.py ---
#
# Filename: fm.py
# Description:
# Author: Werther Zhang
# Maintainer:
# Created: Sat Oct 21 20:24:01 2017 (+0800)
#
# Change Log:
#
#
import sys
import difflib
from component.filemanager import FileManager
from slackbot.bot import plugin_init
from slackbot.bot import respond_... | mit | Python |
db88ed56c8b5085bb16676a65d17869620c4cc79 | Comment hacks | felix1m/pyspotify,kotamat/pyspotify,felix1m/pyspotify,kotamat/pyspotify,jodal/pyspotify,jodal/pyspotify,mopidy/pyspotify,felix1m/pyspotify,mopidy/pyspotify,jodal/pyspotify,kotamat/pyspotify | docs/conf.py | docs/conf.py | # encoding: utf-8
"""pyspotify documentation build configuration file"""
from __future__ import unicode_literals
import mock
import os
import re
import sys
def get_version(filename):
init_py = open(filename).read()
metadata = dict(re.findall("__([a-z]+)__ = '([^']+)'", init_py))
return metadata['versio... | # encoding: utf-8
"""pyspotify documentation build configuration file"""
from __future__ import unicode_literals
import mock
import os
import re
import sys
def get_version(filename):
init_py = open(filename).read()
metadata = dict(re.findall("__([a-z]+)__ = '([^']+)'", init_py))
return metadata['versio... | apache-2.0 | Python |
ad73789f74106a2d6014a2f737578494d2d21fbf | Remove specific process API GET endpoints | virtool/virtool,igboyes/virtool,virtool/virtool,igboyes/virtool | virtool/api/processes.py | virtool/api/processes.py | import virtool.http.routes
import virtool.utils
from virtool.api.utils import json_response
routes = virtool.http.routes.Routes()
@routes.get("/api/processes")
async def find(req):
db = req.app["db"]
documents = [virtool.utils.base_processor(d) async for d in db.processes.find()]
return json_response(d... | import virtool.http.routes
import virtool.utils
from virtool.api.utils import json_response
routes = virtool.http.routes.Routes()
@routes.get("/api/processes")
async def find(req):
db = req.app["db"]
documents = [virtool.utils.base_processor(d) async for d in db.processes.find()]
return json_response(d... | mit | Python |
c18b8b5e545032ae512bad505255c0f72390b633 | Use setuptools_scm in docs generation. | pytest-dev/pytest-runner | docs/conf.py | docs/conf.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import setuptools_scm
extensions = [
'sphinx.ext.autodoc',
]
# General information about the project.
project = 'pytest-runner'
copyright = '2015 Jason R. Coombs'
# The short X.Y version.
version = setuptools_scm.get_version()
# The full version, inc... | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import hgtools.managers
# use hgtools to get the version
hg_mgr = hgtools.managers.RepoManager.get_first_valid_manager()
extensions = [
'sphinx.ext.autodoc',
]
# General information about the project.
project = 'pytest-runner'
copyright = '2015 Jason ... | mit | Python |
3d7cfa80fd6b1bb6bc48dbbea81b048f50bd87af | convert collection into ResourceList | edworboys/soundcloud-python,soundcloud/soundcloud-python,icoxfog417/soundcloud-python,phijor/soundcloud-python | soundcloud/resource.py | soundcloud/resource.py | try:
import json
except ImportError:
import simplejson as json
from UserList import UserList
class Resource(object):
"""Object wrapper for resources.
Provides an object interface to resources returned by the Soundcloud API.
"""
def __init__(self, obj):
self.obj = obj
def __getst... | try:
import json
except ImportError:
import simplejson as json
from UserList import UserList
class Resource(object):
"""Object wrapper for resources.
Provides an object interface to resources returned by the Soundcloud API.
"""
def __init__(self, obj):
self.obj = obj
def __getst... | bsd-2-clause | Python |
68350e16e25181f1fba8af6004ac15ecfdb599fb | fix search | openrural/open-data-nc,openrural/open-data-nc,OpenData-NC/open-data-nc,OpenData-NC/open-data-nc,openrural/open-data-nc,OpenData-NC/open-data-nc | suggestions/views.py | suggestions/views.py | from django.shortcuts import render, redirect, get_object_or_404
from django.template import RequestContext
from django.http import HttpResponseRedirect
from django.contrib.auth.decorators import login_required
from django.core.urlresolvers import reverse
from suggestions.models import *
from suggestions.forms import ... | from django.shortcuts import render, redirect, get_object_or_404
from django.template import RequestContext
from django.http import HttpResponseRedirect
from django.contrib.auth.decorators import login_required
from django.core.urlresolvers import reverse
from suggestions.models import *
from suggestions.forms import ... | mit | Python |
bb5f95f3349acc943496521d2de9e410c83b5d10 | modify config | charliezon/stock,charliezon/stock,charliezon/stock,charliezon/stock | www/config_default.py | www/config_default.py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
'''
Default configurations.
'''
__author__ = 'Chaoliang Zhong'
configs = {
'debug': True,
'db': {
'host': '127.0.0.1',
'port': 3306,
'user': 'root',
'password': 'rootroot',
'db': 'stock'
},
'sessi... | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
'''
Default configurations.
'''
__author__ = 'Chaoliang Zhong'
configs = {
'debug': True,
'db': {
'host': '127.0.0.1',
'port': 3306,
'user': 'root',
'password': 'rootroot',
'db': 'stock'
},
'sessi... | mit | Python |
430543cd6fe483e40209d5249b32212a7e72eb3f | update to use more complete and binary safe product delimiting | akrherz/pyWWA,akrherz/pyWWA | support/ldmbridge.py | support/ldmbridge.py |
# Python imports
import sys, re
from twisted.internet import stdio, error
from twisted.protocols import basic
from twisted.internet import reactor
class LDMProductReceiver(basic.LineReceiver):
delimiter = '\n'
product_start = '\001'
product_end = '\r\r\n\003'
def __init__(self):
self.produc... |
# Python imports
import sys, re
from twisted.internet import stdio, error
from twisted.protocols import basic
from twisted.internet import reactor
class LDMProductReceiver(basic.LineReceiver):
delimiter = '\n'
productDelimiter = '\003'
def __init__(self):
self.productBuffer = ""
self.set... | mit | Python |
3bc5be0fc288379a4dbc801dca5d45962131e596 | make payments readonly until they get removed | feinheit/zipfelchappe,feinheit/zipfelchappe,feinheit/zipfelchappe,feinheit/zipfelchappe | zipfelchappe/admin.py | zipfelchappe/admin.py | from django.contrib import admin
from django.utils.translation import ugettext_lazy as _
from feincms.admin import item_editor
from zipfelchappe.models import Project, Reward, Payment
class RewardInlineAdmin(admin.TabularInline):
model = Reward
extra = 0
class PaymentInlineAdmin(admin.TabularInline):
m... | from django.contrib import admin
from django.utils.translation import ugettext_lazy as _
from feincms.admin import item_editor
from orderable_inlines import OrderableTabularInline
from zipfelchappe.models import Project, Reward, Payment
class RewardInlineAdmin(OrderableTabularInline):
model = Reward
extra ... | bsd-3-clause | Python |
93704d4d7effd35d10b8f1247d64254fb483d65e | Fix PR extlinks in sphinx config | cherrypy/cheroot | docs/conf.py | docs/conf.py | #!/usr/bin/env python3
# Requires Python 3.6+
"""Configuration of Sphinx documentation generator."""
extensions = [
'sphinx.ext.autodoc',
'sphinx.ext.extlinks',
'sphinx.ext.intersphinx',
'jaraco.packaging.sphinx',
'rst.linker',
]
master_doc = 'index'
link_files = {
'../CHANGES.rst': dict(
... | #!/usr/bin/env python3
# Requires Python 3.6+
"""Configuration of Sphinx documentation generator."""
extensions = [
'sphinx.ext.autodoc',
'sphinx.ext.extlinks',
'sphinx.ext.intersphinx',
'jaraco.packaging.sphinx',
'rst.linker',
]
master_doc = 'index'
link_files = {
'../CHANGES.rst': dict(
... | bsd-3-clause | Python |
a4252036f187c633646fcf812811afcc3d53c66a | update tests for appliance instances | dssg/wikienergy,dssg/wikienergy,dssg/wikienergy,dssg/wikienergy,dssg/wikienergy | tests/test_appliance_instance.py | tests/test_appliance_instance.py | import sys
sys.path.append('..')
import disaggregator as da
import unittest
import pandas as pd
import numpy as np
class ApplianceInstanceTestCase(unittest.TestCase):
def setUp(self):
indices = [pd.date_range('1/1/2013', periods=96, freq='15T'),
pd.date_range('1/2/2013', periods=96, fre... | import sys
sys.path.append('..')
import disaggregator as da
import unittest
import pandas as pd
import numpy as np
class ApplianceInstanceTestCase(unittest.TestCase):
def setUp(self):
indices = [pd.date_range('1/1/2013', periods=96, freq='15T'),
pd.date_range('1/2/2013', periods=96, fre... | mit | Python |
53c9d483318964dc8f17068cbe1a905bca2c7090 | fix typo | saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt,saltstack/salt | tests/unit/states/module_test.py | tests/unit/states/module_test.py | # -*- coding: utf-8 -*-
'''
:codeauthor: :email:`Nicole Thomas (nicole@saltstack.com)`
'''
# Import Python Libs
from inspect import ArgSpec
# Import Salt Libs
from salt.states import module
# Import Salt Testing Libs
from salttesting import skipIf, TestCase
from salttesting.helpers import ensure_in_syspath
from ... | # -*- coding: utf-8 -*-
'''
:codeauthor: :email:`Nicole Thomas (nicole@saltstack.com)`
'''
# Import Pyhton Libs
from inspect import ArgSpec
# Import Salt Libs
from salt.states import module
# Import Salt Testing Libs
from salttesting import skipIf, TestCase
from salttesting.helpers import ensure_in_syspath
from ... | apache-2.0 | Python |
77ad68b04b66feb47116999cf79892f6630d9601 | Fix encoding error in source file example | lawrencebenson/thefuck,mlk/thefuck,nvbn/thefuck,PLNech/thefuck,scorphus/thefuck,nvbn/thefuck,SimenB/thefuck,Clpsplug/thefuck,SimenB/thefuck,mlk/thefuck,scorphus/thefuck,lawrencebenson/thefuck,Clpsplug/thefuck,PLNech/thefuck | thefuck/rules/ln_no_hard_link.py | thefuck/rules/ln_no_hard_link.py | # -*- coding: utf-8 -*-
"""Suggest creating symbolic link if hard link is not allowed.
Example:
> ln barDir barLink
ln: ‘barDir’: hard link not allowed for directory
--> ln -s barDir barLink
"""
import re
from thefuck.specific.sudo import sudo_support
@sudo_support
def match(command):
return (command.stderr.en... | """Suggest creating symbolic link if hard link is not allowed.
Example:
> ln barDir barLink
ln: ‘barDir’: hard link not allowed for directory
--> ln -s barDir barLink
"""
import re
from thefuck.specific.sudo import sudo_support
@sudo_support
def match(command):
return (command.stderr.endswith("hard link not al... | mit | Python |
1cc33fd09078f6dc85d7d9cf9c9243759324e094 | delete pid file if pid is dead | cmccabe/redfish,cmccabe/redfish,cmccabe/redfish,cmccabe/redfish,cmccabe/redfish | dtest/run.py | dtest/run.py | #!/usr/bin/python
import json
import os
import subprocess
import sys
import tempfile
from of_daemon import *
from of_util import *
from optparse import OptionParser
if sys.version < '2.5':
sys.stderr.write("You need Python 2.5 or newer.)\n")
sys.exit(1)
def process_is_running(pid):
cmd = "ps -p %d" % pid... | #!/usr/bin/python
import json
import os
import subprocess
import sys
import tempfile
from of_daemon import *
from of_util import *
from optparse import OptionParser
if sys.version < '2.5':
sys.stderr.write("You need Python 2.5 or newer.)\n")
sys.exit(1)
parser = OptionParser()
parser.add_option("-c", "--clus... | apache-2.0 | Python |
c60aabdc34ea3b7b25541126dc0770f566c6d15b | update init.py | lhat-messorem/syntax_db | syntaxdb/__init__.py | syntaxdb/__init__.py | from syntaxdb import syntaxdb | mit | Python | |
76ef28b2d34bbdecd1b068041d8a53f677cba4a3 | Remove jax.util.partial. | google/jax,google/jax,google/jax,google/jax | jax/util.py | jax/util.py | # Copyright 2018 Google LLC
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | # Copyright 2018 Google LLC
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | apache-2.0 | Python |
0fd946251ae463ec8f55c5e2b68000d2d5aeb598 | Bump to version 0.9.4 | reubano/meza,reubano/meza,reubano/tabutils,reubano/meza,reubano/tabutils,reubano/tabutils | tabutils/__init__.py | tabutils/__init__.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# vim: sw=4:ts=4:expandtab
"""
tabutils
~~~~~~~~
Provides methods for reading and processing data from tabular formatted files
Examples:
literal blocks::
python example_google.py
Attributes:
ENCODING (str): Default file encoding.
"""
__title__ = 'tabut... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# vim: sw=4:ts=4:expandtab
"""
tabutils
~~~~~~~~
Provides methods for reading and processing data from tabular formatted files
Examples:
literal blocks::
python example_google.py
Attributes:
ENCODING (str): Default file encoding.
"""
__title__ = 'tabut... | mit | Python |
40bb81ef9cfd333249333e9eadc960048f768d9a | Bump to version 0.9.1 | reubano/tabutils,reubano/tabutils,reubano/tabutils,reubano/meza,reubano/meza,reubano/meza | tabutils/__init__.py | tabutils/__init__.py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# vim: sw=4:ts=4:expandtab
"""
tabutils
~~~~~~~~
Provides methods for reading and processing data from tabular formatted files
Examples:
literal blocks::
python example_google.py
Attributes:
ENCODING (str): Default file encoding.
"""
__title__ = 'tabut... | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# vim: sw=4:ts=4:expandtab
"""
tabutils
~~~~~~~~
Provides methods for reading and processing data from tabular formatted files
Examples:
literal blocks::
python example_google.py
Attributes:
ENCODING (str): Default file encoding.
"""
__title__ = 'tabut... | mit | Python |
1c148aa3ca42bd5d265ef053f675e91acfea51e0 | Add pre- and postflight to call-implementation. | factorial-io/fabalicious,factorial-io/fabalicious | lib/methods/__init__.py | lib/methods/__init__.py | import inspect, sys
from types import TypeType
from base import BaseMethod
from git import GitMethod
from drush import DrushMethod
from ssh import SSHMethod
from composer import ComposerMethod
from scripts import ScriptMethod
from docker import DockerMethod
from slack import SlackMethod
from files import FilesMethod
c... | import inspect, sys
from types import TypeType
from base import BaseMethod
from git import GitMethod
from drush import DrushMethod
from ssh import SSHMethod
from composer import ComposerMethod
from scripts import ScriptMethod
from docker import DockerMethod
from slack import SlackMethod
from files import FilesMethod
c... | mit | Python |
e10d07d4a6012abbb451936c12324df1a12c5f4c | Update thumbnail names | davidbrough1/cse_6242_PCA_Vis | dimension_reduction_code/make_json.py | dimension_reduction_code/make_json.py | import json
import os
directory = '/home/david/git/cse_6242_PCA_Vis/dimension_reduction_code'
json_file = directory + '/12_samples_json_truncated_to_strain_375.JSON'
reduced_data = []
with open(json_file, 'rb') as f:
for line in f:
reduced_data.append(json.loads(line))
reduced_data_names = sorted(reduced... | import json
import os
directory = '/home/david/git/cse_6242_PCA_Vis/dimension_reduction_code'
json_file = directory + '/12_samples_json_truncated_to_strain_375.JSON'
reduced_data = []
with open(json_file, 'rb') as f:
for line in f:
reduced_data.append(json.loads(line))
reduced_data_names = sorted(reduced... | mit | Python |
d7f3ea41bc3d252d786a339fc34337f01e1cc3eb | Remove reference to old UUIDfield in django migration | dabapps/django-db-queue | django_dbq/migrations/0001_initial.py | django_dbq/migrations/0001_initial.py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import jsonfield.fields
import uuid
from django.db.models import UUIDField
class Migration(migrations.Migration):
dependencies = [
]
operations = [
migrations.CreateModel(
name=... | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import jsonfield.fields
import uuid
try:
from django.db.models import UUIDField
except ImportError:
from django_dbq.fields import UUIDField
class Migration(migrations.Migration):
dependencies = [
... | bsd-2-clause | Python |
5450e3ad4770a44b9d775a00fa2b70207a4831b9 | fix test of plumbing to not fail on my recent changes to the arg. parsing | fernandezcuesta/fabric,pashinin/fabric,kmonsoor/fabric,TarasRudnyk/fabric,raimon49/fabric,qinrong/fabric,cgvarela/fabric,bspink/fabric,xLegoz/fabric,ploxiln/fabric,mathiasertl/fabric,simon-engledew/fabric,getsentry/fabric,pgroudas/fabric,rbramwell/fabric,jaraco/fabric,itoed/fabric,ericholscher/fabric,rane-hs/fabric-py3... | test/test_plumbing.py | test/test_plumbing.py | def setUp(self):
pass
def test_cli_arg_parsing(self):
tests = [
("abc", ("abc", {})),
("ab:c", ("ab", {'c':'c'})),
("a:b=c", ('a', {'b':'c'})),
("a:b=c,d=e", ('a', {'b':'c','d':'e'})),
]
for cli, output in tests:
self.assertEquals(fabric._parse_args([cli]), [outpu... | def setUp(self):
pass
def test_cli_arg_parsing(self):
tests = [
("abc", ("abc", {})),
("ab:c", ("ab", {'c':''})),
("a:b=c", ('a', {'b':'c'})),
("a:b=c,d=e", ('a', {'b':'c','d':'e'})),
]
for cli, output in tests:
self.assertEquals(fabric._parse_args([cli]), [output... | bsd-2-clause | Python |
a71ab051035270a92fcc86154ac8f6f77a79cbed | add healthz route to python runtime | jjo/kubeless,jbianquetti-nami/kubeless,skippbox/kubeless,ngtuna/kubeless,jbianquetti-nami/kubeless,sebgoa/kubeless,sebgoa/kubeless,jjo/kubeless,skippbox/kubeless,jjo/kubeless,skippbox/kubeless,kubeless/kubeless,jjo/kubeless,ngtuna/kubeless,kubeless/kubeless,jbianquetti-nami/kubeless,sebgoa/kubeless,sebgoa/kubeless,skip... | docker/runtime/python-2.7/kubeless.py | docker/runtime/python-2.7/kubeless.py | #!/usr/bin/env python
import sys
import os
import imp
from bottle import route, run, request
mod_name = os.getenv('MOD_NAME')
func_handler = os.getenv('FUNC_HANDLER')
mod_path = '/kubeless/' + mod_name + '.py'
try:
mod = imp.load_source('lambda', mod_path)
except ImportError:
print("No valid module found f... | #!/usr/bin/env python
import sys
import os
import imp
from bottle import route, run, request
mod_name = os.getenv('MOD_NAME')
func_handler = os.getenv('FUNC_HANDLER')
mod_path = '/kubeless/' + mod_name + '.py'
try:
mod = imp.load_source('lambda', mod_path)
except ImportError:
print("No valid module found f... | apache-2.0 | Python |
5d788146d7160da7eb43fe1f9f9a49a249d4ed30 | Update deprecationwarning | Aaron1992/wtforms,Xender/wtforms,Aaron1992/wtforms,skytreader/wtforms,pawl/wtforms,jmagnusson/wtforms,pawl/wtforms,cklein/wtforms,crast/wtforms,wtforms/wtforms,hsum/wtforms,subyraman/wtforms | wtforms/ext/i18n/form.py | wtforms/ext/i18n/form.py | import warnings
from wtforms import form
from wtforms.ext.i18n.utils import get_translations
translations_cache = {}
class Form(form.Form):
"""
Base form for a simple localized WTForms form.
**NOTE** this class is now un-necessary as the i18n features have
been moved into the core of WTForms, but it... | import warnings
from wtforms import form
from wtforms.ext.i18n.utils import get_translations
translations_cache = {}
class Form(form.Form):
"""
Base form for a simple localized WTForms form.
**NOTE** this class is now un-necessary as the i18n features have
been moved into the core of WTForms, but it... | bsd-3-clause | Python |
03c5ff794d8e5e2ccfda2303bae5c5c03fc41d2b | update file index method, getIndex(index,dir) gives list of metadata and folder in the index variable | yuan3y/dropbox-clone-MID | fileindex.py | fileindex.py | import os.path
import filemeta
import json
from server.server import walkFiles
def getIndex(index,dir="./"):
meta_data_dict = dict()
listFiles=[]
listFolders=[]
walkFiles(listFiles,listFolders,dir)
for filename in listFiles:
meta_data_dict.setdefault(filename,filemeta.filemeta(filename))
... | import os.path
import filemeta
import json
meta_data_dict = dict()
if False:
# os.path.isfile('.index'):
# TODO: compare the index hash and current hash
pass
else:
# build index
f = open('.index', 'w')
file_names_list = os.listdir("./")
for filename in file_names_list:
if os.path.i... | mit | Python |
9c31ea3f33215ce3e92e34f31587f2ef8282d575 | Fix setup.py for use with jsonschema. | colinhiggs/pyramid-jsonapi,colinhiggs/pyramid-jsonapi | test_project/setup.py | test_project/setup.py | import os
from setuptools import setup, find_packages
here = os.path.abspath(os.path.dirname(__file__))
README = open(os.path.join(here, 'README.txt')).read()
CHANGES = open(os.path.join(here, 'CHANGES.txt')).read()
requires = [
'pyramid',
'SQLAlchemy',
'transaction',
'pyramid_tm',
'pyramid_debug... | import os
from setuptools import setup, find_packages
here = os.path.abspath(os.path.dirname(__file__))
README = open(os.path.join(here, 'README.txt')).read()
CHANGES = open(os.path.join(here, 'CHANGES.txt')).read()
requires = [
'pyramid',
'SQLAlchemy',
'transaction',
'pyramid_tm',
'pyramid_debug... | agpl-3.0 | Python |
a2c16356a105d8c832455413b76568cf07518452 | Fix depends for new pythia version scheme (#26294) | LLNL/spack,LLNL/spack,LLNL/spack,LLNL/spack,LLNL/spack | var/spack/repos/builtin/packages/dire/package.py | var/spack/repos/builtin/packages/dire/package.py | # Copyright 2013-2021 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class Dire(Package):
"""DIRE (short for dipole resummation) a C++ program for all-order
radi... | # Copyright 2013-2021 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class Dire(Package):
"""DIRE (short for dipole resummation) a C++ program for all-order
radi... | lgpl-2.1 | Python |
ddf0f7b7248f23f65c90d8218b2983c9ff591b43 | Change mixer.init() to mixer.pre_init() | MarquisLP/Sidewalk-Champion | Sidewalk_Champion.py | Sidewalk_Champion.py | """
* ************************************************
* Sidewalk Champion - A Customizable Fighting Game
* Author: Mark Padilla
* Created: 3 May 2014
* Last Updated: 20 August 2014
* ************************************************
"""
import os
import pygame
from pygame.locals import *
from lib... | """
* ************************************************
* Sidewalk Champion - A Customizable Fighting Game
* Author: Mark Padilla
* Created: 3 May 2014
* Last Updated: 20 August 2014
* ************************************************
"""
import os
import pygame
from pygame.locals import *
from lib... | unlicense | Python |
26bb46ac9bceb91f744cd973458248c6071d6a0e | update test to v1.1.0 (#1639) | exercism/xpython,jmluy/xpython,exercism/xpython,N-Parsons/exercism-python,exercism/python,N-Parsons/exercism-python,behrtam/xpython,smalley/python,behrtam/xpython,exercism/python,jmluy/xpython,smalley/python | exercises/raindrops/raindrops_test.py | exercises/raindrops/raindrops_test.py | import unittest
from raindrops import raindrops
# Tests adapted from `problem-specifications//canonical-data.json` @ v1.1.0
class RaindropsTest(unittest.TestCase):
def test_the_sound_for_1_is_1(self):
self.assertEqual(raindrops(1), "1")
def test_the_sound_for_3_is_pling(self):
self.assertEq... | import unittest
from raindrops import raindrops
class RaindropsTest(unittest.TestCase):
def test_1(self):
self.assertEqual(raindrops(1), "1")
def test_3(self):
self.assertEqual(raindrops(3), "Pling")
def test_5(self):
self.assertEqual(raindrops(5), "Plang")
def test_7(self)... | mit | Python |
afc359bb2d6b8c0677f38adaa89fc08224a279aa | Remove unused import | bugsnag/bugsnag-python,bugsnag/bugsnag-python | tests/large_object.py | tests/large_object.py | import os
def large_object_file_path():
"""
Resolve the file path to the large_object.json file. This is needed by
`test_utils.py` as the `timeit` module is not able to resolve the path to
the file correctly.
"""
return os.path.abspath(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'l... | import os
import json
def large_object_file_path():
"""
Resolve the file path to the large_object.json file. This is needed by
`test_utils.py` as the `timeit` module is not able to resolve the path to
the file correctly.
"""
return os.path.abspath(os.path.join(os.path.dirname(os.path.abspath(__... | mit | Python |
a5130e32bffa1dbc4d83f349fc3653b690154d71 | Add keyword to echo worker. | TouK/vumi,vishwaprakashmishra/xmatrix,harrissoerja/vumi,TouK/vumi,vishwaprakashmishra/xmatrix,harrissoerja/vumi,vishwaprakashmishra/xmatrix,harrissoerja/vumi,TouK/vumi | vumi/workers/vas2nets/workers.py | vumi/workers/vas2nets/workers.py | # -*- test-case-name: vumi.workers.vas2nets.test_vas2nets -*-
# -*- encoding: utf-8 -*-
from twisted.python import log
from twisted.internet.defer import inlineCallbacks, Deferred
from vumi.message import Message
from vumi.service import Worker
class EchoWorker(Worker):
@inlineCallbacks
def startWorker(sel... | # -*- test-case-name: vumi.workers.vas2nets.test_vas2nets -*-
# -*- encoding: utf-8 -*-
from twisted.python import log
from twisted.internet.defer import inlineCallbacks, Deferred
from vumi.message import Message
from vumi.service import Worker
class EchoWorker(Worker):
@inlineCallbacks
def startWorker(sel... | bsd-3-clause | Python |
66366d0c1dc255946ae4fba31f769a55e343a6a9 | Fix a couple of typos in 1d mesh tests | fangohr/mpimag,fangohr/mpimag,fangohr/mpimag | tests/test_1d_mesh.py | tests/test_1d_mesh.py | """
=========================================================================
Mesh Tests
=========================================================================
Tests for FD meshes
-------------------------------------------------------------------------
1D meshes
---------------------------------------------------... | """
=========================================================================
Mesh Tests
=========================================================================
Tests for FD meshes
-------------------------------------------------------------------------
1D meshes
---------------------------------------------------... | bsd-2-clause | Python |
63d3f69c3c5695f55ef915d2474df0cd89588849 | test client-repr | Thor77/TeamspeakStats,Thor77/TeamspeakStats | tests/test_general.py | tests/test_general.py | from tsstats import parse_logs
from os import remove
from nose.tools import raises
clients = parse_logs('tests/res/test.log')
def test_length():
assert len(clients.clients_by_id) == 2
assert len(clients.clients_by_uid) == 1
def test_getter():
# check getter not raise
assert clients['UIDClient2'].on... | from tsstats import parse_logs
from os import remove
clients = parse_logs('tests/res/test.log')
def test_length():
assert len(clients.clients_by_id) == 2
assert len(clients.clients_by_uid) == 1
def test_getter():
# check getter not raise
assert clients['UIDClient2'].onlinetime == 0
def test_parse... | mit | Python |
5f29736efffe7a5d4b0b589a9aaa144b6d2ebc1f | Fix failed test | KeepSafe/aiohttp,arthurdarcet/aiohttp,juliatem/aiohttp,alex-eri/aiohttp-1,moden-py/aiohttp,KeepSafe/aiohttp,KeepSafe/aiohttp,esaezgil/aiohttp,arthurdarcet/aiohttp,jettify/aiohttp,panda73111/aiohttp,z2v/aiohttp,rutsky/aiohttp,alex-eri/aiohttp-1,playpauseandstop/aiohttp,pfreixes/aiohttp,rutsky/aiohttp,pfreixes/aiohttp,pa... | tests/test_run_app.py | tests/test_run_app.py | import ssl
from unittest import mock
from aiohttp import web
def test_run_app_http(loop, mocker):
mocker.spy(loop, 'create_server')
loop.call_later(0.02, loop.stop)
app = web.Application(loop=loop)
mocker.spy(app, 'startup')
web.run_app(app, print=lambda *args: None)
assert loop.is_closed(... | import ssl
from unittest import mock
from aiohttp import web
def test_run_app_http(loop, mocker):
mocker.spy(loop, 'create_server')
loop.call_later(0.02, loop.stop)
app = web.Application(loop=loop)
mocker.spy(app, 'startup')
web.run_app(app, print=lambda *args: None)
assert loop.is_closed(... | apache-2.0 | Python |
51cd6a415c1007fc613f2b6ee49a4dd3cfd2f922 | Add a intersect generator test which is known as failing | wikimedia/pywikibot-core,wikimedia/pywikibot-core | tests/thread_tests.py | tests/thread_tests.py | # -*- coding: utf-8 -*-
"""Tests for threading tools."""
#
# (C) Pywikibot team, 2014-2020
#
# Distributed under the terms of the MIT license.
#
from contextlib import suppress
from tests.aspects import unittest, TestCase
from pywikibot.tools import ThreadedGenerator, intersect_generators
class BasicThreadedGenerat... | # -*- coding: utf-8 -*-
"""Tests for threading tools."""
#
# (C) Pywikibot team, 2014-2020
#
# Distributed under the terms of the MIT license.
#
from contextlib import suppress
from tests.aspects import unittest, TestCase
from pywikibot.tools import ThreadedGenerator, intersect_generators
class BasicThreadedGenerat... | mit | Python |
9eedaf6d5567418f82b4240309b73fdd6e057a0f | Fix #597: Boolean fields require default values | matthiask/django-content-editor,matthiask/django-content-editor,matthiask/django-content-editor,matthiask/feincms2-content,matthiask/django-content-editor,mjl/feincms,joshuajonah/feincms,feincms/feincms,mjl/feincms,feincms/feincms,joshuajonah/feincms,mjl/feincms,joshuajonah/feincms,matthiask/feincms2-content,matthiask/... | feincms/module/extensions/featured.py | feincms/module/extensions/featured.py | """
Add a "featured" field to objects so admins can better direct top content.
"""
from __future__ import absolute_import, unicode_literals
from django.db import models
from django.utils.translation import ugettext_lazy as _
from feincms import extensions
class Extension(extensions.Extension):
def handle_model... | """
Add a "featured" field to objects so admins can better direct top content.
"""
from __future__ import absolute_import, unicode_literals
from django.db import models
from django.utils.translation import ugettext_lazy as _
from feincms import extensions
class Extension(extensions.Extension):
def handle_model... | bsd-3-clause | Python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.