content stringlengths 4 20k |
|---|
# coding: utf-8
from __future__ import unicode_literals
import re
from .common import InfoExtractor
from ..compat import compat_urlparse
from ..utils import (
int_or_none,
parse_filesize,
unified_strdate,
)
class EsriVideoIE(InfoExtractor):
_VALID_URL = r'https?://video\.esri\.com/watch/(?P<id>[0-9]... |
import os
from datetime import timedelta
from flask import Flask
from flask.ext.assets import Bundle
from mooddiary.core import db, migrate, assets, jwt
from mooddiary.bundles import js, css
from mooddiary.views import main
from mooddiary.api import api
from mooddiary.auth import auth
from mooddiary.models import Ent... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
ANSIBLE_METADATA = {
'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'
}
import traceback
from ansible.module_utils.basic import AnsibleModule, missing_required_lib
MATRIX_IMP_ERR = None
t... |
# -*- coding: utf-8 -*-
#
# Project Unit Tests
#
# To run this script use:
# python web2py.py -S eden -M -R applications/eden/modules/unit_tests/s3db/project.py
#
import unittest
from gluon import *
from gluon.storage import Storage
from gluon.dal import Row
from eden.project import S3ProjectActivityModel
# ========... |
"""
Provides encoded I{marshaller} classes.
"""
from logging import getLogger
from suds import *
from suds.mx import *
from suds.mx.literal import Literal
from suds.mx.typer import Typer
from suds.sudsobject import Factory, Object
from suds.xsd.query import TypeQuery
log = getLogger(__name__)
#
# Add encoded extensi... |
from __future__ import unicode_literals
import frappe
from frappe.utils import flt, cstr, nowdate, nowtime
from erpnext.stock.utils import update_bin
from erpnext.stock.stock_ledger import update_entries_after
def repost(only_actual=False, allow_negative_stock=False, allow_zero_rate=False, only_bin=False):
"""
Repo... |
from selenium.webdriver.remote.webdriver import WebDriver as RemoteWebDriver
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
from .service import Service
class WebDriver(RemoteWebDriver):
"""
Wrapper to communicate with PhantomJS through Ghostdriver.
You will need to follow... |
from subprocess import Popen, PIPE
import sys
import json
# List openvz hosts
vzhosts = ['vzhost1', 'vzhost2', 'vzhost3']
# Add openvz hosts to the inventory and Add "_meta" trick
inventory = {'vzhosts': {'hosts': vzhosts}, '_meta': {'hostvars': {}}}
# default group, when description not defined
default_group = ['vzg... |
import datetime
from oslo_utils import timeutils
import keystone.tests.unit as tests
class TestTimeUtils(tests.BaseTestCase):
def test_parsing_date_strings_returns_a_datetime(self):
example_date_str = '2015-09-23T04:45:37.196621Z'
dt = timeutils.parse_strtime(example_date_str, fmt=tests.TIME_FO... |
import os
import logging
import socket
import select
import threading
import logging
import logging.config
import json
import inspect
import base64
import six
from collections import defaultdict
from scruffy.plugin import Plugin
import voltron
from .plugin import APIPlugin
log = logging.getLogger('api')
version = ... |
"""Pushes native libraries to a device.
"""
import optparse
import os
import sys
BUILD_ANDROID_DIR = os.path.join(os.path.dirname(__file__), os.pardir)
sys.path.append(BUILD_ANDROID_DIR)
from pylib import constants
from util import build_device
from util import build_utils
from util import md5_check
def DoPush(op... |
"""Retry decorators for calls raising exceptions.
For internal use only; no backwards-compatibility guarantees.
This module is used mostly to decorate all integration points where the code
makes calls to remote services. Searching through the code base for @retry
should find all such places. For this reason even plac... |
# -*- coding: utf-8 -*-
"""
***************************************************************************
v_net.py
--------
Date : December 2015
Copyright : (C) 2015 by Médéric Ribreux
Email : medspx at medspx dot fr
******************************************... |
"""Strategies for placing variables on parameter servers.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
from tensorflow.python.framework import tensor_shape
class GreedyLoadBalancingStrategy(object):
"""Returns the least-loaded ... |
"""Tests for the bob_emploi.importer.city_locations module."""
from os import path
import unittest
from bob_emploi.data_analysis.lib import mongo
from bob_emploi.data_analysis.importer import city_locations
from bob_emploi.frontend.api import geo_pb2
class CityLocationsImporterTestCase(unittest.TestCase):
"""Un... |
""" OpenERP core exceptions.
This module defines a few exception types. Those types are understood by the
RPC layer. Any other exception type bubbling until the RPC layer will be
treated as a 'Server error'.
If you consider introducing new exceptions, check out the test_exceptions addon.
"""
# kept for backward comp... |
# -*- coding:utf-8 -*-
import sys
"""
主要分为两种情况,排列在x垂直的直线上,斜率相同时
"""
class Point(object):
def __init__(self, x = 0, y = 0):
self.x = x
self.y = y
class Solution(object):
def cross(self, p1, p2):
return p1.x * p2.y - p2.x * p1.y
def onSegment(self, p1, p2, p3):
if cross(p3 - p1, p3 - p2) == 0:
retur... |
"""Tests Google Test's throw-on-failure mode with exceptions disabled.
This script invokes gtest_throw_on_failure_test_ (a program written with
Google Test) with different environments and command line flags.
"""
__author__ = '<EMAIL> (Zhanyong Wan)'
import gtest_test_utils
import os
import unittest
# Constants.
... |
"""
Decorator module, see http://pypi.python.org/pypi/decorator
for the documentation.
"""
__version__ = '3.3.3'
__all__ = ["decorator", "FunctionMaker", "partial"]
import sys, re, inspect
try:
from functools import partial
except ImportError: # for Python version < 2.5
class partial(object):
"A sim... |
# -*- coding: utf-8 -*-
"""
taiga_ncurses.core
~~~~~~~~~~~~~~~~~~
"""
import functools
from concurrent.futures import wait
import urwid
from taiga_ncurses.ui import views
from taiga_ncurses import controllers
from taiga_ncurses.config import settings
class TaigaCore:
def __init__(self, executor, settings, aut... |
'''
Created on 2013 3 13
@author: Tom Schaul (<EMAIL>)
Managing states and observations, for different types of games
'''
import pygame
from pybrain.utilities import setAllArgs
from ontology import RotatingAvatar, BASEDIRS, GridPhysics, ShootAvatar, kill_effects
from core import Avatar
from tools import listRotate
... |
__revision__ = "src/engine/SCons/Tool/mssdk.py 4043 2009/02/23 09:06:45 scons"
"""engine.SCons.Tool.mssdk
Tool-specific initialization for Microsoft SDKs, both Platform
SDKs and Windows SDKs.
There normally shouldn't be any need to import this module directly.
It will usually be imported through the generic SCons.To... |
#!/usr/bin/env python
import logging
import os
import sys
logging.basicConfig(format='%(asctime)s %(levelname)-7s %(thread)-5d %(name)s %(filename)s:%(lineno)s | %(funcName)s | %(message)s', datefmt='%Y-%m-%d %H:%M:%S')
logging.getLogger().setLevel(logging.DEBUG)
logging.disable(logging.NOTSET)
logging.debug("Importi... |
import pickle
import time
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.metrics import get_scorer
from sklearn.model_selection import GridSearchCV, RandomizedSearchCV
from sklearn.model_selection import cross_validate, learning_curve, train_test_split
from .print_message import Pri... |
import tdl
from clubsandwich.geom import Point, Size
from clubsandwich.ui import RectView
from ui.camera import Camera
from util.cursor import Cursor
class GameWindow(RectView):
def __init__(self, game_context, **kwargs):
super().__init__(fill=True, **kwargs)
self.game_context = game_context
... |
"""
Template file used by ExpGenerator to generate the actual
permutations.py file by replacing $XXXXXXXX tokens with desired values.
This permutations.py file was generated by:
'/Users/ronmarianetti/nupic/eng/lib/python2.6/site-packages/nupic/frameworks/opf/expGenerator/ExpGenerator.py'
"""
import os
from nupic.swa... |
"""
sample router manager.
(un-)instantiate routers
Usage example:
PYTHONPATH=. ./bin/ryu-manager --verbose \
ryu.services.protocols.vrrp.manager \
ryu.services.protocols.vrrp.dumper \
ryu.services.protocols.vrrp.sample_manager
"""
from ryu.base import app_manager
from ryu.contro... |
#!/usr/bin/python
#EandM.py
import sys
import sympy.galgebra.GA as GA
import sympy.galgebra.latex_ex as tex
import sympy,numpy,time
if __name__ == '__main__':
metric = '1 0 0,'+\
'0 1 0,'+\
'0 0 1'
gamma_x,gamma_y,gamma_z = GA.MV.setup('gamma_x gamma_y gamma_z',metric,True)
tex.... |
from collections import defaultdict
from . import builtin
from .. import options as opts
from .path import buildpath, relname, within_directory
from .file_types import FileList, make_file_list, static_file
from ..backends.compdb import writer as compdb
from ..backends.make import writer as make
from ..backends.ninja i... |
import hashlib
import os.path
try:
import json
except ImportError:
import simplejson as json
def save_hashes(hashes_file_path, hashes):
try:
with open(hashes_file_path, "wt") as hashes_file:
json.dump(hashes, hashes_file, indent=4, separators=(",", ": "))
except:
print "ER... |
from changes.api.serializer import serialize
from changes.config import db
from changes.models.project import ProjectOption
from changes.testutils import TestCase
class JobStepCrumblerTestCase(TestCase):
def test_associated_snapshot_image(self):
project = self.create_project()
build = self.create... |
#!/usr/bin/python
# tv_sort.py
# detects and sorts tv shows automatically based on filename
import os
import shutil
import re
import xmlrpclib
words = r'([\'\w\.\- ]+?)'
spacers = re.compile(r'[\s_\-\.]+')
show_filename = re.compile(words + r'S(\d+)\s?EP?(\d+)', re.IGNORECASE)
show_filename_2 = re.compile(words + r'... |
import abc
import logging
import re
from django.utils.translation import ugettext_lazy as _
from keystoneauth1 import exceptions as keystone_exceptions
from keystoneclient.v3 import client as v3_client
import six
from openstack_auth import exceptions
from openstack_auth import utils
LOG = logging.getLogger(__name__)... |
import struct
import urllib2,urllib
import re
import json
import math
CRYPT_XXTEA_DELTA= 0x9E3779B9
headers = [('Accept','text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8'),( 'Connection','Keep-Alive')]
class Crypt_XXTEA:
_key=None
def setKey(self,key):
if isinstance(key, basestring):
... |
"""Control flow statements: loops, conditionals, etc."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.contrib.autograph.utils import builtins
from tensorflow.python.data.ops import dataset_ops
from tensorflow.python.framework import ops
f... |
import sys
import os
import glob
import time
basepath = os.path.abspath(os.path.dirname(__file__))
sys.path.insert(0, os.path.join(basepath, 'gen-py.twisted'))
sys.path.insert(0, glob.glob(os.path.join(basepath, '../../lib/py/build/lib.*'))[0])
from ThriftTest import ThriftTest
from ThriftTest.ttypes import Xception, ... |
import item, time, hasdata
from item import (Item, GroupItem)
from pulp_auto.pulp import Request
from pulp_auto import strip_url
TASK_WAITING_STATE = 'waiting'
TASK_READY_STATE = 'ready'
TASK_RUNNING_STATE = 'running'
TASK_FINISHED_STATE = 'finished'
TASK_ERROR_STATE = 'error'
TASK_CANCELLED_STATE = 'cancelled'
class... |
from __future__ import absolute_import
import os
import posixpath
from collections import Iterable
from .compatibility import string as compatible_string
from .compatibility import PY3
from .util import Memoizer
if PY3:
import urllib.parse as urlparse
else:
import urlparse
class Link(object):
"""Wrapper arou... |
import matplotlib.pyplot as plt
import nest
import numpy as np
# seed NumPy RNG to ensure identical results for runs with random placement
np.random.seed(1234567)
def beautify_layer(layer, fig=plt.gcf(), xlabel=None, ylabel=None,
xlim=None, ylim=None, xticks=None, yticks=None, dx=0, dy=0):
"""... |
"""
MultiCall - a class which inherits its methods from a Tkinter widget (Text, for
example), but enables multiple calls of functions per virtual event - all
matching events will be called, not only the most specific one. This is done
by wrapping the event functions - event_add, event_delete and event_info.
MultiCall r... |
import os
#import new
import logging
log = logging.getLogger("Thug")
acropdf = ( 'acropdf.pdf',
'pdf.pdfctrl',
'CA8A9780-280D-11CF-A24D-444553540000', )
shockwave = ( 'shockwaveflash.shockwaveflash',
'shockwaveflash.shockwaveflash.9',
'shockwaveflash.shockwav... |
"""Unittest for testing utilities,"""
# pytype: skip-file
import logging
import os
import tempfile
import unittest
import mock
from apache_beam.io.filesystem import BeamIOError
from apache_beam.io.filesystems import FileSystems
from apache_beam.testing import test_utils as utils
class TestUtilsTest(unittest.TestC... |
def timeseries_slice(self, date_time_index, start, end):
"""
Returns a frame split on the specified start and end date/times.
Splits a time series frame on the specified start and end date/times.
:param date_time_index: List of date/time strings. DateTimeIndex to conform all series to.
:param star... |
"""Configuration for JavaScript library dependencies."""
__author__ = 'Sean Lip'
# A dict mapping dependency ids to the Angular module names they
# should insert when the Angular app is first initialized.
DEPENDENCIES_TO_ANGULAR_MODULES_DICT = {
'codemirror': ['ui.codemirror'],
'google_maps': ['ui.map'],
... |
import os
import json
import superdesk
import pymongo
from superdesk import get_resource_service
from flask import current_app as app
"""
App initialization information, maps resource name to the file containing the data
and the index to be created for the resource and the boolean flag to update the
resource or not.... |
from __future__ import (absolute_import, division,
print_function, unicode_literals)
from nose.plugins.attrib import attr
from nose.tools import assert_raises, raises
import numpy as np
from numpy.random import RandomState
from scipy.stats import norm
from ..npc import (fisher,
... |
"""
Save media files.
"""
from __future__ import (absolute_import, division,
print_function, unicode_literals)
import os
import sys
from datetime import datetime
import tarfile
import tempfile
from optparse import make_option
import re
from django.conf import settings
from django.core.managemen... |
#!/usr/bin/python
"""A session demonstration app."""
import calendar
from datetime import datetime
import sys
import cherrypy
from cherrypy.lib import sessions
from cherrypy._cpcompat import copyitems
page = """
<html>
<head>
<style type='text/css'>
table { border-collapse: collapse; border: 1px solid #663333; }
th ... |
"""
Acceptance tests for Video Times(Start, End and Finish) functionality.
"""
from flaky import flaky
from .test_video_module import VideoBaseTest
import unittest
class VideoTimesTest(VideoBaseTest):
""" Test Video Player Times """
def setUp(self):
super(VideoTimesTest, self).setUp()
def test_v... |
# coding: utf-8
from __future__ import unicode_literals
import re
from .common import InfoExtractor
from ..utils import (
determine_ext,
ExtractorError,
float_or_none,
get_element_by_class,
int_or_none,
js_to_json,
NO_DEFAULT,
parse_iso8601,
remove_start,
strip_or_none,
url... |
from gnuradio import gr
from gnuradio import blocks
from gnuradio import filter
import sys, time
try:
from gnuradio import analog
except ImportError:
sys.stderr.write("Error: Program requires gr-analog.\n")
sys.exit(1)
try:
import scipy
from scipy import fftpack
except ImportError:
sys.stderr.... |
#!/usr/bin/env python2.7
"""
File : rocker_board.py
Author : Bjorn Barrefors <bjorn dot peter dot barrefors AT cern dot ch>
Description: Distribute data in system to keep it balanced (like a rocker board)
"""
# system modules
import logging
import sys
import getopt
import datetime
import operator
from loggin... |
import os
import re
import base64
import logging
from autotest.client.shared import error
from virttest import virsh
from virttest.remote import LoginError
from virttest.virt_vm import VMError
from virttest.aexpect import ShellError
from virttest.utils_test import libvirt
from virttest.libvirt_xml import vm_xml
from vi... |
import html5lib
import html5lib.treebuilders.dom
# Expected use:
# curl --compressed http://www.whatwg.org/specs/web-apps/current-work/ >current-work
# python specextract.py
#
# Generates current-work-canvas.xhtml, for use by gentest.py to create the annotated spec document
def extract():
parser = html5lib.ht... |
"""
Selectors tests, common for all backends
"""
import re
import weakref
from twisted.trial import unittest
from scrapy.http import TextResponse, HtmlResponse, XmlResponse
from scrapy.selector import XmlXPathSelector, HtmlXPathSelector, \
XPathSelector
from scrapy.utils.test import libxml2debug
class XPathSele... |
import io
import random
import docker
import six
from .base import BaseAPIIntegrationTest, TEST_IMG
import pytest
class TestRegressions(BaseAPIIntegrationTest):
def test_443_handle_nonchunked_response_in_stream(self):
dfile = io.BytesIO()
with pytest.raises(docker.errors.APIError) as exc:
... |
"""
@file coi-services/mi.idk/package_driver.py
@author Bill French
@brief Main script class for running the package_driver process
"""
import sys
import os.path
import zipfile
import subprocess
import shutil
import re
import yaml
from mi.core.log import get_logger ; log = get_logger()
from mi.idk import prompt
from... |
import subprocess
import os
devnull=open('/dev/null','w')
# creates the temporary directory to store the jar files
def createTempDirectoryIfDoesntExist():
import shutil
newpath = r'/tmp/mydep'
if os.path.exists(newpath):
shutil.rmtree(newpath)
os.makedirs(newpath)
# copies depedencies to folder
def copyDep... |
from functools import wraps
from django.utils.decorators import decorator_from_middleware_with_args, available_attrs
from django.utils.cache import patch_cache_control, add_never_cache_headers
from django.middleware.cache import CacheMiddleware
def cache_page(*args, **kwargs):
"""
Decorator for views that tri... |
"""
Temporal Memory implementation in Python.
"""
from nupic.research.temporal_memory import TemporalMemory
from nupic.bindings.algorithms import Connections, ConnectionsCell
class FastTemporalMemory(TemporalMemory):
"""
Class implementing the Temporal Memory algorithm.
Uses C++ Connections data structure fo... |
""" This simple code is desinged to teach a basic user to read in the files in python, simply find what proportion of males and females survived and make a predictive model based on this
Author : AstroDave
Date : 18th September, 2012
"""
import csv as csv
import numpy as np
csv_file_object = csv.reader(open('train.... |
import os
try:
from cStringIO import StringIO
except ImportError:
from StringIO import StringIO
from django.core.management import CommandError
from django.core.management.commands.compilemessages import compile_messages
from django.test import TestCase
LOCALE='es_AR'
class MessageCompilationTests(TestCase)... |
import res_company
import purchase |
"""
Clickjacking Protection Middleware.
This module provides a middleware that implements protection against a
malicious site loading resources from your site in a hidden frame.
"""
from django.conf import settings
from django.utils.deprecation import MiddlewareMixin
class XFrameOptionsMiddleware(MiddlewareMixin):
... |
"""
Danish-language mappings for language-dependent features of
reStructuredText.
"""
__docformat__ = 'reStructuredText'
directives = {
# language-dependent: fixed
u'giv agt': 'attention',
u'pas på': 'caution',
u'kode': 'code',
u'kode-blok': 'code',
u'kildekode': 'code',
u'f... |
"""
mbed SDK
Copyright (c) 2011-2013 ARM Limited
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in wr... |
from __future__ import absolute_import
from __future__ import division
from __future__ import unicode_literals
__all__ = [
"__title__", "__summary__", "__uri__", "__version__", "__author__",
"__email__", "__license__", "__copyright__",
]
__title__ = "bcrypt"
__summary__ = "Modern password hashing for your sof... |
"""
ToggleWhiteSpace Sublime Plugin.
Toggle showing white space in Sublime Text.
```
//////////////////////////////////
// Toggle White Space Command
//////////////////////////////////
{
"caption": "Toggle White Space",
"command": "toggle_white_space"
},
```
Licensed under MIT
Cop... |
# built-in
from __future__ import print_function
# PyOpenGL
from OpenGL import GL
# pyglet
import pyglet
from pyglet.window import key
# gui
from .node import GUINode
# css
from css.color import Color
class Caret(GUINode):
def __init__(self):
super(Caret, self).__init__()
self.__glyph = None
@property
... |
#!/usr/bin/python
"""
Copyright 2014 Google Inc.
Use of this source code is governed by a BSD-style license that can be
found in the LICENSE file.
Test download.py
TODO(epoger): Create a command to update the expected results (in
self._output_dir_expected) when appropriate. For now, you should:
1. examine the resu... |
from openstack_dashboard.test.integration_tests import helpers
from openstack_dashboard.test.integration_tests.pages import loginpage
class TestLogin(helpers.BaseTestCase):
"""This is a basic scenario test:
* checks that the login page is available
* logs in as a regular user
* checks that the user ho... |
# -*- coding: utf-8 -*-
# 非gevent版本
import os
import requests
import time
from lxml import html
def get_response(url):
# 填充请求的头部
headers = {
"headers" : "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2062.94 Safari/537.36"
}
response = requests.get(url... |
import arrow
import datetime
from pytz import utc, timezone # flake8: noqa
tzinfo = getattr(datetime, 'tzinfo', object)
def utcnow():
"""Get tz aware datetime object.
Remove microseconds which can't be persisted by mongo so we have
the values consistent in both mongo and elastic.
"""
if hasattr(... |
"""Insecure client-server interoperability as a unit test."""
from concurrent import futures
import unittest
import grpc
from src.proto.grpc.testing import test_pb2
from tests.interop import _intraop_test_case
from tests.interop import methods
from tests.interop import server
class InsecureIntraopTest(_intraop_tes... |
import copy
import logging
import optparse
import os
import shlex
import socket
import sys
from telemetry.core import platform
from telemetry.core import util
from telemetry.internal.browser import browser_finder
from telemetry.internal.browser import browser_finder_exceptions
from telemetry.internal.browser import pr... |
import os
import re
def myreadlines(f, newline):
buf = ""
while True:
while newline in buf:
pos = buf.index(newline)
yield buf[:pos]
buf = buf[pos + len(newline):]
chunk = f.read(4096)
if not chunk:
yield buf
break
buf += chunk
webIndex='available_packages_by_name.html'
webCRAN='https://cran.... |
from __future__ import unicode_literals
import boto3
import sure # noqa
import re
from moto import mock_opsworks
@mock_opsworks
def test_create_layer_response():
client = boto3.client('opsworks', region_name='us-east-1')
stack_id = client.create_stack(
Name="test_stack_1",
Region="us-east-1"... |
"""
REST API test suite - ceph cluster import
"""
from json.decoder import JSONDecodeError
import pytest
from usmqe.api.tendrlapi import cephapi
LOGGER = pytest.get_logger('test_cluster', module=True)
"""@pylatest default
Setup
=====
"""
"""@pylatest default
Teardown
========
"""
"""@pylatest api/ceph.cluster_im... |
from temboo.core.choreography import Choreography
from temboo.core.choreography import InputSet
from temboo.core.choreography import ResultSet
from temboo.core.choreography import ChoreographyExecution
import json
class Leaderboard(Choreography):
def __init__(self, temboo_session):
"""
Create a n... |
import numpy as np
from numpy.testing import assert_array_equal
from nose import with_setup
from nose.tools import assert_equal
try:
from nose.tools import assert_is
except ImportError:
from landlab.testing.tools import assert_is
from landlab.grid.raster_gradients import (
calc_grad_across_cell_corners)
... |
from math import ceil
from django.db import IntegrityError, connection, models
from django.db.models.sql.constants import GET_ITERATOR_CHUNK_SIZE
from django.test import TestCase, skipIfDBFeature, skipUnlessDBFeature
from .models import (
MR, A, Avatar, Base, Child, HiddenUser, HiddenUserProfile, M, M2MFrom,
... |
from nose.tools import *
import mock
import mendeley
import time
import datetime
from tests.base import OsfTestCase
from website.util import web_url_for
from website.addons.mendeley import model
from website.addons.mendeley.api import APISession
class MendeleyApiTestCase(OsfTestCase):
def setUp(self):
... |
"""Extensions to allow HTTPS requests with SSL certificate validation."""
import re
import socket
import ssl
import boto
from boto.compat import six, http_client
class InvalidCertificateException(http_client.HTTPException):
"""Raised when a certificate is provided with an invalid hostname."""
def __init__... |
from testtools import testcase
from sahara.tests.integration.configs import config as cfg
from sahara.tests.integration.tests import base as b
from sahara.tests.integration.tests import edp
from sahara.tests.integration.tests import scaling
from sahara.tests.integration.tests import swift
from sahara.utils import edp ... |
""" Management of documents for AXDebugging.
"""
import axdebug, gateways
import pythoncom
from util import _wrap, _wrap_remove, RaiseNotImpl, trace
from win32com.server.util import unwrap
import codecontainer
import contexts
from win32com.server.exception import Exception
import win32api, winerror, os, string, sys
#... |
"""Compute global interface information, including public information, dependencies, and inheritance.
Computed data is stored in a global variable, |interfaces_info|, and written as
output (concretely, exported as a pickle). This is then used by the IDL compiler
itself, so it does not need to compute global informatio... |
import unittest
import os
from configuration import Builder
import configuration
import shell
from tests import testhelper
class ConfigurationTestCase(unittest.TestCase):
def setUp(self):
self.workdirectory = os.path.dirname(os.path.realpath(__file__))
# reset global shell variables
shel... |
"""
Copyright (C) since 2013 Calliope contributors listed in AUTHORS.
Licensed under the Apache 2.0 License (see LICENSE file).
objective.py
~~~~~~~~~~~~
Objective functions.
"""
import pyomo.core as po
from calliope.core.util.tools import load_function
def minmax_cost_optimization(backend_model):
"""
Mi... |
# coding: utf-8
"""
OpenAPI spec version:
Generated by: https://github.com/swagger-api/swagger-codegen.git
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
... |
"""
Tests for L{twisted.python.versions}.
"""
from __future__ import division, absolute_import
import sys
import operator
from io import BytesIO
from twisted.python.versions import getVersionString, IncomparableVersions
from twisted.python.versions import Version, _inf
from twisted.python.filepath import FilePath
f... |
# -*- coding: utf-8 -*-
from django.db.models import Model
from django.contrib.auth.models import Permission
from django.contrib.contenttypes.models import ContentType
class ObjectPermissionBackend(object):
def has_perm(self, user_obj, perm, obj=None):
if user_obj and user_obj.is_superuser:
re... |
""" Monthly precip reliability"""
import calendar
import datetime
import psycopg2.extras
import numpy as np
import pandas as pd
from pyiem import network
from pyiem.plot.use_agg import plt
from pyiem.util import get_autoplot_context, get_dbconn
from pyiem.exceptions import NoDataFound
def get_description():
""" ... |
import webob
from nova.compute import api as compute_api
from nova import exception
from nova.openstack.common import jsonutils
from nova import test
from nova.tests.api.openstack import fakes
def fake_get_vnc_console(self, _context, _instance, _console_type):
return {'url': 'http://fake'}
def fake_get_spice_c... |
from __future__ import absolute_import
import pytest
from ansible.modules.source_control.gitlab.gitlab_user import GitLabUser
def _dummy(x):
"""Dummy function. Only used as a placeholder for toplevel definitions when the test is going
to be skipped anyway"""
return x
pytestmark = []
try:
from .gi... |
"""Detect changes in Ansible code."""
from __future__ import absolute_import, print_function
import re
import os
from lib.util import (
ApplicationError,
SubprocessError,
MissingEnvironmentVariable,
CommonConfig,
display,
)
from lib.http import (
HttpClient,
urlencode,
)
from lib.git im... |
from __future__ import absolute_import
from __future__ import unicode_literals
from .. import commands
from dnf.i18n import _
import dnf.exceptions
import logging
logger = logging.getLogger("dnf")
class EraseCommand(commands.Command):
"""Erase command."""
aliases = ('erase', 'remove')
summary = _("Remo... |
from gnuradio import gr, gr_unittest, analog, blocks
class test_dpll_bb(gr_unittest.TestCase):
def setUp(self):
self.tb = gr.top_block()
def tearDown(self):
self.tb = None
def test_dpll_bb_001(self):
# Test set/gets
period = 1.0
gain = 0.1
op = an... |
"""Implementation of JSONDecoder
"""
import re
import sys
import struct
from django.utils.simplejson.scanner import make_scanner
c_scanstring = None
__all__ = ['JSONDecoder']
FLAGS = re.VERBOSE | re.MULTILINE | re.DOTALL
def _floatconstants():
_BYTES = '7FF80000000000007FF0000000000000'.decode('hex')
if sys... |
from sqlalchemy import Boolean, Column, ForeignKey, Integer, String
from neutron.db import model_base
class VlanAllocation(model_base.BASEV2):
"""Represents allocation state of vlan_id on physical network."""
__tablename__ = 'hyperv_vlan_allocations'
physical_network = Column(String(64), nullable=False,... |
#!/usr/bin/env python
import sys
import time
from termcolor import colored
from pymmspa4pg import *
source_list = []
target_list = []
def load_routing_options(
sources_file_path,
targets_file_path,
options_file_path):
with open(sources_file_path) as sources_file:
source_list = [so... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.