content stringlengths 4 20k |
|---|
import pytest
pytest.importorskip("matplotlib") # requires matplotlib!
from matplotlib.font_manager import FontProperties, findfont
from ezdxf.tools.fonts import FontFace
from ezdxf.addons import text2path
from ezdxf.path import Path
from ezdxf import path, bbox
from ezdxf.entities import Text, Hatch
from ezdxf.layo... |
import pytest
import pymysql
from mycli.main import format_output, special
from os import getenv
# TODO: should this be somehow be divined from environment?
USER, HOST, PORT, CHARSET = 'root', 'localhost', 3306, 'utf8'
PASSWORD = getenv('PASSWORD')
def db_connection(dbname=None):
conn = pymysql.connect(user=USER,... |
import time
import traceback
from datetime import date, datetime, timedelta
from threading import Thread
from django.core.exceptions import FieldError
from django.db import DatabaseError, IntegrityError, connection
from django.test import (
SimpleTestCase, TestCase, TransactionTestCase, skipUnlessDBFeature,
)
fro... |
from django import template
from django.db import models
from django.db.models.fields import FieldDoesNotExist
from django.db.models.fields.related import ForeignKey, ManyToManyField
from django.conf import settings
from inplaceeditform import settings as inplace_settings
from inplaceeditform.adaptors import ADAPTOR_I... |
import superdesk
from bs4 import BeautifulSoup
from superdesk.metadata.item import ITEM_TYPE, CONTENT_TYPE
from flask import render_template
from jinja2 import Template
def getTemplate(highlightId):
"""Return the string template associated with highlightId or none """
if not highlightId:
return None
... |
"""Calibration of predicted probabilities."""
# Balazs Kegl <<EMAIL>>
# Jan Hendrik Metzen <<EMAIL>>
# Mathieu Blondel <<EMAIL>>
#
# License: BSD 3 clause
from __future__ import division
import inspect
import warnings
from math import log
import numpy as np
from scipy.optimize import fmin_bf... |
# -*- coding: utf-8 -*-
"""
***************************************************************************
__init__.py
---------------------
Date : May 2015
Copyright : (C) 2015 by Luigi Pirelli
Email : luipir at gmail dot com
*********************************... |
"""
bot - a basic Bot class
"""
from twitterbot import TwitterBot
from mastodonbot import MastodonBot
import argparse, yaml, pystache, random, time, sys
SERVICES = {
'Twitter': TwitterBot,
'Mastodon': MastodonBot
}
class Bot(object):
"""A bot base class.
This is a base class for bots which provide... |
"""
To get the authentication token for Junction TV API calls
This code had two function:
- ``getAuthToken(client_id, client_secret)``: to get the authentication call from `http://cloud.junctiontv.net/ums/2.0/oauth/`
- ``getFeeds(token)``: to get the Feeds according to vairous Junction TV API
For detailed descript... |
#!/usr/bin/env python
#
# Created on 7/5/2013 Pat Cappelaere - Vightel Corporation
#
# Requirements:
# gdal...
#
# DEM Manipulation and Visualization utilities for HydroSHEDS
#
# Inpiration from:
# http://blog.thematicmapping.org/2012/07/terrain-mapping-with-mapnik.html
#
#
import os, inspect
import argparse
import su... |
import socket
import threading
import time
import xmlrpclib
from PyQt4.QtGui import *
from PyQt4.QtCore import *
from electrum_vtc import bitcoin, util
from electrum_vtc import transaction
from electrum_vtc.plugins import BasePlugin, hook
from electrum_vtc.i18n import _
from electrum_vtc.wallet import Multisig_Wallet... |
from __future__ import absolute_import
from django.core.exceptions import ValidationError
from django.utils import timezone
from nose.tools import * # noqa PEP8 asserts
from framework.auth import Auth
from tests.base import OsfTestCase
from osf_tests.factories import UserFactory, CommentFactory
from osf.models impo... |
"""Pure-Python RSA implementation."""
from .cryptomath import *
from . import xmltools
from .ASN1Parser import ASN1Parser
from .RSAKey import *
class Python_RSAKey(RSAKey):
def __init__(self, n=0, e=0, d=0, p=0, q=0, dP=0, dQ=0, qInv=0):
if (n and not e) or (e and not n):
raise AssertionError(... |
"""Classes that hold units of .rc files (:class:`rcunit`) or entire files
(:class:`rcfile`) used in translating Windows Resources.
.. note:::
This implementation is based mostly on observing WINE .rc files,
these should mimic other non-WINE .rc files.
"""
import re
from translate.storage import base
def esc... |
"""
These methods should never be placed in 'desktop.lib.exceptions'.
This file exists to remove circular reference caused by importing django_util.
"""
import sys
import traceback
from django.utils.encoding import force_unicode
# Need full import statement
import desktop.lib.django_util
class PopupException(Excep... |
from __future__ import absolute_import
from __future__ import unicode_literals
import mock
import pytest
from git_code_debt.server import metric_config
from git_code_debt.server.presentation.commit_delta import CommitDeltaPresenter
@pytest.yield_fixture
def patched_color_overrides():
with mock.patch.object(
... |
from django.test.client import RequestFactory
from nose.tools import eq_
import mkt
import mkt.site.tests
from mkt.account.utils import purchase_list
from mkt.constants import apps
from mkt.site.fixtures import fixture
from mkt.site.utils import app_factory
from mkt.users.models import UserProfile
from mkt.webapps.mo... |
"""An adaptation of Py2.3/2.4's Queue module which supports reentrant
behavior, using RLock instead of Lock for its mutex object.
This is to support the connection pool's usage of weakref callbacks to return
connections to the underlying Queue, which can in extremely
rare cases be invoked within the ``get()`` method o... |
"""Base class for executors running Hadoop/Hive jobs."""
import datetime
import getpass
import os
import re
import subprocess
from pinball_ext.common import hadoop_utils
from pinball_ext.common.decorators import retry
from pinball_ext.common.utils import get_logger
__author__ = 'Zach Drach, Changshu Liu'
__copyrigh... |
from .entity import EntityTranslator
from ..converters.default import convert_links, convert_project
class SceneTranslator(EntityTranslator):
"""
Scene property translator.
Assigning this translator to a Scene model will cause inbound property values to be converted.
.. versionadded:: v00_04... |
"""Data model classes for parsing and generating XML for the Contacts API."""
__author__ = '<EMAIL> (Vince Spicer)'
import atom.core
import gdata
import gdata.data
PHOTO_LINK_REL = 'http://schemas.google.com/contacts/2008/rel#photo'
PHOTO_EDIT_LINK_REL = 'http://schemas.google.com/contacts/2008/rel#edit-photo'
E... |
"""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, software... |
#!/usr/bin/env python
"""
Simple tornado app to list and read files.
Start server:
python svc.py -port=8001
(Default port is 8000)
Using service
/
List:
/data/path/to/dir
Read:
/data/path/to/file
Filter:
/data/path/to/file?rows=id1,id2&cols=colid1,colid2
All services return status_code 500 if there is any error.
... |
# -*- coding: utf-8 -*-
class Iterable(list):
"""
Class to iterate among returned objects.
"""
def __init__(self, cls, lst=None, attr=None, auth=None, cypher=None):
if lst is None:
lst = []
self._auth = auth or {}
self._cypher = cypher
self._list = lst
... |
import django_tables2 as tables
from ccbclib.models import Book, Borrower, Transaction
class BookTable(tables.Table):
idbook = tables.Column(verbose_name="id")
get_area = tables.Column(verbose_name="Field",orderable=False)
get_language = tables.Column(verbose_name="Language",orderable=False)
get_book_s... |
#!/usr/bin/env python
# -- Content-Encoding: UTF-8 --
"""
MQTT client utility: Tries to hide Paho client details to ease MQTT usage.
Reconnects to the MQTT server automatically.
This module depends on the paho-mqtt package (ex-mosquitto), provided by the
Eclipse Foundation: see http://www.eclipse.org/paho
:author: Th... |
#!/usr/bin/env python
"""
Unit tests for histogram.py
TODO:
- Improve tests for calculating histogram
- Add tests for output
"""
import unittest
from StringIO import StringIO
from histogram import *
from statslib import InvalidDataException
CSV_INPUT = """1, 17.2, 55, 120.888
6, 4, 51, 220.888
4, 12.6, 52, 120.888
... |
# -*- coding: utf-8 -*-
from django import forms
from django.contrib.auth.forms import ReadOnlyPasswordHashField
from cms.compat import get_user_model
from .models import EmailUser
class UserCreationForm(forms.ModelForm):
"""
A form for creating a new user, including the required
email and password field... |
from __future__ import absolute_import, division, print_function
import numpy as np
from numpy.testing import assert_array_equal, assert_array_almost_equal
from nose.tools import assert_equal
from skbeam.core.constants.xrs import HKL, calibration_standards
from skbeam.core.utils import q_to_d, d_to_q
def smoke_test... |
from django.conf.urls import patterns, url
from . import views
urlpatterns = patterns(
'',
url(r'^(?P<template_name>\w+\.html)$',
views.partial_template,
name='partial_template'),
url(r'^api/yours/$',
views.your_events,
name='your_events'),
url(r'^api/save/$',
... |
"""Test .dist-info style distributions.
"""
import os
import shutil
import tempfile
import unittest
import textwrap
try:
import ast
except:
pass
import pkg_resources
from setuptools.tests.py26compat import skipIf
def DALS(s):
"dedent and left-strip"
return textwrap.dedent(s).lstrip()
class TestDist... |
"""
click._termui_impl
~~~~~~~~~~~~~~~~~~
This module contains implementations for the termui module. To keep the
import time of Click down, some infrequently used functionality is placed
in this module and only imported as needed.
:copyright: (c) 2014 by Armin Ronacher.
:license: BSD, se... |
from __future__ import absolute_import
import sys
import time
import ctypes
import threading
# Based on http://code.activestate.com/recipes/483752/
class TimeoutExpired(Exception):
'''Exception raised when a function times out.'''
def __str__(self):
return 'Function call timed out.'
def timeout(time... |
#!/usr/bin/python
import os
import sys
import time
import datetime
import ccdash
INTERVAL = 300
DELAY = 0
ONCE = False
SUFFIX = ""
FORCE = False
def run_scenarios(scenarios, group):
# Run each scenario
rc = 0
for scenario in scenarios:
argv = []
argv.append("ccdash.py")
argv.append("scenario")
argv.append(... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
from abc import ABCMeta, abstractmethod
from six import with_metaclass
class InventoryParser(with_metaclass(ABCMeta, object)):
'''Abstract Base Class for retrieving inventory information
Any InventoryParser functions by ... |
import numpy as np
from numpy.testing import (assert_array_equal, assert_array_almost_equal,
assert_equal, assert_allclose, assert_array_less)
import pytest
from mne import create_info, EpochsArray
from mne.fixes import is_regressor, is_classifier
from mne.utils import requires_sklearn, requ... |
"""
Django settings for mydjangoproject project.
Generated by 'django-admin startproject' using Django 1.8.
For more information on this file, see
https://docs.djangoproject.com/en/1.8/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.8/ref/settings/
"""
# Buil... |
import os
import sys
import unittest
import ConfigParser
sys.path.insert(1, os.path.abspath(os.path.join(__file__, "../..")))
import base_test
from webdriver import exceptions
from wptserve import server
from wptserve.router import any_method
from wptserve.handlers import basic_auth_handler
class WebDriverAuthTest(un... |
"""Add columns to review questions and review ratings tables.
Revision ID: 2af245be72a6
Revises: 566d5de4e0e5
Create Date: 2017-11-24 11:38:33.292283
"""
import sqlalchemy as sa
from alembic import op
# revision identifiers, used by Alembic.
revision = '2af245be72a6'
down_revision = '566d5de4e0e5'
branch_labels = N... |
"""
37. Fixtures.
Fixtures are a way of loading data into the database in bulk. Fixure data
can be stored in any serializable format (including JSON and XML). Fixtures
are identified by name, and are stored in either a directory named 'fixtures'
in the application directory, or in one of the directories named in the
`... |
import os
import re
import warnings
import boto
from boto.compat import expanduser, ConfigParser, StringIO
# By default we use two locations for the boto configurations,
# /etc/boto.cfg and ~/.boto (which works on Windows and Unix).
BotoConfigPath = '/etc/boto.cfg'
BotoConfigLocations = [BotoConfigPath]
UserConfigP... |
"""stack symbolizes native crash dumps."""
import re
import symbol
def PrintTraceLines(trace_lines):
"""Print back trace."""
maxlen = max(map(lambda tl: len(tl[1]), trace_lines))
print
print "Stack Trace:"
print " RELADDR " + "FUNCTION".ljust(maxlen) + " FILE:LINE"
for tl in trace_lines:
(addr, s... |
# This file helps to compute a version number in source trees obtained from
# git-archive tarball (such as those provided by githubs download-from-tag
# feature). Distribution tarballs (built by setup.py sdist) and build
# directories (produced by setup.py build) will contain a much shorter file
# that just contains th... |
import numpy as np
import numpy.testing as npt
import scipy.ndimage
from dipy.core.ndindex import ndindex
from dipy.tracking.local import (BinaryTissueClassifier,
ThresholdTissueClassifier,
ActTissueClassifier)
from dipy.tracking.local.localtracking imp... |
from django.http.cookie import SimpleCookie, parse_cookie
from django.http.request import (HttpRequest, QueryDict,
RawPostDataException, UnreadablePostError, build_request_repr)
from django.http.response import (
HttpResponse, StreamingHttpResponse, FileResponse,
HttpResponseRedirect, HttpResponsePermanentR... |
# coding: utf-8
from __future__ import unicode_literals
import re
from .common import InfoExtractor
class TF1IE(InfoExtractor):
"""TF1 uses the wat.tv player."""
_VALID_URL = r'http://videos\.tf1\.fr/.*-(?P<id>.*?)\.html'
_TEST = {
'url': 'http://videos.tf1.fr/auto-moto/citroen-grand-c4-picasso-... |
"""python_instance.py: Python Instance for running python functions
"""
from concurrent import futures
from log import Log
import grpc
import InstanceCommunication_pb2_grpc
class InstanceCommunicationServicer(InstanceCommunication_pb2_grpc.InstanceControlServicer):
"""Provides methods that implement functionality o... |
import django
from django.contrib import admin
from django import forms
from allauth.account.adapter import get_adapter
from .models import SocialApp, SocialAccount, SocialToken
class SocialAppForm(forms.ModelForm):
class Meta:
model = SocialApp
exclude = []
widgets = {
'clie... |
#! /usr/bin/python
# -*- coding:utf-8 -*-
"""
Author: AsherYang
Email: <EMAIL>
Date: 2018/7/2
Desc: 权限管理类
主要做一些权限校验
"""
from BaseResponse import BaseResponse
from constant import ResponseCode
from constant import LoginStatus
from util.MD5Util import MD5Util, ADMIN_SECRET_KEY
from mgrsys.AdminManager import Admi... |
"""
This module adds shared support for Apstra AOS modules
In order to use this module, include it as part of your module
from ansible.module_utils.aos import *
"""
import json
from distutils.version import LooseVersion
from ansible.module_utils.pycompat24 import get_exception
try:
import yaml
HAS_YAML = T... |
import sys
from .__pkginfo__ import version as __version__
def run_pylint():
"""run pylint"""
from pylint.lint import Run
Run(sys.argv[1:])
def run_pylint_gui():
"""run pylint-gui"""
try:
from pylint.gui import Run
Run(sys.argv[1:])
except ImportError:
sys.exit('tkinte... |
from django import forms
from django.conf import settings
from django.contrib.contenttypes.models import ContentType
from django.forms import FloatField
from django.utils.translation import gettext_lazy as _
from django.forms.models import inlineformset_factory
from crispy_forms.helper import FormHelper
from crispy_fo... |
""" Thermo Scientific 'Arena 20XT' (The file name for importing staff)
"""
from bika.lims import bikaMessageFactory as _
from bika.lims.utils import t
from . import ThermoArenaImporter, ThermoArenaRPRCSVParser
import json
import traceback
title = "Thermo Scientific - Arena 20XT"
def Import(context, request):
""" ... |
import MySQLdb
class MyDB(object):
def __init__(self, options):
self.name = options.db
self.host = options.host
self.user = options.user
self.passwd = options.passwd
self.mydb = None
self.cursor = None
def admin(self):
self.close()
self.mydb = My... |
"""
Accountant
----------
A commandline utility for managing finance and accounting.
Concepts:
Transaction - double entry accounting.
Statement - Balance of assets at point in time for verification purpose
Account - superclass of Equity, Assets, Liabilities, Expenses, Income
TODO:
Sort out difference between ... |
"""
BibCheck API
This API lets other modules interact with bibcheck.
"""
from invenio import bibcheck_task
def check_record(record, enabled_rules=None):
"""
Check a record agains some bibcheck rules.
@param record: Record to check
@type record: recstruct
@param enabled_rules: List of rules to ru... |
"""Applies a fix to CR LF TAB handling in xml.dom.
Fixes this: http://code.google.com/p/chromium/issues/detail?id=76293
Working around this: http://bugs.python.org/issue5752
TODO(bradnelson): Consider dropping this when we drop XP support.
"""
import xml.dom.minidom
def _Replacement_write_data(writer, data, is_att... |
from datetime import datetime
import time
import htmlentitydefs
import re
import locale
from urllib import quote
def parse_datetime(string):
# Set locale for date parsing
locale.setlocale(locale.LC_TIME, 'C')
# We must parse datetime this way to work in python 2.4
date = datetime(*(time.strptime(stri... |
"""
Testing for export functions of decision trees (sklearn.tree.export).
"""
from re import finditer
from numpy.testing import assert_equal
from nose.tools import assert_raises
from sklearn.tree import DecisionTreeClassifier, DecisionTreeRegressor
from sklearn.ensemble import GradientBoostingClassifier
from sklearn... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import glob
import json
import os
import stat
from ansible.module_utils.six.moves import configparser
from ansible.module_utils.six.moves import StringIO
from ansible.module_utils.facts.utils import get_file_content
from ansible... |
CSRF_SECRET_KEY, SESSION_KEY = "0h97kel3aq17853645odikh97kel3aq4vndtonignnobfjh", "3aq4vnd4vndtonignnt801785onignnob"
# Google APIs
GOOGLE_APP_ID = '768017853645-odikh97kel3aq4vndtonignnobfjhkea.apps.googleusercontent.com'
GOOGLE_APP_SECRET = 'gb2X0NdP36xF-2kmj_S2IN3U'
#GOOGLE_REDIRECT_URI = 'http://localhost:5000/aut... |
#! /usr/bin/env python
from __future__ import print_function, division
import time
import logging
import sys
from os import path, getenv
# if PAPARAZZI_SRC not set, then assume the tree containing this
# file is a reasonable substitute
PPRZ_SRC = getenv("PAPARAZZI_SRC", path.normpath(path.join(path.dirname(path.absp... |
try:
import unittest2 as unittest
except ImportError:
import unittest
try:
import mock
from mock import call
except ImportError:
import unittest.mock as mock
from unittest.mock import call
import sys
if sys.version_info[0] == 2:
import __builtin__ as builtins
else:
import builtins
imp... |
"""
api module contains classes that make http requests to Facebook's graph API.
"""
from facebookads.exceptions import FacebookRequestError
from facebookads.session import FacebookSession
import json
import six
import collections
from six.moves import urllib
from six.moves import http_client
class FacebookResponse(... |
# coding: utf-8
from __future__ import unicode_literals
from .common import InfoExtractor
from ..compat import compat_HTTPError
from ..utils import (
float_or_none,
int_or_none,
try_get,
# unified_timestamp,
ExtractorError,
)
class RedBullTVIE(InfoExtractor):
_VALID_URL = r'https?://(?:www\.)... |
'''
Created on Oct 19, 2010
@author: Peter
'''
from numpy import *
def loadDataSet():
postingList=[['my', 'dog', 'has', 'flea', 'problems', 'help', 'please'],
['maybe', 'not', 'take', 'him', 'to', 'dog', 'park', 'stupid'],
['my', 'dalmation', 'is', 'so', 'cute', 'I', 'love', 'him... |
import fixtures
from keystone import auth
import keystone.server
class BackendLoader(fixtures.Fixture):
"""Initialize each manager and assigns them to an attribute."""
def __init__(self, testcase):
super(BackendLoader, self).__init__()
self._testcase = testcase
def setUp(self):
... |
from bs4 import BeautifulSoup
from collections import defaultdict
import requests
from phone_iso3166.country import network_country
from phone_iso3166.errors import InvalidNetwork
from io import StringIO
from pprint import pformat
names_out_file = 'phone_iso3166/e212_names.py'
html = requests.get('https://en.wikipedi... |
"""Test Statusbar url."""
import pytest
from qutebrowser.utils import usertypes
from qutebrowser.mainwindow.statusbar import url
from PyQt5.QtCore import QUrl
@pytest.fixture
def url_widget(qtbot, monkeypatch, config_stub):
"""Fixture providing a Url widget."""
config_stub.data = {
'colors': {
... |
# Implement 'jpeg' interface using SGI's compression library
# XXX Options 'smooth' and 'optimize' are ignored.
# XXX It appears that compressing grayscale images doesn't work right;
# XXX the resulting file causes weirdness.
from warnings import warnpy3k
warnpy3k("the jpeg module has been removed in Python 3.0", sta... |
import ConfigParser
import StringIO
import unittest
from test import test_support
class TestCaseBase(unittest.TestCase):
def newconfig(self, defaults=None):
if defaults is None:
self.cf = self.config_class()
else:
self.cf = self.config_class(defaults)
return self.c... |
import numpy as np
from ..qt import QtGui
from ..utils import new_plot
from ..utils.canvas import BlitManager, EventManager
from .base import Plugin
__all__ = ['PlotPlugin']
class PlotPlugin(Plugin):
"""Plugin for ImageViewer that contains a plot canvas.
Base class for plugins that contain a Matplotlib pl... |
"""distutils.command.bdist
Implements the Distutils 'bdist' command (create a built [binary]
distribution)."""
import os
from distutils.core import Command
from distutils.errors import *
from distutils.util import get_platform
def show_formats():
"""Print list of available formats (arguments to "--format" optio... |
# -*- coding: utf-8 -*-
"""
pygments.lexers.slash
~~~~~~~~~~~~~~~~~~~~~
Lexer for the `Slash <https://github.com/arturadib/Slash-A>`_ programming
language.
:copyright: Copyright 2012 by GitHub, Inc
:license: BSD, see LICENSE for details.
"""
import re
from pygments.lexer import ExtendedRegex... |
from z3 import *
f = Function('f', IntSort(), RealSort(), IntSort())
try:
print(f.domain(3))
except Z3Exception:
print("Failed")
x = Int('x')
print(f(1, 1))
print(f(1, 1).sort())
print(f(x, 1).num_args())
print(f(x+1, 1).children())
print(f(x+1, 1).arg(0))
print(f(x+1, 1).arg(0).eq(x+1))
print(f(x+1, x).dec... |
#!/usr/bin/env python
import argparse
from ipalib import api
import json
def initialize():
'''
This function initializes the FreeIPA/IPA API. This function requires
no arguments. A kerberos key must be present in the users keyring in
order for this to work.
'''
api.bootstrap(context='cli')
... |
from __future__ import print_function
import json
import mmap
import os
import re
import sys
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("filenames", help="list of files to check, all files if unspecified", nargs='*')
parser.add_argument("-e", "--skip-exceptions", help="ignore hack/verify-f... |
from analytics.lib.counts import CountStat
from analytics.lib.fixtures import generate_time_series_data
from zerver.lib.test_classes import ZulipTestCase
# A very light test suite; the code being tested is not run in production.
class TestFixtures(ZulipTestCase):
def test_deterministic_settings(self) -> None:
... |
'''
Copyright (C) 2013 Rasmus Eneman <<EMAIL>>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distribu... |
import numpy as np
from bokeh.plotting import figure, show, output_file
from bokeh.layouts import column
from bokeh.models import CustomJS
from bokeh.models.widgets import Select
from bokeh.core.enums import SizingMode
N = 4000
x = np.random.random(size=N) * 100
y = np.random.random(size=N) * 100
radii = np.random.ra... |
#!/usr/bin/env python
import sys
import json
from random import randint
import momoko
import motor
import tornado.ioloop
import tornado.web
from tornado import gen
import tornado.options
from tornado.options import options
import tornado.httpserver
PY3 = False
if sys.version_info[0] == 3:
PY3 = True
xrange =... |
"""Command-line interface for DXR"""
from os.path import basename
from sys import argv
from click import ClickException, group
from dxr.cli.clean import clean
from dxr.cli.delete import delete
from dxr.cli.deploy import deploy
from dxr.cli.index import index
from dxr.cli.list import list
from dxr.cli.serve import se... |
import os
from oslo.config import cfg
from nova.api.openstack import API_V3_CORE_EXTENSIONS # noqa
from nova import test
from nova.tests.functional import api_samples_test_base
from nova.tests.unit import fake_network
from nova.tests.unit import fake_utils
CONF = cfg.CONF
class ApiSampleTestBaseV3(api_samples_tes... |
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
import xbmcplugin,xbmcgui,xbmc,xbmcaddon
import os,sys,urllib
def get_params():
param=[]
paramstring=sys.argv[2]
if len(paramstring)>=2:
params=sys.argv[2]
cleanedparams=params.replace('?','')
if (par... |
import abc
import inspect
import logging
import random
import sys
from collections import namedtuple
log = logging.getLogger("edx.courseware")
# This is a tuple for holding scores, either from problems or sections.
# Section either indicates the name of the problem or the name of the section
Score = namedtuple("Scor... |
import sys, csv, json, argparse, random, time
sys.path.append("../")
import numpy as np
from collections import defaultdict
from tool import combineFeature, calSegNum, calMonthLength
settings = json.loads(open("../../SETTINGS.json").read())
TOTAL_MONTH = 3
def genTestPairForBuy(data):
uid_set = set([])
pid_se... |
#!/usr/bin/python
# coding=utf-8
################################################################################
from test import CollectorTestCase
from test import get_collector_config
from test import unittest
from mock import Mock
from mock import patch
try:
from cStringIO import StringIO
except ImportError:
... |
'''
RSON -- readable serial object notation
RSON is a superset of JSON with relaxed syntax for human readability.
Simple usage example:
import rson
obj = rson.loads(source)
Additional documentation available at:
http://code.google.com/p/rson/
'''
__version__ = '0.08'
__author__ = 'Patrick ... |
import json
import logging
from sqlalchemy import or_
from flask import Blueprint, request, url_for
from grano.lib.serialisation import jsonify
from grano.lib.args import object_or_404, get_limit
from grano.core import db, app_name
from grano.lib.exc import BadRequest
from grano.model import Entity, Project, Property... |
# coding:utf-8
import os
import random
from yaml import load
config_path = os.path.join(os.path.dirname(__file__), 'spider.yaml')
with open(config_path, encoding='utf-8') as f:
cont = f.read()
cf = load(cont)
def get_db_args():
return cf.get('db')
def get_redis_args():
return cf.get('redis')
def g... |
"""Implements a EtherLike-MIB MibRetriever and associated functionality."""
from __future__ import absolute_import
from twisted.internet import defer
from . import mibretriever
class EtherLikeMib(mibretriever.MibRetriever):
"""MibRetriever for EtherLike-MIB"""
from nav.smidumps.etherlike_mib import MIB as mib... |
"""
The following classes will be available through gnuradio.wxgui.forms:
"""
########################################################################
# External Converters
########################################################################
from converters import \
eval_converter, str_converter, \
float_convert... |
"""SCons.Script
This file implements the main() function used by the scons script.
Architecturally, this *is* the scons script, and will likely only be
called from the external "scons" wrapper. Consequently, anything here
should not be, or be considered, part of the build engine. If it's
something that we expect ot... |
"""
Lighting channels module for Zigbee Home Automation.
For more details about this component, please refer to the documentation at
https://home-assistant.io/components/zha/
"""
import logging
from . import ZigbeeChannel
_LOGGER = logging.getLogger(__name__)
class ColorChannel(ZigbeeChannel):
"""Color channel.... |
"""Buildgen .proto files list plugin.
This parses the list of targets from the json build file, and creates
a list called "protos" that contains all of the proto file names.
"""
import re
def mako_plugin(dictionary):
"""The exported plugin code for list_protos.
Some projects generators may want to get the fu... |
#
# Unpacker for Dean Edward's p.a.c.k.e.r, a part of javascript beautifier
# by Einar Lielmanis <<EMAIL>>
#
# written by Stefano Sanfilippo <<EMAIL>>
#
# usage:
#
# if detect(some_string):
# unpacked = unpack(some_string)
#
"""Unpacker for Dean Edward's p.a.c.k.e.r"""
import re
import string
from . import Un... |
import markdown2
from django.db import models
from django.conf import settings
from django.utils import timezone
from django.utils.text import slugify
from django.contrib.auth.models import User
from django.contrib.sites.models import Site
# --------------------------------
# Helper Functions
# ----------------------... |
import functools
from PyQt4.QtCore import pyqtSignal, QSize, Qt
from PyQt4.QtGui import QToolBar, QWidget, QSizePolicy, QLabel, QIcon
from roam.popupdialogs import DeleteFeatureDialog
from roam.editorwidgets.core import LargeEditorWidget
from roam.flickwidget import FlickCharm
from roam.api import featureform, RoamEv... |
import os
import signal
import sys
import time
import traceback
from django.apps import apps
from django.conf import settings
from django.core.signals import request_finished
from django.utils import six
from django.utils._os import npath
from django.utils.six.moves import _thread as thread
# This import does nothing... |
import json
from oslo_log import log as logging
from pecan import rest
import sqlalchemy as sa
import tenacity
from wsme import types as wtypes
import wsmeext.pecan as wsme_pecan
from mistral.api import access_control as acl
from mistral.api.controllers.v2 import action_execution
from mistral.api.controllers.v2 impor... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.