content string |
|---|
from oslo_policy import policy
from manila.policies import base
BASE_POLICY_NAME = 'share_instance:%s'
shares_policies = [
policy.DocumentedRuleDefault(
name=BASE_POLICY_NAME % 'index',
check_str=base.RULE_ADMIN_API,
description="Get all share instances.",
operations=[
... |
from spyre import server
import matplotlib.image as mpimg
class InputExample(server.Launch):
title = "Connections"
inputs = [{
"input_type": 'radiobuttons',
"options": [
{"label": "Simple App", "value": 1, "checked": True},
{"label": "Multiple Outputs", "value": 2},
... |
"""Support for Xiaomi Gateway Light."""
import logging
import struct
import binascii
from homeassistant.components.xiaomi_aqara import (PY_XIAOMI_GATEWAY,
XiaomiDevice)
from homeassistant.components.light import (ATTR_BRIGHTNESS, ATTR_RGB_COLOR,
... |
from opencivicdata import common
contact_details = {
"type": "array",
"items": {
"type": "object",
"properties": {
"type": {"type": "string", "enum": common.CONTACT_TYPES},
"value": {"type": "string"},
"note": {"type": "string", "blank": True},
"l... |
import time
import os
import random
import platform
class GolBoard(object):
"""
COMPLETE!
An introduction to python using the game of life as a problem to solve in class.
Not the most pythonic or succinct solution, but it's not meant to be.
Any live cell with fewer than two live neighbours dies,... |
from django.contrib.auth.models import Permission
from django.test import TestCase
from timepiece.tests import factories
from timepiece.tests.base import ViewTestMixin
from ..models import Business
__all__ = ['TestCreateBusinessView', 'TestDeleteBusinessView',
'TestListBusinessesView']
class TestCreateBus... |
import operator
from spec import Spec, eq_, ok_, raises, assert_raises
from invoke.collection import Collection
from invoke.tasks import task, Task
from invoke.vendor import six
from invoke.vendor.six.moves import reduce
from _utils import load, support_path
@task
def _mytask():
six.print_("woo!")
def _func()... |
import abc
import six
from tacker.api import extensions
from tacker.openstack.common import log as logging
LOG = logging.getLogger(__name__)
@six.add_metaclass(abc.ABCMeta)
class ServicePluginBase(extensions.PluginInterface):
"""Define base interface for any Advanced Service plugin."""
supported_extension... |
"""
Copyright (C) 2014 Maruf Maniruzzaman
Website: http://cosmosframework.com
Author: Maruf Maniruzzaman
License :: OSI Approved :: MIT License
"""
from cosmos.service import requesthandler
import tornado.ioloop
import tornado.web
import tornado.template
from tornado import gen
from cosmos.service.utils import M... |
import os
import time
import requests
from email.utils import parsedate
from django.core.management.base import BaseCommand
from django.db import transaction
from django.db.models import Count
from django.conf import settings
from multigtfs.models import Feed
from txc.ie import get_timetables
from ...models import Oper... |
import proto # type: ignore
from google.cloud.securitycenter_v1p1beta1.types import finding as gcs_finding
from google.cloud.securitycenter_v1p1beta1.types import resource as gcs_resource
__protobuf__ = proto.module(
package='google.cloud.securitycenter.v1p1beta1',
manifest={
'NotificationMessage',
... |
from PyQt4 import QtCore, QtGui, QtOpenGL
import math
import numpy
import numpy.linalg as linalg
import OpenGL
OpenGL.ERROR_CHECKING = True
from OpenGL.GL import *
from OpenGL.GLU import *
class PyGLWidget(QtOpenGL.QGLWidget):
# Qt signals
signalGLMatrixChanged = QtCore.pyqtSignal()
rotationBeginEvent = Q... |
"""
:module:`openquake.sub.tests.slab.rupture_test_sa06`
"""
import os
import unittest
import numpy as np
from openquake.sub.slab.rupture import create_ruptures
from openquake.hazardlib.scalerel.strasser2010 import StrasserIntraslab
BASE_DATA_PATH = os.path.dirname(__file__)
class RuptureCreationSATest(unittest.Te... |
# vim: set fileencoding=utf-8:
'''
vinergy.util.util
~~~~~~~~~~~~~~~~~
Handy tools for Vinergy.
'''
import mimetypes
import pygments.lexers
from pygments import formatters
from pygments import highlight
from pygments.lexers import guess_lexer
from .formatter import MyHTMLFormatter
from .filter import TabFilt... |
import sys
#--------------------------------------------------
def print_multiplication_table():
for x in range(1, 13):
print
for y in range(1, 13):
print '{:>4}'.format(x * y),
print
print
print_multiplication_table()
print
print
#------------------------------------... |
from test_support import verbose
import rfc822, sys
try:
from cStringIO import StringIO
except ImportError:
from StringIO import StringIO
def test(msg, results):
fp = StringIO()
fp.write(msg)
fp.seek(0)
m = rfc822.Message(fp)
i = 0
for n, a in m.getaddrlist('to') + m.getaddrlist('cc'):
... |
"""support classes for parsing autoSql generated objects"""
import string
def strArraySplit(commaStr):
"parser for comma-separated string list into a list"
if len(commaStr) == 0:
return []
strs = commaStr.split(",")
if commaStr.endswith(","):
strs = strs[0:-1]
return strs
... |
"""
Different implementations of persistent storage endpoints.
Each storage should be a subclass of :py:class:`~.Storage`. For more information
refer to that class.
Currently this is only aimed at disk-storage but other implementations would be
possible. But then some variable names and function signatures *might* ne... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import os
from django.conf.global_settings import *
INSTALLED_APPS = (
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.messages',
'django.contrib.staticfile... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import os
from django.core import serializers
from django.db import models, migrations
def load_data(apps, schema_editor):
"""
Load fixtures for MockPerson, MockPet and MockLocation
"""
fixtures = os.path.abspath(os.path.join(os.path.d... |
import time
import datetime
import logging
logger = logging.getLogger(__name__)
import re
import urllib2
from .. import translit
from ..htmlcleanup import stripHTML
from .. import exceptions as exceptions
from base_adapter import BaseSiteAdapter, makeDate
def getClass():
return FicBookNetAdapter
logger = lo... |
#!/usr/bin/env python2.7
import numpy as np
#with alpha = 0.71 we get Online: CTR=?? Took ??
# Offline: TAKES TOO LONG!!!! Evaluated 51586/1040000 lines. CTR = 0.055907
# Implementation of Linear UCB
class LinUCB:
all_articles = []
A_zero = np.identity(36)
A_zero_inv... |
"""SCons.Platform.cygwin
Platform-specific initialization for Cygwin systems.
There normally shouldn't be any need to import this module directly. It
will usually be imported through the generic SCons.Platform.Platform()
selection method.
"""
#
# __COPYRIGHT__
#
# Permission is hereby granted, free of charge, to an... |
import argparse
from pipeline.backend.pipeline import PipeLine
from pipeline.component import DataIO
from pipeline.component import Evaluation
from pipeline.component import HeteroLinR
from pipeline.component import Intersection
from pipeline.component import Reader
from pipeline.interface import Data
from pipeline.u... |
''' restart.py '''
import heron.tools.cli.src.python.args as args
import heron.tools.cli.src.python.cli_helper as cli_helper
import heron.tools.cli.src.python.jars as jars
import argparse
import re
def create_parser(subparsers):
""" Create the parse for the update command """
parser = subparsers.add_parser(
... |
"""empty message
Revision ID: 554d7eb589fa
Revises: 10186c00258b
Create Date: 2014-12-30 16:37:22.683386
"""
# revision identifiers, used by Alembic.
revision = '554d7eb589fa'
down_revision = '10186c00258b'
from alembic import op
import sqlalchemy as sa
def upgrade():
### commands auto generated by Alembic - plea... |
from django.conf.urls import url
from django.contrib.auth.decorators import login_required
from views import *
urlpatterns = [
url(r'confirmar/crear/$',login_required(ConfirmacionesCrearView.as_view()), name="confirmaciones_crear"),
url(r'confirmar/lista/$',(ConfirmacionListView.as_view()), name="confirmacion... |
# encoding: utf-8
# module PyQt4.QtGui
# from /usr/lib/python2.7/dist-packages/PyQt4/QtGui.so
# by generator 1.135
# no doc
# imports
import PyQt4.QtCore as __PyQt4_QtCore
class QFontInfo(): # skipped bases: <type 'sip.simplewrapper'>
"""
QFontInfo(QFont)
QFontInfo(QFontInfo)
"""
def bold(self): ... |
#!/usr/bin/env python
from runtest import TestBase
class TestCase(TestBase):
def __init__(self):
TestBase.__init__(self, 'std-string', lang='C++', result="""
# DURATION TID FUNCTION
[71555] | main() {
7.549 us [71555] | std_string_arg("Hello"s);
0.218 us [71555] | std_string_a... |
import os
from config_system import lex
class LexWrapper:
def __init__(self, ignore_missing, verbose=False):
self.lexers = []
self.sources = []
self.root_dir = None
self.ignore_missing = ignore_missing
self.verbose = verbose
def open(self, fname):
"""Open the ... |
#!/usr/bin/env python3
import pytest
import subprocess
import testinfra
import json
from settings import *
container_name = 'ps-docker-test-inspect'
@pytest.fixture(scope='module')
def inspect_data():
docker_id = subprocess.check_output(
['docker', 'run', '--name', container_name, '-e', 'MYSQL_ROOT_PASSW... |
import pyos
application = None
def alphabetize(apps):
appd = {}
for a in apps: appd[a.title] = a
return [appd[a] for a in sorted(appd)]
def getVisibleAppList():
visible = []
for app in state.getApplicationList().getApplicationList():
if app.getIcon() != False and not app.parameters.get("h... |
import os
import sys
import logging
import traceback
from dlab.fab import *
from dlab.meta_lib import *
from dlab.actions_lib import *
from fabric.api import *
if __name__ == "__main__":
instance_class = 'notebook'
local_log_filename = "{}_{}_{}.log".format(os.environ['conf_resource'], os.environ['edge_user_na... |
import signal
import time
import requests
import numpy
import pyaudio
import ntplib
import math
from multiprocessing import Queue
from river.status_codes import status_code
from river.config import config
from river.utilities import sine, silence
def query_configuration(name, address, port):
r = requests.post("h... |
from __future__ import unicode_literals
import frappe
from frappe import _
from frappe.utils import get_fullname, flt, cstr
from frappe.model.document import Document
from erpnext.hr.utils import set_employee_name
from erpnext.accounts.party import get_party_account
from erpnext.accounts.general_ledger import make_gl_e... |
from apiclient.discovery import build
from apiclient.errors import HttpError
from oauth2client.tools import argparser
DEVELOPER_KEY = "AIzaSyAPLpQrMuQj6EO4R1XwjwS2g47dqpFXW3Y"
YOUTUBE_API_SERVICE_NAME = "youtube"
YOUTUBE_API_VERSION = "v3"
def youtube_search():
youtube = build(YOUTUBE_API_SERVICE_NAME, YOUTUBE_A... |
import logging
from django.db import transaction
from cookiecutter_manager.helpers.helper_cookiecutter import \
clone_cookiecutter_template
from experiments_manager.consumers import \
send_exp_package_creation_status_update
from git_manager.helpers.git_helper import GitHelper
from git_manager.models import Gi... |
'''
Todo:
- Wait for delete methods to be fixed
'''
import sys
import os
import time
import datetime
import logging
gaj_path = '/home/jendrik/projects/RedNotebook/ref/gnome-activity-journal/'
sys.path.insert(0, gaj_path)
sys.path.insert(0, os.path.join(gaj_path, 'src'))
import gtk
import gobject
try:
import zei... |
from django.test import TestCase
from core.registration.static.models import StaticReg
from core.registration.static.models import StaticRegKeyValue
from systems.tests.utils import create_fake_host
from mozdns.domain.models import Domain
from mozdns.address_record.models import AddressRecord
from mozdns.ip.utils impo... |
from __future__ import absolute_import
from __future__ import print_function
from __future__ import unicode_literals
import os
import random
import tempfile
import pytest
from django.conf import settings
from django.core.management import call_command
from django.test.utils import override_settings
from mock import p... |
#!/usr/bin/env python
# encoding: utf-8
#####################################
# REGISTER EXAMPLE #
#####################################
'''
This file shows a simple agent which just registers
a service in the DF. Then it searches for the same service
in order to check it is properly registered.
You ne... |
"""Automatically port legacy passes tests to be lit tests
"""
import argparse
import glob
import os
import subprocess
import sys
script_dir = os.path.dirname(__file__)
test_dir = os.path.join(os.path.dirname(script_dir), 'test')
def warn(msg):
print(f'WARNING: {msg}', file=sys.stderr)
def port_test(args, tes... |
from typing import TYPE_CHECKING
from azure.core.configuration import Configuration
from azure.core.pipeline import policies
from azure.mgmt.core.policies import ARMHttpLoggingPolicy
from ._version import VERSION
if TYPE_CHECKING:
# pylint: disable=unused-import,ungrouped-imports
from typing import Any
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*- #
from __future__ import unicode_literals
# import pelican_gist
AUTHOR = u'Ross Donaldson'
SITENAME = u'Strangely Specific and Very Odd'
SITEURL = 'http://blog.gastove.com'
THEME = '../lib/theme/svbhack'
USER_LOGO_URL = 'http://www.gravatar.com/avatar/a942cea13e537bb0ea7... |
"""Model zoo for pre-trained models."""
from __future__ import print_function
__all__ = ['get_model_file', 'purge']
import os
import zipfile
from ..utils import download, check_sha1
_model_sha1 = {name: checksum for checksum, name in [
('44335d1f0046b328243b32a26a4fbd62d9057b45', 'alexnet'),
('f27dbf2dbd5ce9a... |
"""Version information for Invenio-Ext.
This file is imported by ``invenio_ext.__init__``,
and parsed by ``setup.py``.
"""
__version__ = "0.3.3.dev20151007" |
try:
from unittest.mock import create_autospec
except ImportError:
from mock import create_autospec
try:
from unittest.mock import MagicMock
except ImportError:
from mock import MagicMock
import time
import pytest
from retry.api import retry_call
from retry.api import retry
def test_retry(monkeypa... |
from unittest import TestCase
from replayer.url_filter import URLFilter
from replayer.config_constants import ConfigConstants
from replayer.log_constants import LogConstants
class TestURLFilter(TestCase):
def test_proceed_empty_filter(self):
url_filter = URLFilter({})
request_data = {}
se... |
# -*- coding: utf-8 -*-
'''
:copyright: (c) 2015 by Allenta Consulting S.L. <<EMAIL>>.
:license: BSD, see LICENSE.txt for more details.
'''
from __future__ import absolute_import
import json
from contextlib import closing
from datetime import datetime
from requests import Session, Request
from requests.exceptions imp... |
from setuptools import setup, find_packages
import sys, os, glob
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
version = '0.9.14'
if sys.version_info < (2,7):
print('SDST requires python 2.7 or higher')
exit(1)
setup(name='SDST',
version=version,
descrip... |
import glob
import re
import yaml
import os
import argparse
import MethBase
import MethBase_Utils
assemToOrg = {"hg18":"Human", "hg19":"Human", "mm9":"Mouse", "mm10":"Mouse", "gorGor3":"Gorilla", \
"panTro2":"Chimp", "tair10":"Arabidopsis", "canFam3":"Dog", "danRer7":"Zebrafish"}
defaultSamples = ["Ho... |
from __future__ import division
from __future__ import absolute_import
import os
import random
import numpy
import sys
from io import open
from itertools import imap
def main():
#testfile is the file name of the dataset in dir /cs170data in project file
testfile = raw_input(u"""Welcome to Zi Zhou Feature Seletion Al... |
from abc import ABCMeta, abstractproperty, abstractmethod
from gtd.utils import cached_property
class Domain(object):
"""Encapsulate all domain-dependent information.
To add a new domain, create a subclass of domain (in a separate file)
and then add it to the get_domain method below.
"""
__metac... |
# -*- coding: utf-8 -*-
from openerp.osv import fields, osv, orm
from openerp.tools.translate import _
from openerp import tools, SUPERUSER_ID
class oph_cim10_category(osv.osv):
def name_get(self, cr, uid, ids, context = None):
if isinstance(ids, (list, tuple)) and not len(ids):
return []
... |
"""
Django settings for app project.
For more information on this file, see
https://docs.djangoproject.com/en/1.7/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.7/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import... |
from assertpy import assert_that,fail
class TestIn(object):
def test_is_in(self):
assert_that(1).is_in(1)
assert_that(1).is_in(1,2,3)
assert_that('foo').is_in('foo', 'bar', 'baz')
assert_that([1,2,3]).is_in([1,2,3], [2,3,4], [3,4,5])
def test_is_in_failure(self):
try:
... |
from __future__ import absolute_import
import operator
def _validate_squeeze_index(i, sz):
try:
i = operator.index(i)
except TypeError:
raise TypeError('nd.squeeze() requires an int or '
+ 'tuple of ints for axis parameter')
if i >= 0:
if i >= sz:
ra... |
# -*- coding: utf-8 -*-
from __future__ import (
absolute_import,
division,
print_function,
unicode_literals
)
import copy
import six
class PytingoData(object):
"""Settings flexible mapper"""
__slots__ = [
"_data_dict", "_meta_field", "_separator", "_wildcard", "_list_accessor", "_... |
#!/usr/bin/env python
"""
sentry.utils.runner
~~~~~~~~~~~~~~~~~~~
:copyright: (c) 2012 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
from __future__ import absolute_import, print_function
from logan.runner import run_app, configure_app
import base64
import os
impo... |
"""
Tests of the SubsectionGrade classes.
"""
from ddt import data, ddt, unpack
from ..models import PersistentSubsectionGrade
from ..subsection_grade import CreateSubsectionGrade, ReadSubsectionGrade
from .base import GradeTestBase
from .utils import mock_get_score
@ddt
class SubsectionGradeTest(GradeTestBase):
... |
"""Yaml helpers."""
import os
import yaml
def read(yaml_filename):
"""Reads and loads yaml file specified by |yaml_filename|."""
if not os.path.exists(yaml_filename):
raise Exception('Yaml file %s does not exist.' % yaml_filename)
with open(yaml_filename) as file_handle:
return yaml.load(... |
"""
Script to upload and refresh the geo_substation table in the swith_chile
OCM database. The only inputs needed are the connection parameters.
"""
from __future__ import print_function
import pandas as pd
import sys, os.path, psycopg2
from csv import writer, reader
from unidecode import unidecode
from pyproj import... |
""" Base class for the modules """
import os
import re
import sys
from optparse import OptionParser, OptionGroup
from util_functions import get_modname
from templates import Templates
class ModTool(object):
""" Base class for all modtool command classes. """
def __init__(self):
self._subdirs = ['lib... |
""" tlog tests """
import os
import ast
import stat
import time
import socket
from tempfile import mkdtemp
import pexpect
import pytest
from misc import check_recording, ssh_pexpect, mklogfile, \
check_outfile, check_journal, mkcfgfile, \
journal_find_last
class TestTlogRec:
"... |
# -*- coding: utf-8 -*-
##################################################################################################
import logging
import os
import xbmcgui
import xbmcaddon
import read_embyserver as embyserver
from utils import language as lang
###############################################################... |
#!/bin/env python
import sys, os
from optparse import OptionParser
#ApkToolPath = os.path.dirname(os.path.abspath(__file__))
ApkToolPath = 'c:\\\\android\\\\apkjet'
def sign_apk(fn, fn_new):
if not fn_new:
file_path, ext = os.path.splitext(fn)
fn_new = r'%s_signed%s' %(file_path, ext)
cmd = ... |
"""
The test file for all standalone tests that doesn't
requires a shared Serve instance.
"""
import sys
import socket
import pytest
import requests
import ray
from ray import serve
from ray.cluster_utils import Cluster
from ray.serve.constants import SERVE_PROXY_NAME
from ray.serve.utils import (block_until_http_rea... |
from spack import *
class RAskpass(RPackage):
"""Cross-platform utilities for prompting the user for credentials or a
passphrase, for example to authenticate with a server or read a protected
key. Includes native programs for MacOS and Windows, hence no 'tcltk' is
required. Password entry can be invok... |
import unittest
import mock
from touchdown.core import errors, serializers
from touchdown.aws.cloudfront import Distribution
from . import aws
from touchdown.aws.session import session
class TestMetadata(unittest.TestCase):
def test_waiter_waity_enough(self):
waiter = session.get_waiter_model("cloudfr... |
import os
from ducktape.services.background_thread import BackgroundThreadService
from kafkatest.directory_layout.kafka_path import KafkaPathResolverMixin, CORE_LIBS_JAR_NAME, CORE_DEPENDANT_TEST_LIBS_JAR_NAME
from kafkatest.services.security.security_config import SecurityConfig
from kafkatest.version import DEV_BRA... |
import re
import logging
from autotest.client.shared import error
from virttest import utils_misc
from virttest import utils_test
from virttest import data_dir
@error.context_aware
def run(test, params, env):
"""
change a removable media:
1) Boot VM with QMP/human monitor enabled.
2) Connect to QMP/... |
"""
Daplug keyset creation class
"""
from conv import *
class KeySet:
"""@KeySet"""
# Key constants
USAGE_GP = 0x01
"""@KeySet.USAGE_GP"""
USAGE_GP_AUTH = 0x02
"""@KeySet.USAGE_GP_AUTH"""
USAGE_HOTP = 0x03
"""@KeySet.USAGE_HOT... |
import os
from setuptools import setup
# Functions #########################################################
def package_data(pkg, root_list):
"""Generic function to find package_data for `pkg` under `root`."""
data = []
for root in root_list:
for dirname, _, files in os.walk(os.path.join(pkg, ro... |
import sys, configparser, os.path, os
# translation of mpi Device keys to udev attributes
mpi2udev = {
'vendorid': 'ATTRS{idVendor}=="%s"',
'productid': 'ATTRS{idProduct}=="%s"',
'usbvendor': 'ATTRS{vendor}=="%s"',
'usbmodel': 'ATTRS{model}=="%s"',
'usbproduct': 'ATTRS{product}=="%s"',
'usbmanu... |
from __future__ import absolute_import
import re
import logging
from collections import defaultdict
from aleph.core import db, celery, USER_QUEUE, USER_ROUTING_KEY
from aleph.text import match_form
from aleph.model import Entity, EntityIdentity, Reference, Document, Alert
from aleph.model.common import merge_data
fro... |
from nose.tools import *
import requests
import json
notification = None
auth = ('username', 'password')
def test_noAuth():
r = requests.get('http://localhost:5000/v0.1/getAvailableNotifications')
print(repr(r.text))
assert r.status_code == 401
def test_getAvailableNotifications_empty():
global auth
r = reque... |
import pytz
import datetime
from django.core.cache import cache
from readthedocs.donate.constants import OFFERS, CLICKS, VIEWS
def get_ad_day():
date = pytz.utc.localize(datetime.datetime.utcnow())
day = datetime.datetime(
year=date.year,
month=date.month,
day=date.day,
tzinf... |
import os
import sys
import shutil
import tempfile
import traceback
from .util import (
initialize_chain,
assert_equal,
start_nodes,
connect_nodes_bi,
sync_blocks,
sync_mempools,
stop_nodes,
wait_bitcoinds,
enable_coverage,
check_json_precision,
initialize_chain_clean,
)
fr... |
def getResultsFromSpecialCaseDay(string):
"""
Possible results:
"Days": [0,1,2,...,6]
"Date": "ISO 8601 DateString e.g. 2016-12-25"
"DaysOfMonth" e.g. {n: "BIWEEKLY" or "LAST" or e.g.[1,4] for first and fourth instances of day n} (can be e.g. {1:[1],2:[2,3]})
"DaysOfMonthFrequenc... |
import csv, re
def uniquifyIds():
with open('us-county-names.tsv', 'rb') as csvfile:
reader = csv.reader(csvfile, delimiter="\t")
with open('us-county-names-normalized.csv', 'wb') as csvoutfile:
writer = csv.writer(csvoutfile)
writer.writerow(reader.next())
cou... |
'''
Created on 16.04.15
@author = mharder
'''
from bonfire.dateutils import datetime_parser, datetime_converter
import arrow
import pytest
def test_datetime_parser():
now = arrow.now()
ts_tuples = [
("10 minutes ago", lambda x: x.shift(minutes=-10).\
replace(microsecond=0, tzinfo='l... |
from laman import *
class Waver:
"""
Finds distances to particular cells and groups pills into clusters
"""
class Cell:
def __init__(self, pos, distance, come_from, cluster_no):
"""
:param distance Distance from pos1
:param come_from which cell you come into... |
"""Fixtures used in tests."""
import pytest
from billabong import billabong
from billabong.settings import inventory, stores
@pytest.fixture
def record(request):
"""Import a file, return the record and delete them after the test."""
new_record = billabong.add_file('hello.txt', tags=['hello', 'ipsum'],
... |
import os
import logging
from pyramid.paster import get_appsettings
log = logging.getLogger('bodhi')
def get_configfile():
configfile = None
setupdir = os.path.join(os.path.dirname(os.path.dirname(__file__)), '..')
if configfile:
if not os.path.exists(configfile):
log.error("Cannot f... |
from calvin.actor.actor import Actor, ActionResult, condition
class Wrapper(object):
"""Wrap a token value in 'left' and 'right', i.e. 1 => ((( 1 )))"""
def __init__(self, left, right):
super(Wrapper, self).__init__()
self.left = str(left)
self.right = str(right)
def wrap(self, x)... |
print("\n##########################################")
print("##### 7.6.0 - A Plural Rule Iterator #####")
print("##########################################\n")
print("""
class LazyRules:
rules_filename = 'plural6-rules.txt'
def __init__(self):
self.pattern_file = open(self.rules_filename, encoding='ut... |
from src import BaseView, AssociationView
from src import api
from .resources import BrandResource, DistributorBillResource, DistributorResource, ProductResource, \
ProductTaxResource, StockResource, TaxResource, TagResource, ComboResource, AddOnResource, SaltResource,\
ProductDistributorResource, ProductTagRes... |
import os
import testtools
from tempest import config
from tempest.lib import exceptions
from murano_tempest_tests.tests.api.application_catalog import base
from murano_tempest_tests import utils
CONF = config.CONF
class TestRepositoryNegativeNotFound(base.BaseApplicationCatalogTest):
@classmethod
def reso... |
import os, sys, sqlite3
set_folder = u'settings/' # папка настроек
wtfbase = set_folder+u'wtfbase.db' # старые определения
wtfbase2 = set_folder+u'wtfbase2.db' # новые определения
print 'Updater for Isida Jabber Bot from 1.8-1.91 to 2.00'
print '(c) Disabler Production Lab.'
os.system('rm -rf '+wtfbase2)
wtf1 ... |
import os
from setuptools import find_packages
from setuptools import setup
PACKAGE_ROOT = os.path.abspath(os.path.dirname(__file__))
with open(os.path.join(PACKAGE_ROOT, 'README.rst')) as file_obj:
README = file_obj.read()
# NOTE: This is duplicated throughout and we should try to
# consolidate.
SETUP_B... |
from django.http import Http404
from django.contrib.auth import login, logout
from django.utils.http import base36_to_int
from django.utils.translation import ugettext_lazy as _
from rest_framework import generics
from rest_framework import exceptions
from rest_framework.views import APIView
from rest_framework.respon... |
"""
Helper functions for the accounts API.
"""
import hashlib
from django.conf import settings
from django.core.exceptions import ObjectDoesNotExist
from django.core.files.storage import get_storage_class
from django.contrib.staticfiles.storage import staticfiles_storage
from microsite_configuration import microsite
... |
#!/usr/bin/env python
"""xml2json.py Convert XML to JSON
Relies on ElementTree for the XML parsing. This is based on
pesterfish.py but uses a different XML->JSON mapping.
The XML->JSON mapping is described at
http://www.xml.com/pub/a/2006/05/31/converting-between-xml-and-json.html
Rewritten to a command line utili... |
from __future__ import print_function
import sys
import jinja2
import six
from timid import environment
from timid import steps
from timid import utils
class Context(object):
"""
Represent the context for executing a test file. This contains
the environment, template variables, test steps, and any oth... |
import requests, json, logging
from requests.auth import HTTPDigestAuth
from django.core.mail import send_mail
from django.core.management.base import BaseCommand, CommandError
from django.utils import timezone
from django.contrib.auth.models import User
from silo.models import *
from silo.gviews_v4 import *
logger =... |
"""
Provider related utilities
"""
from libcloud.utils.misc import get_driver as _get_provider_driver
from libcloud.utils.misc import set_driver as _set_provider_driver
from libcloud.compute.types import Provider, DEPRECATED_RACKSPACE_PROVIDERS
from libcloud.compute.types import OLD_CONSTANT_TO_NEW_MAPPING
__all__ = ... |
from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar
import warnings
from azure.core.async_paging import AsyncItemPaged, AsyncList
from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error
from azure.core.pipeline ... |
import os, os.path
import shlex
import sys
from . import debug, info, warning, error, fatal
from .tools import *
def _path_sub(src, dest, subst='"${src}"'):
if src in dest:
b, e = dest.split(src, 1)
while e.startswith(os.path.sep):
e = e[1:]
ps = []
y = ps.append
if b: y(b)
y(subst)
if e: y(e)
re... |
""" Parses http://www.live-footballontv.com for info about live matches """
import re
from datetime import datetime, timedelta
import requests
from bs4 import BeautifulSoup
url = 'https://www.live-footballontv.com'
headers = {'User-Agent': 'Football Push Notifications'}
def convert_date(date):
"""
Returns ... |
__revision__ = "test/Fortran/FORTRANFILESUFFIXES2.py rel_2.5.1:3735:9dc6cee5c168 2016/11/03 14:02:02 bdbaddog"
import TestSCons
from common import write_fake_link
_python_ = TestSCons._python_
_exe = TestSCons._exe
test = TestSCons.TestSCons()
write_fake_link(test)
test.write('myfortran.py', r"""
import getopt
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.