code stringlengths 1 199k |
|---|
from bs4 import BeautifulSoup as BS
from collections import OrderedDict
from lxml import etree
import json
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
def parse_html_by_BeautifulSoup(html_content):
'''
从房价HTML页面中解析出房价数据,返回一个以城市名为key、房价为vlaue的字典
:param html_content: 房价HTML网页内容
:return: 以城市名为ke... |
import sqlite3
class Database(object):
def __init__(self, path, config):
self.config = config
self.path = path
connection = sqlite3.connect(path, isolation_level=None)
cursor = connection.cursor()
for attr in ('execute', 'executescript', 'fetchone', 'fetchall'):
s... |
from f6a_tw_crawler.constants import *
import unittest
import logging
from f6a_tw_crawler import util_pd
class TestUtilPd(unittest.TestCase):
def setUp(self):
pass
def tearDown(self):
pass |
import argparse
from .cmd import Cmd
from ..configs import configs
def add_parser(subparsers):
parser = subparsers.add_parser('configs')
parser.set_defaults(func=Configs)
parser.add_argument('--run-args',
default='',
help='arguments to pass to run command')
... |
"""
Django settings for scoreserver project.
Generated by 'django-admin startproject' using Django 1.10.4.
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 os... |
from __future__ import unicode_literals
import six
import requests
from django.conf import settings
from django.core.mail.backends.base import BaseEmailBackend
from django.core.mail.message import sanitize_address
from requests.packages.urllib3.filepost import encode_multipart_formdata
__version__ = '0.7.1'
version = '... |
"""Perform tasks defined in a Makefile.py in the current or parent
directories.
"""
import os
from os.path import exists, dirname, abspath, join, basename
import sys
import re
from pprint import pprint
import glob
import logging
import optparse
import time
import traceback
from mklib.common import *
from mklib.makefile... |
"""pymoku example: Basic Laser Lock Box
This example demonstrates how you can configure the laser lock box
instrument
(c) 2019 Liquid Instruments Pty. Ltd.
"""
from pymoku import Moku
from pymoku.instruments import LaserLockBox
from scipy import signal
def gen_butterworth(corner_frequency):
"""
Generate coeffic... |
from django.conf import settings
from hardware.administration import models
class GlobalSettingsMiddleware(object):
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
request.private = settings.PRIVATE
try:
bitcoin_address = models... |
import sys
for line in sys.stdin:
a, b = map(int, line.split())
print(a ^ b) |
"""
80. Remove Duplicates from Sorted Array II
https://leetcode.com/problems/remove-duplicates-from-sorted-array-ii/
"""
from typing import List
class Solution:
def removeDuplicates(self, nums: List[int]) -> int:
last = 0
for num in nums:
if last < 2 or num > nums[last-2]:
... |
import urllib.request, urllib.error, urllib.parse
import json
import base64
import sys, os
import datetime
import argparse, configparser
import query
__location__ = os.path.realpath(os.path.join(os.getcwd(), os.path.dirname(__file__)))
default_config_file = os.path.join(__location__, 'config.ini')
config = configparser... |
""" Admin file """
from django.contrib import admin
from app.logic.logger.models.LogModel import LogEntry
admin.site.register(LogEntry) |
import codecs
def bytes_to_hex_str(arg_bytes):
return codecs.encode(arg_bytes,'hex').decode('ascii')
def hex_str_to_bytes(arg_str):
return codecs.decode(arg_str.encode('ascii'),'hex') |
"""
The MIT License (MIT)
Copyright (c) 2014 Leonardo Kewitz
Exemplo de processamento de uma imagem RGB utilizando numpy.
"""
from numpy import *
from scipy import misc
import matplotlib.pyplot as plt
image = misc.imread('./src/maddog.jpg')
alt, lag, c = image.shape
image[:,:,1] = zeros((alt,lag))
image[:,:,2] = zeros(... |
import pmisc
from pmisc import AE, RE
import pytest
import pcsv
from tests.fixtures import (
common_exceptions,
write_file,
write_input_file,
write_replacement_file,
)
def test_concatenate():
"""Test concatenate function behavior."""
# In place replacement
with pmisc.TmpFile(write_input_file... |
from __future__ import unicode_literals
from django.db import migrations
def load_tipoevento_from_fixture(apps, schema_editor):
from django.core.management import call_command
call_command("loaddata", "0017_tipoevento_loaddata")
def delete_tipoevento(apps, schema_editor):
tipoevento = apps.get_model("servic... |
def init():
from example.app import app as app_, db
with app_.test_request_context() as ctx:
db.create_all()
if __name__ == "__main__":
init() |
import logging
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters
from modules.gifsapm import GifsApmHandler
from modules.estraviz import EstravizHandler
from modules.dice import DiceHandler
logging.basicConfig(format='[%(asctime)s] [%(name)s] [%(levelname)s] %(message)s',
lev... |
from .error_details import ErrorDetails, ErrorDetailsException
from .create_device_request import CreateDeviceRequest
from .authentication import Authentication
from .symmetric_key import SymmetricKey
from .device_description import DeviceDescription
__all__ = [
'ErrorDetails', 'ErrorDetailsException',
'CreateD... |
import re
def word_gen(fn):
with open(fn, 'rb') as text:
splitter = re.compile(r'[\s.,?;!]+')
for line in text:
words = splitter.split(line)
for word in words:
yield word.lower()
def count_words(fn):
counts = {}
for word in word_gen(fn):
try:
... |
import pygame
from configuraciones import *
class Proyectil(pygame.sprite.Sprite):
def __init__(self, dir, col = VERDE):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.Surface([5, 5])
self.image.fill(col)
self.rect = self.image.get_rect()
self.dir = dir
self.... |
import os
from flask import Flask, Response
from twilio.jwt.client import ClientCapabilityToken
app = Flask(__name__)
@app.route('/token', methods=['GET'])
def get_capability_token():
"""Respond to incoming requests."""
# Find these values at twilio.com/console
account_sid = os.environ['TWILIO_ACCOUNT_SID']... |
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('isisdata', '0057_auto_20170324_1729'),
]
operations = [
migrations.AddField(
model_name='historicaltracking'... |
import logging
class Logger():
"""
Create logger instance for writing to both console and a local file.
Parameters
----------
filepath : str, optional
Specify a log filename with the absolute path.
If not given, no output is written to a file.
"""
def __init__(self, filepath=... |
from setuptools import setup
from setuptools import find_packages
setup(name='borg-summon',
version='0.1',
description='A work-in-progress wrapper for automating BorgBackup use',
url='https://github.com/grensjo/borg-summon',
author='Anton Grensjö',
author_email='anton@grensjo.se',
license='MIT',... |
import re
__symbols__ = u"()[]{}"
__symbols__ += u"+-×÷"
__symbols__ += u"⍺⍵"
__symbols__ += u"⍳⍴"
__symbols__ += u"←"
__name__ = u"([A-Za-z∆⍙][A-Za-z0-9∆⍙¯_]*)" # Constructed Names
__name__ += u"|(¯?[0-9]+\.[0-9]*)|(¯?\.?[0-9]+)" # Floats or Integers
__name__ = re.compile(__name__)
class __APL_type__:
def __ini... |
import os
path = os.path.dirname(os.path.realpath(__file__))
sbmlFilePath = os.path.join(path, 'BIOMD0000000058.xml')
with open(sbmlFilePath,'r') as f:
sbmlString = f.read()
def module_exists(module_name):
try:
__import__(module_name)
except ImportError:
return False
else:
return... |
import cloud_sptheme as csp
import jupytext
project = "Scientific python tutorial"
copyright = "David J Pine"
author = "David Pine"
version = ""
release = "1.0"
extensions = [
"nbsphinx",
"sphinx.ext.mathjax",
]
templates_path = ["_templates"]
source_suffix = ['.rst', '.md']
master_doc = "index"
language = None... |
"""nmrcen URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.8/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based... |
"""Kwalitee checks for PEP8, PEP257, PyFlakes and License."""
from __future__ import unicode_literals
import os
import re
import pep8
import codecs
import pep257
import pyflakes
import pyflakes.checker
import tokenize
from datetime import datetime
SUPPORTED_FILES = '.py', '.html', '.tpl', '.js', '.jsx', '.css', '.less'... |
from local_system import LocalSystem
from remote_system import RemoteSystem
import logging
import util
import traceback
import sys
class MysqlDB():
def __init__(self, config):
self.logger = logging.getLogger(__name__)
self.config = config.get_config_list()
self.localsystem = LocalSystem(config)
self.remotesyst... |
import sys
sys.path.append("designer")
from beetypes import *
import PyQt4.QtCore as qtcore
import PyQt4.QtGui as qtgui
from beeutil import *
from LayerWidgetUi import Ui_LayerConfigWidget
from LayersWindowDockUi import Ui_LayersWindow
from beeapp import BeeApp
from beeeventstack import *
from abstractbeewindow import ... |
"""
Lorum ipsum
Usage:
keeponlyreadmes [options] <target_dir>
Options:
-h --help Show this screen.
author : rabshakeh (erik@a8.nl)
project : ghresearch
created : 21-05-15 / 22:12
"""
from arguments import Arguments
import os
class IArguments(Arguments):
"""
IArguments
"""
def __init__(self, doc... |
import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *
class Digits(QWidget):
Slide, Flip, Rotate = range(3)
def __init__(self, parent):
QWidget.__init__(self, parent)
self.m_number = 0
self.m_transition = self.Slide
self.m_pixmap = QPixmap()
self.m_lastPixmap = ... |
"""Zenodo - Research. Shared."""
import os
from setuptools import find_packages, setup
readme = open('README.rst').read()
history = open('CHANGES.rst').read()
tests_require = [
'check-manifest>=0.35',
'coverage>=4.4.1',
'isort>=4.2.15',
'mock>=2.0.0',
'pydocstyle>=2.0.0',
'pytest-cache>=1.0',
... |
import xml.etree.ElementTree as etree
'''
To add attributes to the newly created element, pass a dictionary of attribute names and values in the
attrib argument. Note that the attribute name should be in the standard ElementTree format, {namespace}localname
'''
new_feed = etree.Element('{http://www.w3.org/2005/Atom}fee... |
import sys
import calcoohija
if __name__ == "__main__":
fichero = open(sys.argv[1], 'r')
#leo todo el fichero
lista_lineas = fichero.read()
#creamos una lista de lineas sin salto de linea
lista_lineas = lista_lineas.splitlines()
miCalculadora = calcoohija.CalculadoraHija()
#recorro la lista ... |
"""
python ordered dictionnary
Copyright (C) 2012 sipdbg@member.fsf.org
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This pro... |
import re
from django.conf import settings
from theming.core import Theme, ThemeManager
class ThemingMiddleware(object):
theme_manager = ThemeManager()
def process_request(self, request):
settings.request_handler = request
request.theme = self.theme_manager.get_default()
theme_config = g... |
class SnakTestCase():
def new_instance(self):
raise NotImplementedError('Deriving classes should implement this method')
def test_can_construct(self):
self.new_instance()
def test_get_type_returns_string(self):
self.assertIsInstance(self.new_instance().getType(), str) |
from django.db import models
from django.contrib.gis.db import models as geo_models
class CoastlinePolygons(geo_models.Model):
plateid1 = geo_models.DecimalField(max_digits=10, decimal_places=0, blank=True, null=True)
fromage = models.DecimalField(max_digits=65535, decimal_places=65535, blank=True, null=True)
... |
import json
import time
from core.Core import Core
from pprint import pprint
class Morphux:
# Construct function
# @param path of the config file (Optional)
def __init__(self, path = "/etc/morphux/configBot.json"):
fd = open(path)
self.config = json.load(fd)... |
"""Script for unittesting the mcpu module"""
import unittest
from ganeti import mcpu
from ganeti import opcodes
from ganeti.constants import \
LOCK_ATTEMPTS_TIMEOUT, \
LOCK_ATTEMPTS_MAXWAIT, \
LOCK_ATTEMPTS_MINWAIT
import testutils
class TestLockAttemptTimeoutStrategy(unittest.TestCase):
def testConstants... |
import urllib, sys, re, random, socket, time, urllib2, string, sets
def title():
print "\n\t d3hydr8[at]gmail[dot]com EmailCollecter v1.2"
print "\t--------------------------------------------------\n"
def timer():
now = time.localtime(time.time())
return time.asctime(now)
def StripTags(text):
finished = 0
... |
from django.db import models
class MaternalPostFuDxTManager(models.Manager):
def get_by_natural_key(self, post_fu_dx, report_datetime, visit_instance, code, subject_identifier_as_pk):
MaternalPostFuDx = models.get_model('mb_maternal', 'MaternalPostFuDx')
maternal_post_fu_dx = MaternalPostFuDx.object... |
import xmlrpclib
import sys
import getpass
class RHNClient(object):
def __init__(self, serverURL):
self.url = serverURL
def connect(self, user=None, password=None):
self.server = xmlrpclib.ServerProxy(self.url)
if user == None or password == None:
user, password = self.auth()... |
"""
Dual Button Plugin
Copyright (C) 2018 Olaf Lüke <olaf@tinkerforge.com>
dual_button_v2.py: Dual Button V2 Plugin Implementation
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of t... |
"""
BuiltInBlocks imports the iDevice blocks which are built-in (i.e. not
plugins) to eXe
"""
from exe.webui.freetextblock import FreeTextBlock
from exe.webui.genericblock import GenericBlock
from exe.webui.multichoiceblock import MultichoiceBlock
from exe.webui.reflectionblock import Re... |
import distutils
import os
import errno
import shutil
import zipfile
import subprocess
import re
import globals as gv
__author__ = "Dulip Withanage"
__email__ = "dulip.withanage@gmail.com"
from debug import Debuggable
from teimanipulate import TeiManipulate
from lxml import etree
class DocxToTei(Debuggable):
def __... |
import json
from pprint import pprint
from collections import defaultdict, Counter
with open('music_old.json') as original_file:
music_data = json.load(original_file)
class JsonTree(object):
def __init__(self, data, parent_name):
self.path = []
self.name = parent_name
self.result = defau... |
from collections import defaultdict
from functools import partial
from itertools import chain, filterfalse
from britney_util import iter_except
class InstallabilityTester(object):
def __init__(self, universe, revuniverse, testing, broken, essentials,
safe_set, eqv_table):
"""Create a new in... |
import base64
import hmac
import string
from hashlib import sha1
from Crypto.Cipher import AES
import time
from datetime import datetime, date, timedelta
from decimal import Decimal
import hashlib
import json
import random
import re
class PropDict(dict):
"""A dict that allows for object-like property access syntax.... |
from django.utils.translation import ugettext as _
from django.http import HttpResponseForbidden
from itkufs.accounting.models import Group
def limit_to_group(function):
def wrapped(request, *args, **kwargs):
# Let admin through immediately
assert "is_admin" in kwargs
if kwargs["is_admin"]:
... |
import sys
import re
import os
import string
import urllib2
import datetime
import getopt
import bs4
sys.path.append(".")
from internal.common_inf import *
def digit_full_with_space(digit, length):
#fmt = "%" + ("%d"%(length)) + "d"
fmt = "%%%dd"%(length)
d_v = fmt%(digit)
return d_v
def full_with_space(digit, leng... |
from zope.component import adapts
from zope.interface import implements
from Products.Zuul.interfaces import IReportable
from ZenPacks.zenoss.ZenETL.reportable import Reportable, DEFAULT_STRING_LENGTH
from ZenPacks.zenoss.OpenVZ.Container import Container
class BaseReportable(Reportable):
implements(IReportable)
... |
"""
***************************************************************************
ProcessingConfig.py
---------------------
Date : August 2012
Copyright : (C) 2012 by Victor Olaya
Email : volayaf at gmail dot com
***********************************************... |
from tkinter import *
import tkinter.messagebox as tm
import pickle
import support
users = {}
class LoginFrame(Frame):
def __init__(self, master):
super().__init__(master)
self.username_label = Label(self, text="Username")
self.password_label = Label(self, text="Password")
self.user_... |
import os
import sys
import subprocess
import re
from setuptools import setup, find_packages
from setuptools.command.sdist import sdist as _sdist
from setuptools.command.install import install as _install
VERSION_PY = """
__version__ = '%s'
"""
def update_version_py():
if not os.path.isdir(".git"):
print("T... |
__version__ = "0.0.1"
__license__ = """The GNU General Public License (GPL-2.0)"""
__author__ = "Sebastian Rojo <http://www.sapian.com.co> arpagon@gamil.com"
__contributors__ = []
_debug = 0
import os
import logging
from optparse import OptionParser
import csv
import collections
from weakref import proxy
from math impo... |
import re
class TemplateReplacer(object):
""" Replaces parameter values in a mwparserfromhell.Template node while
preserving its whitespace.
"""
def __init__(self, template):
self.template = template
def get_value(self, name):
return self.template.get(name).value
def set_valu... |
import shutil
import pytest
import numpy as np
import os.path
import random
import tensorflow.compat.v1 as tf
import deepplantphenomics as dpp
from deepplantphenomics import loaders, layers
from deepplantphenomics.tests.mock_dpp_model import MockDPPModel
@pytest.fixture(scope="module")
def test_data_dir():
return o... |
from datetime import datetime
from py_arduino.main_utils import BaseMain
NON_STREAMING_READS = 400
STREAMING_READS = 1000
def nsar(arduino):
start_analogRead = datetime.now()
for i in xrange(0, NON_STREAMING_READS): # @UnusedVariable
arduino.analogRead(0)
end_analogRead = datetime.now()
analogR... |
import datetime
import Queue
import threading
import time
class LcdUi:
def __init__(self, lcd, max_idle=60):
self._lcd = lcd
self._frame_stack = []
self._last_paint = None
self._key_events = Queue.Queue()
self._last_activity = datetime.datetime.now()
self._max_idle = datetime.timedelta(seconds... |
import hashlib
from django.http.response import HttpResponse, HttpResponseRedirect
from django.utils.decorators import method_decorator
from django.views.decorators.cache import cache_page
from django.views.generic.base import View
import pydenticon
from pygments.formatters.html import HtmlFormatter
from gitbrowser.con... |
import pytest
def pytest_addoption(parser):
parser.addoption(
"--run-manual",
action="store_true",
default=False,
help="Run tests that require a device be connected",
)
def pytest_collection_modifyitems(config, items):
if not config.getoption("--run-manual"):
manual =... |
"""
Simple example that connects to the first Crazyflie found, ramps up/down
the motors and disconnects.
"""
import time, sys
from threading import Thread
sys.path.append("../lib")
import cflib
from cflib.crazyflie import Crazyflie
import logging
logging.basicConfig(level=logging.ERROR)
class MotorRampExample:
"""E... |
from django.conf.urls import patterns, include, url
import views
urlpatterns = patterns('',
# Examples:
# url(r'^$', 'Fingerprints_django.views.home', name='home'),
url(r'^$', views.home),
url(r'^home/?$', views.home, name='home'),
url(r'^how_to_use_api/?$', views.how_to_use_api, name='how_to_use_ap... |
import os
from gi.repository import GLib
from gi.repository import Gio
from gi.repository import GObject
_instance = None
def get_instance():
global _instance
if _instance is None:
_instance = Brightness()
return _instance
class Brightness(GObject.GObject):
_STEPS = 20
_SUGAR_LINK = '/var/ru... |
from StringIO import StringIO
from java import awt, applet
from java.net import URL
from JGLBabalCanvas import JGLBabalCanvas
class JGLBabalApplet(applet.Applet):
def _get_map_file(self):
map_param = self.getParameter('map')
map_url = URL(self.getDocumentBase(), map_param)
self.showStatus('L... |
"""
Django test runner that invokes nose.
Usage:
./manage.py test DJANGO_ARGS -- NOSE_ARGS
The 'test' argument, and any other args before '--', will not be passed
to nose, allowing django args and nose args to coexist.
You can use
NOSE_ARGS = ['list', 'of', 'args']
in settings.py for arguments that you always w... |
"""Script for unittesting the cmdlib module 'instance_storage'"""
import unittest
from ganeti import constants
from ganeti.cmdlib import instance_storage
from ganeti import errors
from ganeti import objects
import testutils
import mock
class TestCheckNodesFreeDiskOnVG(unittest.TestCase):
def setUp(self):
self.nod... |
from neolib.plots.altador.steps.FindOil import FindOil
from neolib.plots.Part import Part
class PartOne(Part):
_links = {
'hall': {
'link': 'http://www.neopets.com/altador/hallofheroes.phtml?',
'checks': ['monument to the great legends of Altador'],
},
'janitor': {
... |
from base import *
SECRET_KEY = '0$ip1fb5xtq%a=)-k_4r^(#jn0t^@+*^kihkxkozg-mip7+w3+'
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'sigi',
'USER': 'sigi',
'PASSWORD': '123456',
'HOST': 'localhost',
},
}
DEBUG = True
TEMPLATE_DEBUG ... |
import logging_util
from models.attachment_base import AttachmentBase
def generate_attachment_class(db):
class DbAttachment(db.Model, AttachmentBase):
_logger = logging_util.get_logger_by_name(__name__, 'DbAttachment')
__tablename__ = 'attachment'
id = db.Column(db.Integer, primary_key=True)... |
import array
from ola.ClientWrapper import ClientWrapper
import datetime
import time
NUM_PIXELS = 50
RED = 0
GREEN = 0
BLUE = 0
TIMESTEP = 1
bDimming = True
def DmxSent(state):
wrapper.Stop()
universe = 1
INCREMENT = 1
while bDimming:
# sleep for timestep
time.sleep(TIMESTEP)
# dim color valu... |
import PyKDE4.kdecore as __PyKDE4_kdecore
import PyQt4.QtCore as __PyQt4_QtCore
import PyQt4.QtGui as __PyQt4_QtGui
import PyQt4.QtSvg as __PyQt4_QtSvg
class KSelectionWatcher(__PyQt4_QtCore.QObject):
# no doc
def lostOwner(self, *args, **kwargs): # real signature unknown
pass
def newOwner(self, *ar... |
context.value += " " + context.lang.l3_code() + \
" " + context.country.l3_code() + \
" " + context.guid.string() + \
" " + context.locale.lang.l3_code() + "/" + \
context.locale.country.l3_code() + \
" " + context.moment.rfc0822(True,... |
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "gator_dev.settings")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv) |
import io
import sys, os, errno
import subprocess
import math
import re
import csv
import ConfigParser
import shutil
def average(s):
return sum(s) * 1.0 / len(s)
def deviation(s):
avg = average(s)
variance = map(lambda x: (x - avg)**2, s)
# sample deviation
return math.sqrt(sum(variance) / (len(vari... |
"""
A tool for generating statistics for each release.
.. moduleauthor:: Luke Macken <lmacken@redhat.com>
"""
from collections import defaultdict
from datetime import timedelta
from operator import itemgetter
import sys
from sqlalchemy.sql import and_
from bodhi.server import Session, initialize_db
from bodhi.server.mo... |
import requests
import Sven.Exception
import logging
import simplejson as json
from Sven.Methods import *
requests_log = logging.getLogger("requests")
requests_log.setLevel(logging.WARNING)
class Requests(object):
def headers(self, extraHeaders = None):
headers = {}
if extraHeaders is not None:
headers.... |
import PyKDE4.kdeui as __PyKDE4_kdeui
import PyQt4.QtCore as __PyQt4_QtCore
import PyQt4.QtGui as __PyQt4_QtGui
from .KBookmarkActionInterface import KBookmarkActionInterface
class KBookmarkAction(__PyKDE4_kdeui.KAction, KBookmarkActionInterface):
# no doc
def slotSelected(self, *args, **kwargs): # real signatu... |
"""KVM hypervisor
"""
import errno
import os
import os.path
import re
import tempfile
import time
import logging
import pwd
import shutil
import urllib2
from bitarray import bitarray
try:
import psutil # pylint: disable=F0401
except ImportError:
psutil = None
try:
import fdsend # pylint: disable=F0401
except ... |
'''
Copyright (C) 2015 Ryan M Cote.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is dis... |
"""TDjango URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.8/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-base... |
"""Provide API-callable functions for knowledge base management."""
import json
import os
import re
import warnings
from invenio.base.globals import cfg
from invenio.base.i18n import _
from invenio.ext.sqlalchemy import db
from invenio.ext.sqlalchemy.utils import session_manager
from invenio.modules.collections.models ... |
"""
The multiply-with-carry random number generator.
"""
import os
import warnings
import numpy as np
from util import devlib, assemble_code
mults = None
def load_mults():
pfpath = os.path.join(os.path.dirname(__file__), 'primes.bin')
if os.path.isfile(pfpath):
with open(pfpath) as fp:
retur... |
import math
def pair(tup):
return (tup[0], tup[1]) if len(tup) > 2 else tup
def dotproduct(v1, v2):
return sum((a*b) for a, b in zip(v1, v2))
def length(v):
return math.sqrt(dotproduct(v, v))
def angle(v1, v2):
return math.acos(dotproduct(v1, v2) / (length(v1) * length(v2)))
def angleToPoint(vec):
rotatio... |
import socket, struct, os, time, sys, hmac, types, random, errno, select
import imp, marshal, new, __builtin__
try:
import hashlib
md5=hashlib.md5
except ImportError:
import md5
md5=md5.md5
import Pyro.constants, Pyro.util
from Pyro.errors import *
from Pyro.errors import _InternalNoModuleError
pickle = Pyro.util.g... |
"""Block device abstraction"""
import re
import time
import errno
import pyparsing as pyp
import os
import logging
from ganeti import utils
from ganeti import errors
from ganeti import constants
from ganeti import objects
from ganeti import compat
from ganeti import netutils
_DEVICE_READ_SIZE = 128 * 1024
def _IgnoreEr... |
from __future__ import print_function
import traceback
import sys
import getopt
from itertools import chain
from random import sample
from tlsfuzzer.runner import Runner
from tlsfuzzer.messages import Connect, ClientHelloGenerator, \
ClientKeyExchangeGenerator, ChangeCipherSpecGenerator, \
FinishedGener... |
import unittest
from ropeide.formatter import Formatter
class FormatterTest(unittest.TestCase):
def setUp(self):
super(FormatterTest, self).setUp()
self.formatter = Formatter()
def tearDown(self):
super(FormatterTest, self).tearDown()
def test_removing_extra_spaces(self):
for... |
import terra
ser = terra.connect_and_flush()
terra.pause_board(ser)
terra.remove_alarm(ser,0,0,bytes("21",encoding="ascii"))
terra.remove_alarm(ser,0,0,bytes("20",encoding="ascii"))
terra.resume_board(ser)
ser.close() |
from __future__ import unicode_literals
import collections
from molbiox.io import tabular
from molbiox.frame import interactive
fieldlist_mini = [
('query.id', None),
('query.length', int),
('subject.length', int),
('subject.id', None),
('alignment.length', int),
... |
import Interface
import openwns.wrowser.Tools as Tools
import Errors
from PyQt4 import QtGui
class GraphInstantiator:
def __init__(self, graphClass):
self.graphs = dict()
self.graphClass = graphClass
def getGraphInstance(self, key, graphargs):
if not self.graphs.has_key(key):
... |
from ....const import LOCALE as glocale
_ = glocale.translation.gettext
from .. import Rule
class SearchName(Rule):
"""Rule that checks for full or partial name matches"""
labels = [_('Substring:')]
name = _('People matching the <name>')
description = _("Matches people with a specified (part... |
from containers import *
from events import *
from struct import unpack, pack
from constants import *
from util import *
class FileReader(object):
def read(self, midifile):
pattern = self.parse_file_header(midifile)
for track in pattern:
self.parse_track(midifile, track)
return p... |
import pandas as pd
def resample_records(records, rule):
"""Resamples records with pandas DataFrame.resample()
Args:
records (django queryset): Ordinary django queryset to be resampled
with pandas resample.
rule (pandas resampling rule): Pandas resampling rule. 'D' for
... |
__author__ = 'tonycastronova'
class Status():
Loaded = 'LOADED'
Running = 'RUNNING'
Finished = 'FINSHED'
Error = 'ERROR'
Ready = 'READY'
NOTREADY = 'NOTREADY' |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.