content stringlengths 4 20k |
|---|
from pulse.vendor.Qt import QtCore, QtWidgets, QtGui
import pulse.controlshapes
from pulse import editorutils
from pulse.views.core import PulsePanelWidget
from pulse.views.style import UIColors
from pulse.views.utils import getIcon
from pulse.views.utils import undoAndRepeatPartial as cmd
__all__ = [
"ControlsPa... |
# coding: utf-8
from typing import Optional
from il2fb.commons import actors
from il2fb.commons.events import ParsableEvent
from il2fb.commons.regex import (
ANYTHING, WHITESPACE, DIGIT, NUMBER, START_OF_STRING, END_OF_STRING,
make_matcher, choices, group, named_group,
)
from il2fb.commons.transformers import... |
#!/usr/bin/python
#coding:utf8
__author__ = ['markshao']
MACHINES_PERSISTENT_FILE = ".machines_persistent"
PAGRANT_CONFIG_FILE_NAME = "Pagrantfile"
from pagrant.commands.init import InitCommand
from pagrant.commands.test import TestCommand
from pagrant.commands.vmp import VmpCommand
from pagrant.commands.clean impor... |
from pickle import dumps, loads
try:
from bsddb3 import db
except:
# FIXME: make this more abstract to deal with other backends
class db:
DB_RMW = 0
DB_FIRST = 0
DB_LAST = 0
DB_CURRENT = 0
DB_PREV = 0
DB_NEXT = 0
#--------------------------------------------... |
from sqlalchemy import Column, String, Float, Integer, ForeignKey
from sqlalchemy.ext.declarative import as_declarative, declared_attr
@as_declarative()
class Base(object):
id = Column(Integer, primary_key=True)
@declared_attr
def __tablename__(self):
return self.__name__.lower()
def setup_db(s... |
from openerp.osv import fields, osv
from openerp.tools.translate import _
from openerp import SUPERUSER_ID
class inactive_account_wizard(osv.osv_memory):
_name = 'inactive.account.wizard'
def get_accounts(self, cr, uid, ids, context=None):
account_obj = self.pool.get('account.account')
for da... |
import os
import sys
from os import listdir
from os.path import isfile, join
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
from PIL import Image
import subprocess
def getFiles(loc) :
files=[os.path.join(dp, f) for dp, dn, fn in os.walk(os.path.expanduser(loc)) for f in fn]
... |
from oslo.utils import timeutils
from nova import db
from nova.tests.unit.api.openstack.compute.plugins.v3 import test_services
from nova.tests.unit.integrated.v3 import api_sample_base
class ServicesJsonTest(api_sample_base.ApiSampleTestBaseV3):
extension_name = "os-services"
def setUp(self):
super... |
"""
DAG designed to test a PythonOperator that calls a functool.partial
"""
import functools
import logging
from datetime import datetime
from airflow.models import DAG
from airflow.operators.python import PythonOperator
DEFAULT_DATE = datetime(2016, 1, 1)
default_args = dict(
start_date=DEFAULT_DATE,
owner='... |
from sphinx_testing import with_app
lines = []
@with_app(buildername='text', srcdir='root', copy_srcdir_to_tmpdir=True, outdir='root/_build')
def setup(app, status, warning):
app.build()
global lines
with open(app.outdir + '/index.txt') as f:
lines = f.readlines()
lines = [line.replace('\n'... |
from __future__ import absolute_import, division, print_function, unicode_literals
import pytest ; pytest
#-----------------------------------------------------------------------------
# Imports
#-----------------------------------------------------------------------------
# Standard library imports
from mock import... |
import abc
import logging
import pathlib
from ..options import ConnexionOptions
from ..resolver import Resolver
logger = logging.getLogger('connexion.app')
class AbstractApp(metaclass=abc.ABCMeta):
def __init__(self, import_name, api_cls, port=None, specification_dir='',
host=None, server=None,... |
import afnumpy
from asserts import *
import pytest
xfail = pytest.mark.xfail
def test_comparisons():
a = afnumpy.arange(10, dtype="float32") - 5.
b = afnumpy.ones((10), dtype="float32")
a.eval()
a_mask = a < 0.
a_sum = a_mask.sum()
a -= b
assert(a_sum == a_mask.sum())
a_mask = a > 0.
... |
"""OS routines for Mac, DOS, NT, or Posix depending on what system we're on.
This exports:
- all functions from posix, nt, dos, os2, mac, or ce, e.g. unlink, stat, etc.
- os.path is one of the modules posixpath, ntpath, macpath, or dospath
- os.name is 'posix', 'nt', 'dos', 'os2', 'mac', or 'ce'
- os.curdir is... |
from django.conf.urls import patterns, include, url
from django.conf import settings
from django.views.generic import RedirectView
from onadata.apps.api.urls import router
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns(
'',
# ... |
from JumpScale import j
class ActorsInfo():
def getActorMethodCall(self, appname, actor, method):
"""
used for during error show links to methods in browser
"""
url = "/rest/%s/%s/%s?" % (appname, actor, method)
auth = j.core.portal.active.ws.routes["%s_%s_%s" % (appname, ... |
from paravistest import datadir, Import_Med_Field
import pvserver as paravis
med_file = datadir + "carre_en_quad4_import22.med"
field_names = ["fieldcelldouble", "fieldnodedouble", "fieldnodedouble", "fieldnodedouble", "fieldnodeint"]
prs_list = [ range(10), [1,2,3,4,8], [1,2,3,4,8], [1,2,3,4,8], [1,2,3,4,8] ]
Import... |
"""Comparing execution times of h5features 1.0 and 1.1 versions."""
import argparse
import timeit
# import cProfile
# import os
from aux import generate
import aux.h5features_v1_0 as h5f
from aux.utils import remove
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument('-i', '--nitems',
... |
from collections import namedtuple
PingObjectTuple = namedtuple("PingObjectTuple", "name "
"address "
"update_rate "
"number_of_pings "
... |
import serial
from wader.common import consts
from core.hardware.novatel import (NovatelWCDMADevicePlugin,
NovatelWCDMACustomizer,
NOVATEL_BAND_DICT)
from core.hardware.base import build_band_dict
class NovatelXU870Customizer(Novat... |
import docker
class DockerImage(object):
"""
This class hold all the image information we could possibly need.
"""
def __init__(self,
repository,
tag,
img_id,
created,
size,
virtual_size):
sel... |
from operator import itemgetter
from jinja2 import nodes
from jinja2.ext import Extension
from flask import g, request, current_app, _request_ctx_stack, url_for
try:
from markupsafe import Markup as jinja2_Markup, escape as jinja2_escape
except ImportError:
from jinja2._markupsafe import Markup as jinja2_Marku... |
from starthinker.util.data import get_rows
def weather_gov_test(config, task):
print('testing weather_gov connector')
if 'verify' in task['weather_gov']:
rows = get_rows(config, task['auth'],
task['weather_gov']['verify']['read'])
station_ids = task['weather_gov']['verify']['station_i... |
import functools
from typing import Any, Callable
from unittest import skipUnless
from tests import os_release
def skip_unless_codename(codename, message: str) -> Callable[..., Callable[..., None]]:
if type(codename) is str:
codename = [codename]
def _wrap(func: Callable[..., None]) -> Callable[...,... |
NET_STATUS_ACTIVE = 'ACTIVE'
NET_STATUS_BUILD = 'BUILD'
NET_STATUS_DOWN = 'DOWN'
NET_STATUS_ERROR = 'ERROR'
PORT_STATUS_ACTIVE = 'ACTIVE'
PORT_STATUS_BUILD = 'BUILD'
PORT_STATUS_DOWN = 'DOWN'
PORT_STATUS_ERROR = 'ERROR'
FLOATINGIP_STATUS_ACTIVE = 'ACTIVE'
FLOATINGIP_STATUS_DOWN = 'DOWN'
FLOATINGIP_STATUS_ERROR = 'ERR... |
from __future__ import absolute_import, division, unicode_literals, print_function
import collections
import contextlib
import logging
import logging.handlers
import sys
import threading
import uuid
import warnings
# Support order in python 2.7 and 3
try:
from collections import OrderedDict
except ImportError:
... |
""" Setup script for PyPI """
import os
from setuptools import setup
from ConfigParser import SafeConfigParser
settings = SafeConfigParser()
settings.read(os.path.realpath('dynamic_dynamodb/dynamic-dynamodb.conf'))
setup(
name='dynamic-dynamodb',
version=settings.get('general', 'version'),
license='Apach... |
# coding: utf-8
import logging
from collections import defaultdict
from ppyt.filters import FilterBase
from ppyt.models.orm import start_session, FinancialData
logger = logging.getLogger(__name__)
class CashFlowIncreasingFilter(FilterBase):
"""営業キャシュフローが毎年している銘柄を絞り込みます。"""
_findkey = '営業キャッシュフローフィルタ' # フィル... |
import requests
from cloudbot import hook
from cloudbot.util import web, formatting
shortcuts = {
'cloudbot': 'CloudBotIRC/CloudBot'
}
@hook.command("ghissue", "issue")
def issue_cmd(text):
"""<username|repo> [number] - gets issue [number]'s summary, or the open issue count if no issue is specified"""
a... |
import yaml
class Worldly:
def __init__(self, filename="i18n.yaml"):
with open(filename, "r", encoding="utf-8") as f:
self.messages = yaml.load(f)
self.use_language = "en" # default; please override
self.config = {
"master_fallback": "en",
... |
from unittest import TestCase
from mock import Mock
from cloudshell.cp.aws.domain.services.ec2.route_table import RouteTablesService
class TestRouteTableService(TestCase):
def setUp(self):
self.ec2_session = Mock()
self.reservation = Mock()
self.vpc_id = 'vpc-id'
self.vpc = Mock... |
import os
import sys
# load modules from parent dir
sys.path.insert(1, os.path.dirname(sys.path[0]))
from mozharness.mozilla.testing.gaia_test import GaiaTest
from mozharness.mozilla.testing.unittest import TestSummaryOutputParserHelper
class GaiaBuildIntegrationTest(GaiaTest):
def __init__(self, require_confi... |
from django.db import models
from django.contrib.auth.models import User
class LibraryUser(models.Model):
user = models.OneToOneField(User)
# Link to photo probably gravatar
photo = models.CharField(max_length=100, null=True)
phone = models.CharField(max_length=40, null=True)
def __unicode__(sel... |
# PR#192, dir(func) and dir(method) returning []
def test1():
'Test function 1'
pass
def test2(a, b=2, c=3):
pass
attrs = dir(test1)[:]
for attr in ['__doc__', '__name__', 'func_code', 'func_defaults',
'func_doc', 'func_globals', 'func_name']:
attrs.remove(attr)
assert not a... |
import datetime
from pathlib import Path
from unittest.mock import patch
import pytest
from freezegun import freeze_time
from augur import utils
class TestUtils:
def test_ambiguous_date_to_date_range_not_ambiguous(self):
assert utils.ambiguous_date_to_date_range("2000-03-29", "%Y-%m-%d") == (
... |
"""Defines the high-level Fisher estimator class."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import contextlib
import itertools
import numpy as np
from tensorflow.contrib.kfac.python.ops import utils
from tensorflow.python.framework import ops as ... |
from cStringIO import StringIO
import ConfigParser
from datetime import date, datetime
import fnmatch
import os
from paver.easy import *
# this pulls in the sphinx target
from paver.doctools import html
import xmlrpclib
import zipfile
options(
plugin = Bunch(
name = 'geogig',
ext_libs = path('geog... |
"""Migrate Assessment to Assignable mixin
Revision ID: 6bed0575a0b
Revises: 262bbe790f4c
Create Date: 2016-02-03 14:39:12.737518
"""
# Disable Invalid constant name pylint warning for mandatory Alembic variables.
# pylint: disable=C0103
from alembic import op
# revision identifiers, used by Alembic.
revision = '6b... |
"""Generate an LDIF file with host information which supplements DNS."""
from collections import defaultdict
from itertools import imap
from operator import itemgetter
from Cerebrum.Utils import Factory
from Cerebrum.modules.dns import ARecord
from Cerebrum.modules.dns import DnsOwner
from Cerebrum.modules.LDIFutils ... |
"""Provides functionality to interact with humidifier devices."""
from __future__ import annotations
from datetime import timedelta
import logging
from typing import Any, final
import voluptuous as vol
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import (
ATTR_MODE,
SERVICE_T... |
import logging
from datetime import datetime
from collections import defaultdict
from functools import partial
import sqlalchemy as sa
from dateutil.parser import parse as dateutil_parse
from flask import current_app
from .exceptions import ImproperlyConfigured
from .sqla import transaction
logger = logging.getLogg... |
import os
import logging
import mirror.component as component
from mirror.pluginbase import PluginBase
import logcleantask
import taskcleantask
_plugin_name = "systemtask"
log = logging.getLogger(_plugin_name)
class SystemTask(PluginBase):
def enable(self):
event_manager = component.get("EventManager")... |
"""Fixtures for Z-Wave tests."""
import pytest
from homeassistant.components.zwave import const
from tests.async_mock import AsyncMock, MagicMock, patch
from tests.components.light.conftest import mock_light_profiles # noqa
from tests.mock.zwave import MockNetwork, MockNode, MockOption, MockValue
@pytest.fixture
d... |
"""Easier access to ID3 tags.
EasyID3 is a wrapper around mutagen.id3.ID3 to make ID3 tags appear
more like Vorbis or APEv2 tags.
"""
from fnmatch import fnmatchcase
import mutagen.id3
from mutagen import Metadata
from mutagen._util import DictMixin, dict_match
from mutagen.id3 import ID3, error, delete, ID3FileTyp... |
from __future__ import print_function
import sys, os.path, base64, json, getpass, re, itertools, uuid, zlib, struct
################################### Cryptography Libraries ###################################
# Creates two decryption functions (in global namespace), aes256_cbc_decrypt() and aes256_ofb_decrypt(),
#... |
from datetime import datetime, timedelta
from pytz import timezone
from openerp import _, api, fields, models
from openerp.exceptions import ValidationError
class Generator(models.TransientModel):
_name = "event.track.generator"
event_id = fields.Many2one(
"event.event",
string="Event",
... |
from webob import exc
from nova.api.openstack import extensions
from nova.api.openstack import wsgi
from nova.i18n import _
from nova import utils
ALIAS = "os-access-ips"
authorize = extensions.soft_extension_authorizer('compute', 'v3:' + ALIAS)
class AccessIPsController(wsgi.Controller):
def _extend_server(sel... |
'''
OpenDHT API borrowed from http://www.opendht.org.
The put, get and remove functions are generators so that we don't block the
main multitask thread while doing XML-RPC.
'''
import hashlib, multitask
from xmlrpclib import ServerProxy, Binary
_gateway = 'http://opendht.nyuld.net:5851/'
#_gateway = 'http://p... |
import bpy
import sys, subprocess, re
from netrender.utils import *
BLENDER_PATH = sys.argv[0]
def commandToTask(command):
i = command.index("|")
ri = command.rindex("|")
return (command[:i], command[i+1:ri], command[ri+1:])
def taskToCommand(task):
return "|".join(task)
def... |
from __future__ import print_function, division, absolute_import
import functools
import sys
import weakref
import llvmlite.llvmpy.core as lc
import llvmlite.llvmpy.passes as lp
import llvmlite.binding as ll
import llvmlite.ir as llvmir
from numba import config, utils
from numba.runtime.atomicops import remove_redun... |
import unittest
from sql import Table, Literal
from sql.operators import And, Not, Less, Equal, NotEqual, In
class TestOperators(unittest.TestCase):
table = Table('t')
def test_and(self):
and_ = And((self.table.c1, self.table.c2))
self.assertEqual(str(and_), '("c1" AND "c2")')
self.a... |
from __future__ import unicode_literals
import frappe, unittest
import requests
from frappe.model.delete_doc import delete_doc
from frappe.utils.data import today, add_to_date
from frappe import _dict
from frappe.limits import update_limits, clear_limit
from frappe.utils import get_url
from frappe.core.doctype.user.u... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Retrieve and interpolate data for Earth Orientation and timescales conversions
"""
import logging
from pathlib import Path
from inspect import isclass
from pkg_resources import iter_entry_points
from ..config import config
from ..errors import EopError, ConfigError
_... |
"""
Genrate Test Points
-
Provided by Honeybee 0.0.66
Args:
_testSurface: Test surface as a Brep.
_gridSize: Size of the test grid.
_distBaseSrf: Distance from base surface.
moveTestMesh_: Set to 'False' if you want test mesh not to move. Default is 'True'.
Returns:
... |
import logging as logging_
logging = logging_.getLogger('WILMA.streaming.RTSPserver')
import gst.rtspserver
import gstutils
import glib, gobject
import socket
class RTSPserver:
def __init__(self, profile='L16', channels=2, source='audiotestsrc',
startCallback=None
):
prof... |
"""This script is used to synthesize generated parts of this library."""
import synthtool as s
import synthtool.gcp as gcp
import synthtool.languages.ruby as ruby
import logging
import os
import re
logging.basicConfig(level=logging.DEBUG)
gapic = gcp.GAPICGenerator()
v1_library = gapic.ruby_library(
'containera... |
"""
In the 20x20 grid below, four numbers along a diagonal line have been marked in red.
NO COLOR IN A COMMENT, GO HERE:
http://projecteuler.net/problem=11
The product of these numbers is 26 * 63 * 78 * 14 = 1788696.
What is the greatest product of four adjacent numbers in any direction
(up, down, left, right, or di... |
from .geom import geom
import matplotlib.patches as patches
class geom_rect(geom):
"""
2-dimensional rectangle
Parameters
----------
xmin:
min value for x
xmax:
max value for x
ymin:
min value for y
ymax:
max value for y
color:
color of oute... |
#!/usr/bin/env python3
import requests
import re
import os
from time import sleep
def get_topic_images(topic_id):
req = requests.get('http://habrahabr.ru/post/' + str(topic_id) + '/')
result = set()
if req.status_code != 200:
return result
all_images = re.findall(r'<img\s+src="([^"]+)"', req.t... |
"""
ConfigParser
by George K. Thiruvathukal
This is a re-implementation of the ConfigParser class in Python, which I
also gave out as a homework assignment to the markup languages class.
"""
import string
class ConfigParser:
def __init__(self):
self.sections = {}
def set_property(self, section_name, pro... |
import random
from monte_fishing.game import (
Response,
Request,
)
class SecretivePlayer(object):
def __init__(self,hand):
self.name="Secretive"
self.hand = {}
self.completed = {}
for card in hand:
if card.value in self.hand:
sel... |
class MergeDict:
"""
A simple class for creating new "virtual" dictionaries that actualy look
up values in more than one dictionary, passed in the constructor.
"""
def __init__(self, *dicts):
self.dicts = dicts
def __getitem__(self, key):
for dict in self.dicts:
try:... |
import os
import re
from datetime import datetime, timedelta
from django.conf import settings
from django.core.files.storage import default_storage as storage
from django.db import transaction
from django.utils.encoding import force_text
from django_statsd.clients import statsd
from multidb import get_replica
import... |
import os
from lib.cuckoo.common.abstracts import Report
from lib.cuckoo.common.exceptions import CuckooDependencyError
from lib.cuckoo.common.exceptions import CuckooReportError
from lib.cuckoo.common.objects import File
try:
from pymongo import MongoClient
from pymongo.errors import ConnectionFailure
fr... |
from openpyxl.descriptors.serialisable import Serialisable
from openpyxl.descriptors import (
Sequence,
Typed,
Alias,
)
from openpyxl.descriptors.excel import ExtensionList
from openpyxl.descriptors.nested import (
NestedBool,
NestedInteger,
NestedSet
)
from ._chart import ChartBase
from .axis ... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
This module contains the ServerManager class, which implemnts a server manager.
Managers are command line tools used for testing transports. They simulate Tor by launching transports and providing similar environment variables as would be provided by Tor.
Managers are only... |
import markdown
from markdown.extensions.codehilite import CodeHiliteExtension
from markdown.extensions.extra import ExtraExtension
from markdown.extensions.toc import TocExtension
from django import template
from django.utils.safestring import mark_safe
register = template.Library()
@register.filter
def iteam_mark... |
#!/usr/bin/env python
"""Creates a plaidml user configuration file."""
from __future__ import print_function
import os
import sys
from six.moves import input
import numpy as np
import plaidml2 as plaidml
import plaidml2.edsl as edsl
import plaidml2.exec as plaidml_exec
import plaidml2.settings as plaidml_settings
... |
from django.conf.urls import url
from django.shortcuts import redirect
from olympia.addons.urls import ADDON_ID
from olympia.reviewers import views, views_themes
# All URLs under /editors/
urlpatterns = (
url(r'^$', views.dashboard, name='reviewers.dashboard'),
url(r'^dashboard$',
lambda request: red... |
import sys
import time
import commands
import userinterface.Client as Client
from taskbuffer.JobSpec import JobSpec
from taskbuffer.FileSpec import FileSpec
if len(sys.argv)>1:
site = sys.argv[1]
else:
site = "ANALY_BNL_ATLAS_1"
datasetName = 'panda.destDB.%s' % commands.getoutput('uuidgen')
destName = 'BN... |
#!/usr/bin/env python
import click
#from philharmonic import conf_test
import philharmonic
# TODO: combine this with schedule.py
@click.group()
def cli():
"""The philharmonic command line interface."""
pass
@cli.command('run')
@click.option('--conf', default='philharmonic.settings.base',
help... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
author: Luzius Thöny
<EMAIL>
2016
"""
import math, time, scipy
from numpy.random import *
from distutils.dir_util import mkpath
#~ from graph_tool.all import *
try:
from graph_tool.all import *
except ImportError:
pass
# a wrapper for a simple two-dimensional ma... |
"""Misc flags."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from absl import flags
from tf2_common.utils.flags._conventions import help_wrap
def define_image(data_format=True):
"""Register image specific flags.
Args:
data_format: Create a... |
#!/usr/bin/python
"""Test of find result presentation."""
from macaroon.playback import *
import utils
sequence = MacroSequence()
sequence.append(KeyComboAction("<Control>Home"))
sequence.append(KeyComboAction("<Control>F"))
sequence.append(TypeAction("orca"))
sequence.append(PauseAction(3000))
sequence.append(uti... |
#!/usr/bin/env python
from __future__ import print_function
import sys
if sys.hexversion < 0x03000000:
from future_builtins import zip, map
"""
test_N_x_M_and_collate.py
This script takes N pairs of input file pairs
(with the suffices .gene and .gwas)
... |
__source__ = 'https://leetcode.com/problems/longest-substring-with-at-most-two-distinct-characters/'
# https://github.com/kamyu104/LeetCode/blob/master/Python/longest-substring-with-at-most-two-distinct-characters.py
# Time: O(n^2)
# Space: O(1)
# Hashtable
#
# Description: Leetcode # 159. Longest Substring with At Mo... |
# card2csv.py 21/06/2015 D.J.Whale
#
# (c) 2015 D.J.Whale
#
# Read a card and write it to a csv file compatible with the maze builder
# program in Adventures in Minecraft.
import time
# Use this to force test harness that returns a test card every second
#from cardreader import tester as cardreader
# Use this to f... |
from pecan import hooks
from poppy.openstack.common import context
from poppy.openstack.common import local
class ContextHook(hooks.PecanHook):
def on_route(self, state):
context_kwargs = {}
if 'X-Project-ID' in state.request.headers:
context_kwargs['tenant'] = state.request.headers... |
import os
import sys
import re
import csv
import json
import requests
from time import sleep
from bs4 import BeautifulSoup
def round_format(nom,denom):
try:
if float(denom) > 0:
percent = 100* round(float(nom)/float(denom), 2)
else:
percent = 0
except Exception, e:
percent = 0
return percent
file_ =... |
"""
JSON Output Module
"""
import json
def jsonOutput(queryResult, separator=''):
"""
Display the data separated in JSON
"""
print json.JSONEncoder().encode(queryResult) |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Test scriptharness/commands/__init__.py
"""
from __future__ import absolute_import, division, print_function, \
unicode_literals
from contextlib import contextmanager
import logging
import mock
import os
import pprint
import scriptharness.commands ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Modbus TestKit: Implementation of Modbus protocol in python
(C)2009 - Luc Jean - <EMAIL>
(C)2009 - Apidev - http://www.apidev.fr
This is distributed under GNU LGPL license, see license.txt
"""
from __future__ import with_statement
import threading
... |
"""Common settings and globals."""
from os.path import abspath, basename, dirname, join, normpath
from sys import path
########## PATH CONFIGURATION
# Absolute filesystem path to the Django project directory:
DJANGO_ROOT = dirname(dirname(abspath(__file__)))
# Absolute filesystem path to the top-level project fold... |
# -*- coding: utf-8 -*-
'''
Create and verify ANSI X9.31 RSA signatures using OpenSSL libcrypto
'''
# python libs
from __future__ import absolute_import
import glob
import sys
import os
# salt libs
import salt.utils
# 3rd-party libs
from ctypes import cdll, c_char_p, c_int, c_void_p, pointer, create_string_buffer
fr... |
import logging
import knuckle
import ui
log = logging.getLogger("test_window")
logging.basicConfig(level=logging.INFO)
class PlayState(knuckle.State):
name = 'PlayState'
def on_post_init(self):
self.ui.add_widget(ui.TextItem, 3, 3, 'Escape to exit')
self.eb.subscribe('ui_input_press', self... |
import pytest
from nbgrader.api import MissingEntry
from nbgrader.tests.formgrader.base import BaseTestFormgrade
@pytest.mark.js
@pytest.mark.usefixtures("all_formgraders")
class TestGradebook(BaseTestFormgrade):
def test_start(self):
# This is just a fake test, since starting up the browser and formgra... |
r"""
****************************
espressopp.FixedPairDistList
****************************
.. function:: espressopp.FixedPairDistList(storage)
:param storage:
:type storage:
.. function:: espressopp.FixedPairDistList.add(pid1, pid2)
:param pid1:
:param pid2:
:type pid1:
:type pid2:
:rtype:
.... |
import os.path
dprint = print
class InputPaths(object):
"""
This object recall the list of paths in which \input will search for its files.
"""
def __init__(self):
self.directory_list = ["."]
def append(self, dirname):
self.directory_list.append(dirname)
def get_file(self, ... |
try:
from mapnik import *
except:
print '\n\nThe mapnik library and python bindings must have been compiled and \
installed successfully before running this script.\n\n'
raise
m = Map(690,690,"+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs")
m.background = Color(255,100,100,255)
road_style = Style()
#... |
import os
import numpy as np
import warnings
import sys
from numpy.testing import assert_array_equal, assert_equal, assert_raises
from bruker2nifti._getters import get_stack_direction_from_VisuCorePosition
def test_get_stack_direction_from_VisuCorePosition_OK_dummy_multiple_cases():
visu_core_position_ = np.arr... |
import numpy
import six
import chainer
from chainer import cuda
from chainer import function
from chainer.utils import type_check
class SelectItem(function.Function):
"""Select elements stored in given indices."""
def check_type_forward(self, in_types):
type_check.expect(in_types.size() == 2)
... |
import __main__
def import_to_global(modname, attrs=None, math=False):
"""
import_to_global(modname, (a,b,c,...), math): like "from modname import a,b,c,...",
but imports to global namespace (__main__).
If math==True, also registers functions with QtiPlot's math function list.
"""
import sys
import os
sys.p... |
from rasa.rasa_classifier import RasaClassifier
from util.parse_dataset import CreateJson
# Generate RASA training data from text files
jsonCreator = CreateJson()
# Acknowledgements
jsonCreator.parse_directory("/rasa/text/acknowledgement/", "/rasa/data/acknowledgement/")
# Claim Categories
jsonCreator.parse_director... |
import re
def numsplit(text):
"""\
Convert string into a list of texts and numbers in order to support a
natural sorting.
"""
result = []
for group in re.split(r'(\d+)', text):
if group:
try:
group = int(group)
except ValueError:
... |
from nova.api.openstack import api_version_request
from nova import exception
from nova import test
from nova.tests.unit.api.openstack import fakes
class APIVersionRequestTests(test.NoDBTestCase):
base_path = '/%s' % fakes.FAKE_PROJECT_ID
def test_valid_version_strings(self):
def _test_string(version... |
'''
Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Created on Jun 3, 2014
@author: dfleck
'''
class classChordClientAPI(object):
'''
This is a stub class which defines the API needed for any upper client object.
The network layer uses these me... |
import mock
from mistral.tests.api import base
from mistral.db import api as db_api
from mistral import engine
# TODO: later we need additional tests verifying all the errors etc.
TASKS = [
{
'id': "1",
'workbook_name': "my_workbook",
'execution_id': '123',
'name': 'my_task',
... |
# -*- coding: utf-8 -*-
"""
(c) 2014-2018 - Copyright Red Hat Inc
Authors:
Pierre-Yves Chibon <<EMAIL>>
"""
from __future__ import unicode_literals, absolute_import
import datetime
import gc
import logging
import time
import os
import flask
import pygit2
import pagure.doc_utils
import pagure.exceptions
impo... |
#!/usr/bin/env python
########################################################################
# $HeadURL$
# File : dirac-wms-job-delete
########################################################################
"""
Reschedule the given DIRAC job
"""
from __future__ import print_function
__RCSID__ = "$Id$"
import DI... |
import aiopg
import bcrypt
import markdown
import os.path
import psycopg2
import re
import tornado.escape
import tornado.httpserver
import tornado.ioloop
import tornado.locks
import tornado.options
import tornado.web
import unicodedata
from tornado.options import define, options
define("port", default=8888, help="run... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.