content stringlengths 4 20k |
|---|
import sys, os, re, errno
import markdown
import simplejson as json
from cuddlefish import packaging
from cuddlefish import Bunch
from cuddlefish import apiparser
from cuddlefish import apirenderer
INDEX_PAGE = '/static-files/base.html'
BASE_URL_INSERTION_POINT = '<base '
HIGH_LEVEL_PACKAGE_SUMMARIES = '<li id="high-... |
# -*- coding: utf-8 -*
import sys
import random
import subprocess
import Scene
import ScenePath
import Settings
from ToolUtils import ToolUtils
# Imports the monkeyrunner modules used by this program
from com.android.monkeyrunner import MonkeyRunner, MonkeyDevice
supportedDevices = [
{"pName":"1080P Phone","resol... |
""" Tests with-statement behavior of Timeout class. Don't import when
using Python 2.4. """
from __future__ import with_statement
import sys
import unittest
import weakref
import time
from eventlet import sleep
from eventlet.timeout import Timeout
from tests import LimitedTestCase
DELAY = 0.01
class Error(Exception)... |
#!/usr/bin/env python
import os
import subprocess
import sys
from Bio import SeqIO
from Bio.SeqIO import FastaIO
"""
# =============================================================================
Copyright Government of Canada 2018
Written by: Eric Marinier, Public Health Agency of Canada,
National Microbiology... |
from PySide.QtCore import *
from PySide.QtGui import *
import gettext
from gettext import gettext as _
gettext.textdomain('remindor-common')
import logging
logger = logging.getLogger('remindor_qt')
from remindor_qt import helpers
from remindor_common.helpers import QuickDialogInfo
class QuickDialog(QDialog):
a... |
"""
The image test runner is used for image quality and performance testing.
It is designed to process directories of arbitrary test images, using the
directory structure and path naming conventions to self-describe how each image
is to be compressed. Some built-in test sets are provided in the ./Test/Images
directory... |
""" Defines a the DragZoom tool class
"""
# Enthought library imports
from enable.tools.drag_tool import DragTool
from traits.api import Bool, Enum, Float, Tuple
# Chaco imports
from better_zoom import BetterZoom
class DragZoom(DragTool, BetterZoom):
""" A zoom tool that zooms continuously with a mouse drag mov... |
__author__ = 'MatrixRev'
import os
import re
import json
import codecs
from collections import defaultdict
import string
library_path="C://Users//MatrixRev//Desktop//library_12//" # output file path
data_path="C://Users//MatrixRev//Dropbox//data" # input Marc file director
error_log="C://Users//MatrixRev//Desktop//lo... |
""" Tests for the questions list. """
from constants import constants
from core.domain import question_services
from core.domain import skill_services
from core.domain import topic_domain
from core.domain import topic_services
from core.domain import user_services
from core.tests import test_utils
import feconf
clas... |
import os
import subprocess
import textwrap
if __name__ == "__main__":
opt_file = open("cinder/opts.py", 'a')
opt_dict = {}
dir_trees_list = []
REGISTER_OPTS_STR = "CONF.register_opts("
REGISTER_OPT_STR = "CONF.register_opt("
license_str = textwrap.dedent(
"""
# Licensed under ... |
#
# Electronics.py
#
#
# This file currently only contains one class "Resistor" which helps with computations involving resistors.
#
#
import numbers
import math
class Resistor:
"""Simple implementation of a resistor class, that includes checks on the max power of the
combined resistors."""
def __init_... |
# project/server/models.py
"""Write your models here."""
import datetime
from project.server import app, db, bcrypt
class User(db.Model):
"""User model in the database."""
__tablename__ = "users"
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
email = db.Column(db.String(255), uniq... |
"""
PyDev script to trigger pythontidy code formatting on demand
by pressing CTRL + 2 and pt
"""
import tempfile
import os
if False:
from org.python.pydev.editor import PyEdit
cmd = 'command string'
editor = PyEdit
SCRIPT = '/usr/local/bin/PythonTidy'
ACTIVATION_STRING = 'pt'
WAIT_FOR_ENTER = False
cl... |
import unittest
from autothreadharness.harness_case import HarnessCase
class Leader_5_5_7(HarnessCase):
role = HarnessCase.ROLE_LEADER
case = '5 5 7'
golden_devices_required = 3
def on_dialog(self, dialog, title):
if title.startswith('Reset DUT'):
self.dut.stop()
retur... |
#!/usr/bin/env python
# -*- coding: utf8 -*-
"""
Copyright Andrew Wang, 2017
Distributed under the terms of the GNU General Public License.
This 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 ... |
from __future__ import unicode_literals
import os
import subprocess
from django.utils import six
from djblets.util.filesystem import is_exe_in_path
from reviewboard.diffviewer.parser import DiffParser
from reviewboard.scmtools.core import SCMTool
from reviewboard.scmtools.errors import FileNotFoundError, SCMError
... |
import numpy as np
from params import RBMParams, SGDParams
from models.rbm import RBM, RBMTrainer
from vis import RBMTrainingMNIST
import time
import matplotlib.pyplot as plt
# RBM AND TRAINER EXPECT PARAMETER OBJECTS
model_params = RBMParams()
train_params = SGDParams()
# vis_fun = RBMTrainingMNIST()
# vis_fun.visib... |
"""The Netio switch component."""
import logging
from collections import namedtuple
from datetime import timedelta
import voluptuous as vol
from homeassistant.core import callback
from homeassistant import util
from homeassistant.components.http import HomeAssistantView
from homeassistant.const import (
CONF_HOST... |
import time
from app.accessibility_tasks import *
# Do not remove this import. Without it the hook will not be ran
from app.hooks import with_firefox
def open_homes_page():
find_element(homes_page).click()
wait_for_page("homes")
def is_groups_visible():
return find_element(homes_first_group).is_display... |
# accounts low-dimensional cases in 3D
# (NB the PW-based codes are forced to put vacuum in a "non-periodical" direction)
# extends ASE object(s)
# TODO: account all "pseudo-periodic" cases for 1d and 0d
import math
from numpy.linalg import det
from ase.data import chemical_symbols, covalent_radii
# hierarchy API:... |
import os
import json
import getpass
try:
import requests
HAVE_REQUESTS = True
except ImportError:
HAVE_REQUESTS = False
try:
from bs4 import BeautifulSoup
HAVE_BS4 = True
except ImportError:
HAVE_BS4 = False
from viper.common.out import *
from viper.common.abstracts import Module
from viper.... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import copy
import json
import re
import sys
from math import isnan
import six
try:
# 3.8 and up
from collections.abc import Iterable
except ImportError:
from collections import Iterable
def check_if_numbers_are_consecutive(list_):
"""
Returns True ... |
"""Onewire ingest."""
import time
import os
import datetime
os.environ["TZ"] = "CST6CDT"
def main():
"""Go Main Go"""
with open("runner.pid", "w") as fh:
fh.write("%s" % (os.getpid(),))
while 1:
_si, so = os.popen4('./digitemp -q -a -s /dev/ttyS0 -o"%s %.2F"')
d = so.readlines()
... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Sentinel-2 AWS metadata application helper library
#
import re
import os
import sys
import requests
import shutil
import codecs
import simplejson
from datetime import datetime
from xml.dom.minidom import parseString
import pymongo
from pymongo import MongoClient
class R... |
"""
Test cases for the commissaire_http.authentication.AuthenticationManager class.
"""
from unittest import mock
from . import TestCase, create_environ
from commissaire_http import authentication
# The response from dummy_wsgi_app
DUMMY_WSGI_BODY = [bytes('hi', 'utf8')]
# Dummy wsgi app for testing
def dummy_wsgi... |
from marshmallow import Schema, post_dump
from marshmallow.fields import List, Nested, String
from flask.ext.marshmallow.fields import AbsoluteUrlFor as URL, Hyperlinks
from .utils import Length, Polymorphic
# sane defaults
common = ('name', 'id')
class BaseSchema(Schema):
class Meta:
additional = common... |
"""
********************************************************************************
utilities
********************************************************************************
.. currentmodule:: compas_rhino.utilities
layers
======
.. autosummary::
:toctree: generated/
:nosignatures:
create_layers
... |
"""
Tests for .importer module.
"""
import os
import sys
import recursely
from tests._compat import TestCase
TESTS_DIR = os.path.dirname(__file__)
IMPORTED_DIR = os.path.join(TESTS_DIR, 'imported')
def test_imported_dir_is_not_package():
"""Make sure `imported` directory was not made into a package.
The r... |
import os
from setuptools import setup, find_packages
import filemanager
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name='django-filemanager',
version=filemanager.__version__,
description='Template for reusable django applications.',
long_descript... |
from __future__ import with_statement
from functionaltest import FunctionalTest
import key_codes
class Test_2633_CursorKeysMoveAroundGrid(FunctionalTest):
def get_cell_editor_cursor_position(self):
try:
selection_start = int(self.selenium.get_eval("window.$('%s').caret().start" % (self.get_c... |
#!/usr/bin/env python
# encoding: utf-8
"""
Author: Isabel Restrepo
Script to compute centroid from a PLY file
CAUTION! - This method is very memory inefficient
"""
import os
import sys
import numpy as np
from scipy import stats
import argparse
def compute_mean(file_in, lines2skip=16):
fid = open(file_in, 'r')
xy... |
import datetime
from mongoengine import Document
from mongoengine import ObjectIdField, StringField, ListField
from django.conf import settings
from cripts.core.fields import CriptsDateTimeField
from cripts.core.cripts_mongoengine import CriptsDocument, CriptsSchemaDocument
class Notification(CriptsDocument, Cripts... |
"""
Copyright 2015 Enzo Busseti
This file is part of CVXPY.
CVXPY 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 License, or
(at your option) any later version.
CVXPY is distributed in ... |
"""Git Archive dialog"""
from __future__ import division, absolute_import, unicode_literals
import os
from qtpy import QtCore
from qtpy import QtWidgets
from qtpy.QtCore import Qt
from qtpy.QtCore import Signal
from ..git import git
from ..git import STDOUT
from ..i18n import N_
from ..interaction import Interaction
... |
from src.base.solution import Solution
from src.tests.part1.q310_test_min_height_trees import MinHeightTreesTestCases
class MinHeightTrees(Solution):
def verify_output(self, test_output, output):
return set(test_output) == set(output)
def print_output(self, output):
super(MinHeightTrees, self... |
# -*- coding: utf8 -*-
"""
.. module:: burpui.misc.parser.openssl
:platform: Unix
:synopsis: Burp-UI configuration file parser OpenSSL configuration.
.. moduleauthor:: Ziirish <<EMAIL>>
"""
import os
import re
import codecs
import subprocess
from hashlib import md5
from OpenSSL import crypto
from ...tools.log... |
import os
import os.path
import tempfile
import shutil
from nose.tools import eq_
from build_pack_utils import utils
from compile_helpers import setup_webdir_if_it_doesnt_exist
from compile_helpers import convert_php_extensions
from compile_helpers import build_php_environment
from compile_helpers import is_web_app
fro... |
import copy
import re
from typing import List, Sequence
import dataproperty as dp
import typepy
from dataproperty import ColumnDataProperty, DataProperty, LineBreakHandling
from mbstrdecoder import MultiByteStrDecoder
from ...style import Align
from ...style._styler import get_align_char
from ._text_writer import Tex... |
from __future__ import absolute_import
from envisage.ui.tasks.preferences_category import PreferencesCategory
from envisage.ui.tasks.preferences_dialog import PreferencesDialog as PD, PreferencesTab
from pyface.tasks.topological_sort import before_after_sort
from traits.api import on_trait_change, Property
from traits... |
#!/usr/bin/env python
#coding:utf-8
import os.path
import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.web
from tornado.options import define, options
define("port", default=8203, help="run on the given port", type=int)
class IndexHandler(tornado.web.RequestHandler):
def get(se... |
"""fix#1
Revision ID: 8ca3928ef055
Revises: 63cb00d5fde5
Create Date: 2016-01-16 21:12:50.229331
"""
# revision identifiers, used by Alembic.
revision = '8ca3928ef055'
down_revision = '63cb00d5fde5'
from alembic import op
import sqlalchemy as sa
def upgrade():
### commands auto generated by Alembic - please a... |
#!/usr/bin/python
'''
Part of the Qt-Deployment scripts
@package qt-release
'''
import github3
import sys
import getpass
import os
import mimetypes
import re
import argparse
import ConfigParser
def printInfo(text):
sys.stdout.write(text)
sys.stdout.flush()
class QtRelease:
def __init__(self):
s... |
# -*- coding: utf-8 -*-
import os.path
import urllib.request, urllib.error, urllib.parse
import sys
from fabric.api import cd, put
from .versions import (getOutwikerVersion,
readAppInfo,
downloadAppInfo)
from .libs.colorama import Fore
from .buildfacts import BuildFacts
... |
import datetime
import json
import uuid
import mock
import netaddr
from oslo.config import cfg
from testtools import matchers
import webob.exc
from neutron.api import extensions
from neutron.api.v2 import attributes as attr
from neutron.api.v2 import base as api_base
from neutron.common import exceptions as exc
from ... |
"""Experimental shader functions.
Building and using a shader fuction:
from miru.shader import *
vs = VertexShader(data)
fs = FragmentShader(data)
program = createProgram(vs, fs)
...
@stability: unstable
"""
from pyglet import gl
import pyglet
import ctypes as c
from miru import imiru
from z... |
"""
Example shows lifecycle (Create-Read-Update-Delete) of a Partition.
"""
import sys
import logging
import yaml
import json
import requests.packages.urllib3
from pprint import pprint
import zhmcclient
requests.packages.urllib3.disable_warnings()
if len(sys.argv) != 2:
print("Usage: %s hmccreds.yaml" % sys.arg... |
# This example show how to write an inline mode telegramt bot use pyTelegramBotAPI.
import telebot
import time
import sys
import logging
from telebot import types
API_TOKEN = '<TOKEN>'
bot = telebot.TeleBot(API_TOKEN)
telebot.logger.setLevel(logging.DEBUG)
@bot.inline_handler(lambda query: query.query == 'text')
de... |
"""Data Equivalence Tests"""
from __future__ import print_function
# Authors: Teon Brooks <<EMAIL>>
# Martin Billinger <<EMAIL>>
# Alan Leggitt <<EMAIL>>
# Alexandre Barachant <<EMAIL>>
#
# License: BSD (3-clause)
import os.path as op
import inspect
import warnings
from nose.tools import a... |
#!/usr/bin/python
# -*- coding: UTF-8 -*-
# BEGIN PYTHON 2/3 COMPATIBILITY BOILERPLATE
from __future__ import absolute_import
from __future__ import with_statement
from __future__ import division
from __future__ import nested_scopes
from __future__ import generators
from __future__ import unicode_literals
from __future... |
"""Configuration panel."""
import logging
from os.path import isfile
from qgis.core import Qgis, QgsProject
from QuickOSM.core.exceptions import FileDoesntExistException
from QuickOSM.core.parser.osm_parser import OsmParser
from QuickOSM.core.process import open_file
from QuickOSM.definitions.gui import Panels
from... |
"""setuptools-based installation script. """
from setuptools import find_packages
from setuptools import setup
setup(
name='dview',
version='0.0.0',
description='Viewer for dsub workflow execution graphs',
url='https://github.com/jbingham/dview',
author='Jonathan Bingham',
author_email='<EMAIL>',
licens... |
# -*- coding: utf-8 -*-
"""Enhancements for Behave.
Some of them might be proposed upstream
"""
import os.path
from behave import formatter
from behave import matchers
from behave import model
from behave import runner
from behave.formatter.ansi_escapes import up
from behave.model_describe import escape_cell, escape_... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import argparse
import json
import os
from random import randint
from threading import Thread
import time
import model
import pygame
from pygame.locals import *
import queue
APPLE_COLOR = pygame.Color('red')
S... |
from couchpotato.core.logger import CPLog
from couchpotato.core.notifications.base import Notification
log = CPLog(__name__)
class Trakt(Notification):
urls = {
'base': 'http://api.trakt.tv/%s',
'library': 'movie/library/%s',
'unwatchlist': 'movie/unwatchlist/%s',
}
listen_to = [... |
from app import db
from app.models import Nodes, LastEntry, AppSettings, Sensors, SensorData
import sqlalchemy
import datetime
__author__ = 'Lesko'
# Documentation is like sex.
# When it's good, it's very good.
# When it's bad, it's better than nothing.
# When it lies to you, it may be a while before you realize some... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from kokemomo.plugins.engine.controller.km_engine import KMEngine
from kokemomo.plugins.engine.controller.km_exception import log as log_error
from kokemomo.plugins.engine.controller.km_login import KMLogin
from kokemomo.plugins.engine.model.km_user_table import KMUser
fr... |
# -*- coding: utf-8 -*-
import scrapy
from locations.items import GeojsonPointItem
import json
class WholeFoodsSpider(scrapy.Spider):
name = "whole_foods"
allowed_domains = ["www.wholefoodsmarket.com"]
start_urls = (
'https://www.wholefoodsmarket.com/ajax/stores',
)
def parse_phone(self, p... |
#!/usr/bin/env python
# Tests accessing of instruction operands.
import sys
import os
import llvm
# top-level, for common stuff
from llvm.core import *
# Get the name of an LLVM value
def get_name(val) :
if (not isinstance(val, Value)):
return ''
if isinstance(val, Argument):
#return val.name... |
''' gamma function and its natural logarithm'''
##/* @(#)er_lgamma.c 5.1 93/09/24 */
##/*
## * ====================================================
## * Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved.
## *
## * Developed at SunPro, a Sun Microsystems, Inc. business.
## * Permission to use, copy, modi... |
from ..waveform_control import pulsar
from ..waveform_control import pulse
from ..waveform_control import element
from ..waveform_control import sequence
from ..waveform_control.viewer import show_element, show_wf
from ..waveform_control import pulse_library as pl
from . import standard_elements_cbox as st_elts
from i... |
import kol.Error as Error
from kol.util import Report
class GenericRequest(object):
"A generic request to a Kingdom of Loathing server."
def __init__(self, session):
self.session = session
self.requestData = {}
self.skipParseResponse = False
self.get = False
def doRequest... |
"""
mbed CMSIS-DAP debugger
Copyright (c) 2006-2015 ARM Limited
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 ... |
'''
Created on 14 feb. 2016
@author: davandev
'''
import logging
import os
global logger
logger = logging.getLogger(os.path.basename(__file__))
def getUserHomeUrl(config, user):
'''
Return the url to the fibaro scene to activate the user presence
'''
home_url = ""
if user == "M... |
from __future__ import print_function
from operator import mul as mul_op
from functools import reduce
from random import choice
import pandas as pd
from collections import abc
def is_list_like(obj, allow_sets=False, allow_dict=False):
return (isinstance(obj, abc.Iterable) and
not isinstance(obj, (str, by... |
from pathlib import Path
from template_tests.test_response import test_processor_name
from django.template import Context, EngineHandler, RequestContext
from django.template.backends.django import DjangoTemplates
from django.template.library import InvalidTemplateLibrary
from django.test import RequestFactory, overri... |
from django.test import TestCase
from .utils import extruct_domain, extruct_l2_domain
from .cache import UserCache, DomainCache, DomainFilterCache
class ExtructDomainTestCase(TestCase):
def test_simple(self):
# http
domain_name = extruct_domain('http://test')
self.assertEqual(domain_nam... |
#!/usr/bin/env python
#coding=utf8
'''
Given a string that consists of only uppercase English letters, you can replace any letter in the string with another letter at most k times. Find the length of a longest substring containing all repeating letters you can get after performing the above operations.
Note:
Both the... |
import json
from django.http import HttpResponse
from django.views.decorators.http import require_POST
from django.views.decorators.csrf import csrf_exempt
from tapiriik.auth import User
from tapiriik.sync import Sync, SynchronizationTask
from tapiriik.database import db
from tapiriik.services import Service
from tapir... |
#!/usr/bin/env/python
"""
Setup script for PuLP added by Stuart Mitchell 2007
Copyright 2007 Stuart Mitchell
"""
import sys
from ez_setup import use_setuptools
use_setuptools()
from setuptools import setup
Description = open('README').read()
License = open('LICENSE').read()
# read the version number safely from the ... |
import sys
import PyQt5.QtWidgets
import qdarkstyle
import PyQt5.QtWidgets
class Example(PyQt5.QtWidgets.QWidget):
def __init__(self):
super().__init__()
self.init_ui()
def init_ui(self):
grid = PyQt5.QtWidgets.QGridLayout()
self.setLayout(grid)
# list = [] names = [list-item_0, list-item_1, lis... |
import copy
import futurist
from futurist import waiters
from oslo_config import cfg
from oslo_log import log
from oslo_service import service
CONF = cfg.CONF
LOG = log.getLogger(__name__)
class DecisionEngineThreadPool(object, metaclass=service.Singleton):
"""Singleton threadpool to submit general tasks to"""
... |
import io
from mock import MagicMock
from tests.helper.voctomix_test import VoctomixTest
from gi.repository import Gst
from lib.sources import TCPAVSource
from lib.config import Config
# noinspection PyUnusedLocal
class AudiomixMultipleSources(VoctomixTest):
def setUp(self):
super().setUp()
Con... |
import pyaudio
import numpy as np
import matplotlib.pyplot as plt
import struct
import SignalUtils as su
from sklearn.preprocessing import MinMaxScaler
from keras.models import Sequential
from keras.layers import Dense, Conv1D, BatchNormalization, MaxPool1D, Flatten, Dropout
# constants
CHUNK = 16000 ... |
'''simpler & deprecated python script controllers'''
import Sofa
import inspect
def deprecated(cls):
# TODO maybe we should print a backtrace to locate the origin?
# or even better, use: https://docs.python.org/2/library/warnings.html#warnings.warn
line = '''class `{0}` from module `{1}` is deprecated. Y... |
# -*- coding: utf-8 -*-
from time import sleep
import threading
import logging
from datetime import datetime
class CSDevice:
"""Stores information about a single device connected
to GPIO"""
# Type "enum"
typeDht = "DHT"
typeLED = "LED"
typeSwitch = "Switch"
typeNone = "None"
# Mode "... |
from django import template
from tracking.models import Visitor
import re
register = template.Library()
class VisitorsOnSite(template.Node):
"""
Injects the number of active users on your site as an integer into the context
"""
def __init__(self, varname, same_page=False):
self.varname = varna... |
from __future__ import print_function, absolute_import
import time
import logging
from licensedcode.whoosh_spans.spans import Span
from textcode import analysis
from licensedcode import index
from licensedcode.models import get_all_rules
from licensedcode import models
logger = logging.getLogger(__name__)
# import... |
import pymysql
from pymysql.tests import base
import unittest
import sys
try:
import imp
reload = imp.reload
except AttributeError:
pass
import datetime
# backwards compatibility:
if not hasattr(unittest, "skip"):
unittest.skip = lambda message: lambda f: f
class TestOldIssues(base.PyMySQLTestCase)... |
import os
import sys
import gtk
import gobject
import gnomevfs
import gettext
import shutil
import subprocess
from userdir import UserdirFile
from common.consts import *
from common.widgets import ErrorDialog
class FileChooserDialog(gtk.FileChooserDialog):
"""Show a dialog to select a folder, or to do more thing
... |
import unittest
import warnings
import mxnet as mx
def test_print_summary():
data = mx.sym.Variable('data')
bias = mx.sym.Variable('fc1_bias', lr_mult=1.0)
emb1= mx.symbol.Embedding(data = data, name='emb1', input_dim=100, output_dim=28)
conv1= mx.symbol.Convolution(data = emb1, name='conv1', num_fil... |
"""Tests for chords_lib."""
# internal imports
import tensorflow as tf
from magenta.common import testing_lib as common_testing_lib
from magenta.music import chord_symbols_lib
from magenta.music import chords_lib
from magenta.music import constants
from magenta.music import melodies_lib
from magenta.music import sequ... |
# -*- coding: utf-8 -*-
"""Tests for Hunk."""
import os.path
import unittest2
from nlg4patch.unidiff.patch import Hunk
class TestHunk(unittest2.TestCase):
"""Tests for Hunk."""
def setUp(self):
self.sample_line = 'Sample line'
def test_default_is_valid(self):
hunk = Hunk()
... |
import asyncio
import os
import socket
from unittest import mock
import pytest
from blackhole import protocols
from blackhole.child import Child
from blackhole.control import _socket
from blackhole.streams import StreamProtocol
from ._utils import ( # noqa: F401; isort:skip
Args,
cleandir,
create_confi... |
import socket
import ssl
import errno
from time import time
from . import logging
from .protocol import HANDSHAKE_PACKET
# Global connector registry.
# Fill by calling registerConnectorHandler.
# Read by calling SocketConnector.__new__
connector_registry = {}
def registerConnectorHandler(connector_handler):
connec... |
from setuptools import setup, find_packages
long_description = "\n".join(
(
open("README.rst", encoding="utf-8").read(),
open("CHANGES.txt", encoding="utf-8").read(),
)
)
setup(
name="more.transaction",
version="0.9.dev0",
description="transaction integration for Morepath",
lon... |
"""\
=================================================================
Compile EIT schedule and present-following tables from a schedule
=================================================================
Aim of this code is to compile some DVB SI table sections representing an EIT
schedule (EPG) and present-following (... |
#!/usr/bin/env python
from setuptools import setup, find_packages
with open('README.rst') as f:
README = f.read()
VERSION = "0.3.5"
setup(
name = "python-congress",
packages=find_packages(exclude=['docs']),
version = VERSION,
description = "A Python client for the ProPublica Congress API",
... |
from itertools import combinations
from random import randint, uniform
# Kendell's Tao distance between vector v and u
def kendall_tau(v, u):
pairs = combinations(v, 2)
dist = 0
for x, y in pairs:
a = v.index(x) - v.index(y)
b = u.index(x) - u.index(y)
# if discordant (different si... |
#!/usr/bin/python
import versioning_base
import psycopg2
import os
import shutil
def prtTab( cur, tab ):
print "--- ",tab," ---"
pcur.execute("SELECT pid, trunk_rev_begin, trunk_rev_end, trunk_parent, trunk_child, length FROM "+tab)
for r in pcur.fetchall():
t = []
for i in r: t.append(str(... |
"""
* File: consumer.py
* Description: This is the MQTT consumer handles incoming messages
* published by producers from a particular topic.
* Consumer prints the topic and payload as it receives messages.
*
* Author: Eamin Zhang
* robomq.io (http://www.robomq.io)
"""
import time
import paho.mqtt.client... |
import sys
import os
import re
import urllib
import uuid
import hashlib
from urllib.parse import urlparse
from MimeExt import *
def byteToInt(b):
return int.from_bytes(b, byteorder='little')
def isCacheInitialized(addr):
"""
Cache address is initialized if the first bit is set
"""
return (int... |
"""
Django settings for iConnect project.
Generated by 'django-admin startproject' using Django 1.10.6.
For more information on this file, see
https://docs.djangoproject.com/en/1.10/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.10/ref/settings/
"""
import o... |
#!/usr/bin/env python
import os.path
from flask import Flask, session, request, url_for, redirect, render_template, g, abort
#import sqlite3
import random
import threading
import webbrowser
import argparse
import sys
import main
import TOOLS.Config as cfg
app = Flask(__name__)
instance = None
cmd_loc = N... |
"""
Base class for Scrapy spiders
See documentation in docs/topics/spiders.rst
"""
import logging
import warnings
from scrapy import signals
from scrapy.http import Request
from scrapy.utils.trackref import object_ref
from scrapy.utils.url import url_is_from_spider
from scrapy.utils.deprecate import create_deprecated... |
from __future__ import nested_scopes
import os
def set_trace_in_qt():
from _pydevd_bundle import pydevd_tracing
from _pydevd_bundle.pydevd_comm import get_global_debugger
debugger = get_global_debugger()
if debugger is not None:
pydevd_tracing.SetTrace(debugger.trace_dispatch)
_patched_qt = F... |
from collections import defaultdict
from contextlib import contextmanager
import os
import plistlib
import re
import threading
import yaml
import sublime
MYPY = False
if MYPY:
from typing import DefaultDict, List, Optional
if 'syntax_file_map' not in globals():
syntax_file_map = defaultdict(list) # type: ... |
from __future__ import unicode_literals
import inspect
import re
from django.db.backends.postgresql_psycopg2 import schema
from ...schema import is_shared_model, is_shared_table
from ...schema import get_schema_model, _schema_table_exists
from ...schema import deactivate_schema, activate_template_schema
def in_app... |
from __future__ import absolute_import, unicode_literals
from django.apps import apps
from django.dispatch import receiver
try:
from django.channels import Channel
except ImportError:
from channels import Channel
from .models import VM, GazonEntry
stratus_app = apps.get_app_config('stratus')
signals = strat... |
from .mobiusbase import MobiusBase, standardmap
from .circle import Circle
from .zline import Zline
from .disk import Disk
import numpy as np
import numpy.linalg
class Mobius(MobiusBase):
"""Create a Mobius transform
"""
def __init__(self, **kwargs):
super(Mobius, self).__init__(**kwargs)
@s... |
from burst.exception import CookieException
class Cookie:
@classmethod
def parse(cls, header, set_cookie=False):
if set_cookie:
if ";" in header:
nvp, attributes = header.split(";", 1)
else:
nvp, attributes = header, ""
if not "=" in nvp:
raise CookieException("No '='... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.