content stringlengths 4 20k |
|---|
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'network'}
import re
import time
from copy import deepcopy
from ansible.module_utils.basic import Ansib... |
import time
from typing import List, TypeVar
from psycopg2.extensions import cursor
from psycopg2.sql import SQL, Composable, Identifier
CursorObj = TypeVar('CursorObj', bound=cursor)
def do_batch_update(cursor: CursorObj,
table: str,
assignments: List[Composable],
... |
"""
Test methods in twisted.internet.threads and reactor thread APIs.
"""
from __future__ import division, absolute_import
import sys, os, time
from twisted.trial import unittest
from twisted.python.compat import _PY3
from twisted.internet import reactor, defer, interfaces, threads, protocol, error
from twisted.pyt... |
microcode = '''
# FSQRT
''' |
from osv import fields, osv
class accounting_report(osv.osv_memory):
_name = "accounting.report"
_inherit = "account.common.report"
_description = "Accounting Report"
_columns = {
'enable_filter': fields.boolean('Enable Comparison'),
'account_report_id': fields.many2one('account.financ... |
"""This example creates a redirect creative associated with a given advertiser.
To get a size ID, run get_size.py.
"""
import argparse
import sys
from apiclient import sample_tools
from oauth2client import client
# Declare command-line flags.
argparser = argparse.ArgumentParser(add_help=False)
argparser.add_argumen... |
"""Regular expression based lexer."""
__author__ = ('<EMAIL> (Robert Walker)',
'<EMAIL> (Andy Perelson)')
from closure_linter.common import tokens
# Shorthand
Type = tokens.TokenType
class Tokenizer(object):
"""General purpose tokenizer.
Attributes:
mode: The latest mode of the tokenizer. T... |
import os
import re
from sos.plugins import Plugin, RedHatPlugin, UbuntuPlugin, DebianPlugin
from sos.utilities import is_executable
class IprConfig(Plugin, RedHatPlugin, UbuntuPlugin, DebianPlugin):
"""IBM Power RAID storage adapter configuration information
"""
plugin_name = 'iprconfig'
def check_... |
"""This module stores information and functionality that relates to plurals."""
languages = {
'af': (u'Afrikaans', 2, '(n != 1)'),
'ak': (u'Akan', 2, 'n > 1'),
'am': (u'Amharic', 2, 'n > 1'),
'an': (u'Aragonese', 2, '(n != 1)'),
'ar': (u'Arabic', 6,
'n==0 ? 0 : n==1 ? 1 : n==2 ? 2 : n%100>=3 && n%100<=10 ? 3 :... |
import settestpath
import unittest
from up2date_client import haltree
class HalDeviceTests(unittest.TestCase):
def test_no_parent(self):
properties = { 'info.udi' : 'foo/bar/disk/3' }
device = haltree.HalDevice(properties)
self.assertEquals(None, device.parent_udi)
def test_with_p... |
#!/usr/bin/env python
"""
Declare the helper functions for the framework.
"""
from collections import defaultdict
from framework.lib.filelock import FileLock
import logging
import multiprocessing
import os
import re
import pprint
import random
import string
import sys
import threading
import time
import base64
import ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# This is very different to AboutModules in Ruby Koans
# Our AboutMultipleInheritance class is a little more comparable
#
from runner.koan import *
from another_local_module import *
from local_module_with_all_defined import *
class AboutModules(Koan):
def test_i... |
import getpass
import os
import luigi.contrib.hadoop
import luigi.contrib.hdfs
from nose.plugins.attrib import attr
import unittest
try:
from snakebite.minicluster import MiniCluster
except ImportError:
raise unittest.SkipTest('To use minicluster, snakebite must be installed.')
@attr('minicluster')
class M... |
def WebIDLTest(parser, harness):
parser.parse("""
typedef long mylong;
typedef long? mynullablelong;
interface Foo {
const mylong X = 5;
const mynullablelong Y = 7;
const mynullablelong Z = null;
void foo(mylong arg);
};
""")
results = parser.finish()... |
# -*- coding: utf-8 -*-
import urlparse
import datetime
from openerp import api, fields, models, tools
class BaseConfiguration(models.TransientModel):
""" Inherit the base settings to add a counter of failed email + configure
the alias domain. """
_inherit = 'base.config.settings'
fail_counter = fi... |
import jinja2
from django.template.loader import render_to_string
from django_jinja import library
from bedrock.thunderbird.details import thunderbird_desktop
from bedrock.base.urlresolvers import reverse
from lib.l10n_utils import get_locale
@library.global_function
@jinja2.contextfunction
def download_thunderbird(... |
from rope.base import codeanalyze
def get_indents(lines, lineno):
return codeanalyze.count_line_indents(lines.get_line(lineno))
def find_minimum_indents(source_code):
result = 80
lines = source_code.split('\n')
for line in lines:
if line.strip() == '':
continue
result = m... |
import os
from pypers.core.step import CmdLineStep
from pypers.utils import utils
from pypers.utils.samplesheet import SampleSheet
class CasavaDemux(CmdLineStep):
spec = {
"name": "CasavaDemux",
"version": "1.8.2",
"descr": [
"Runs Casava demultiplexing"
],
"url... |
"""Johnny's main caching functionality."""
import re
import time
from uuid import uuid4
try:
from hashlib import md5
except ImportError:
from md5 import md5
import localstore
import signals
from johnny import settings
from johnny.decorators import wraps, available_attrs
from transaction import TransactionMan... |
from HTMLComponent import HTMLComponent
from GUIComponent import GUIComponent
from enigma import eEPGCache, eListbox, eListboxPythonMultiContent, gFont, \
RT_HALIGN_LEFT, RT_HALIGN_RIGHT, RT_HALIGN_CENTER, RT_VALIGN_CENTER
from Tools.Alternatives import CompareWithAlternatives
from Tools.LoadPixmap import LoadPixmap... |
"""
Cache robots.txt contents.
"""
from .. import robotparser2
from ..containers import LFUCache
from ..decorators import synchronized
from ..lock import get_lock
# lock objects
cache_lock = get_lock("robots.txt_cache_lock")
robot_lock = get_lock("robots.txt_robot_lock")
class RobotsTxt (object):
"""
Thread... |
from __future__ import absolute_import, unicode_literals
import warnings
class FeedParserDict(dict):
keymap = {'channel': 'feed',
'items': 'entries',
'guid': 'id',
'date': 'updated',
'date_parsed': 'updated_parsed',
'description': ['summary', '... |
import datetime
import os
import shutil
import stat
import tempfile
class RecordsCollection:
def __init__(self, last_sent, config_dir):
from azure.cli.telemetry.components.telemetry_logging import get_logger
self._last_sent = last_sent
self._next_send = last_sent
self._records = [... |
from os.path import join, exists, getsize
from homura import download as fetch
import requests
from utils import check_create_folder
from mixins import VerbosityMixin
import settings
class RemoteFileDoesntExist(Exception):
pass
class IncorrectSceneId(Exception):
pass
class Downloader(VerbosityMixin):
... |
# -*- coding: utf-8 -*-
"""
werkzeug.contrib.wrappers
~~~~~~~~~~~~~~~~~~~~~~~~~
Extra wrappers or mixins contributed by the community. These wrappers can
be mixed in into request objects to add extra functionality.
Example::
from werkzeug.wrappers import Request as RequestBase
fr... |
import numpy
from chainer import cuda
from chainer import function
from chainer.utils import type_check
class MeanSquaredError(function.Function):
"""Mean squared error (a.k.a. Euclidean loss) function."""
def check_type_forward(self, in_types):
type_check.expect(in_types.size() == 2)
type_... |
#!/usr/bin/python
import pickle
import random
wordlength = 3
def process_word(w,g):
w=w.lower()
for i in range(0,len(w)-(wordlength-1)):
chunk=w[i:i+wordlength]
if g.has_key(chunk) and g[chunk]:
g[chunk]+=1
else:
g[chunk]=1
def process_text(filename,g):
f=open(filename,"r")
for s in f.readlines():
... |
"""
Tests for file field behavior, and specifically #639, in which Model.save()
gets called *again* for each FileField. This test will fail if calling a
ModelForm's save() method causes Model.save() to be called more than once.
"""
import os
import shutil
import unittest
from django.core.files.uploadedfile import Sim... |
import re
from datetime import datetime
from collections import defaultdict
from bs4 import BeautifulSoup
from pyquery import PyQuery
from ilms import exception
class ParseResult:
def __init__(self, body=None):
self.soup = BeautifulSoup(body, 'lxml') if body else None
self.result = []
se... |
import re
import binascii
from email.mime.text import MIMEText
from email.header import Header
from hashlib import sha256
from email.MIMEMultipart import MIMEMultipart
from email.mime.nonmultipart import MIMENonMultipart
from twisted.logger import Logger
from leap.bitmask.mail import walk
from pixelated.adapter.mode... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {
'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'
}
try:
from pyVmomi import vim, vmodl
except ImportError:
pass
from ansible.module_utils.basic import AnsibleMo... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = r'''
---
module: purefa_volume
version_added: '2.4'
short_description: Manag... |
from pandas import DataFrame
import numpy as np
import pandas as pd
from pandas.util import testing as tm
class TestToCSV(object):
def test_to_csv_quotechar(self):
df = DataFrame({'col': [1, 2]})
expected = """\
"","col"
"0","1"
"1","2"
"""
with tm.ensure_clean('test.csv') as path:
... |
#!/usr/bin/env python
from lxml import objectify
import argparse
import os
import codecs
import gzip
# init constants and vars
RAWDATADIR = 'opengov.cat/rawdata/xml/' # use 'wget -r -np http://opengov.cat/rawdata/xml/ to download files'
start = {}
end = {}
entity = {}
# load entities
def read():
files = [ f for f... |
from onecodex.exceptions import OneCodexException, PlottingException
from onecodex.lib.enums import AbundanceMetric, Rank, Metric
from onecodex.viz._primitives import (
interleave_palette,
prepare_props,
sort_helper,
get_base_classification_url,
)
class VizBargraphMixin(object):
def plot_bargraph(... |
from Proxies.Protocols.NoProtocol import NoProtocol
from Proxy import Proxy
class NoProxy(Proxy):
"""
A proxy which is actually no proxy? That's right! The NoProxy class extends from the Proxy class but is
actually no proxy but a direct connection. It's used when the program does not make use of a... |
import blackjack.cmake.cmd as cmd
from .BaseTarget import BaseTarget
from .LibTypes import LibTypes
class LibTarget(BaseTarget):
"""
Represents a CMake Library target
add_library(<name> [STATIC | SHARED | MODULE] [EXCLUDE_FROM_ALL] source1 [source2 ...])
"""
def __init__(self, name: str, sr... |
import numpy as np
import matplotlib.pyplot as plt
from scipy.signal import hamming, triang, blackmanharris
import math
from scipy.fftpack import fft, ifft, fftshift
import sys, os, functools, time
sys.path.append(os.path.join(os.path.dirname(os.path.realpath(__file__)), '../../../software/models/'))
import dftModel a... |
#!/usr/bin/env python
'''
example program to extract GPS data from a waypoint file, and create a GPX
file, for loading into google earth
'''
import sys, struct, time, os
from argparse import ArgumentParser
parser = ArgumentParser(description=__doc__)
parser.add_argument("wpfiles", metavar="WP_FILE", nargs="+")
args ... |
"""
Test the Data Aggregation Layer for Course Enrollments.
"""
import ddt
from mock import patch
from nose.tools import raises
import unittest
from django.conf import settings
from xmodule.modulestore.tests.django_utils import ModuleStoreTestCase
from xmodule.modulestore.tests.factories import CourseFactory
from enr... |
"""
Turns your complex OpenFlow switches into stupid hubs.
"""
from pox.core import core
import pox.openflow.libopenflow_01 as of
from pox.lib.util import dpidToStr
log = core.getLogger()
def _handle_ConnectionUp (event):
msg = of.ofp_flow_mod()
msg.actions.append(of.ofp_action_output(port = of.OFPP_FLOOD))
e... |
import sqlite3
from sqlalchemy import Column, Integer, String, Boolean, create_engine, ForeignKey, Float
from sqlalchemy.orm import relationship, sessionmaker
from sqlalchemy.ext.declarative import declarative_base
from settings import SQLITE_FILE
Base = declarative_base()
engine = create_engine('sqlite:////{}'.forma... |
from mox3.mox import MoxTestBase, IsA
from slimta.envelope import Envelope
from slimta.lookup.policy import LookupPolicy
from slimta.lookup.drivers.dict import DictLookup
class TestDictLookup(MoxTestBase):
def setUp(self):
super(TestDictLookup, self).setUp()
self.data = {}
self.address_p... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from zope.interface import implementer
from scrapy.interfaces import ISpiderLoader
from scrapy.utils.misc import walk_modules
from scrapy.utils.spider import iter_spider_classes
@implementer(ISpiderLoader)
class SpiderLoader(object):
"""
SpiderL... |
# encoding: utf-8
import sys
import pytest
class TestPasteCapture:
@pytest.fixture
def pastebinlist(self, monkeypatch, request):
pastebinlist = []
plugin = request.config.pluginmanager.getplugin('pastebin')
monkeypatch.setattr(plugin, 'create_new_paste', pastebinlist.append)
re... |
# -*- coding: utf-8 -*-
"""
The module contains helper functions to work with MOSEK.
Created on Tue Nov 18 10:51:14 2014
@author: Peter Wittek
"""
from __future__ import division, print_function
import numpy as np
import sys
from .sdpa_utils import convert_row_to_sdpa_index
def streamprinter(text):
"""Helper fu... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import sys
__doc__ = """%s: Remove the BOM from BOM-containing UTF-8 text files. These are, almost
without exception, produced by Microsoft products, especially under Windows.
Hey Microsoft: fuck you for deciding to produce noncompliant files instead of
adequately tra... |
# -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2014 CodUP (<http://codup.com>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affer... |
import logging
import os
from yoda import find_path
from yoda.subcommands import Subcommand
class Jump(Subcommand, object):
def setup(self, name, config, subparser):
self.subparser = subparser
self.logger = logging.getLogger(__name__)
super(Jump, self).setup(name, config, subparser)
... |
"""pydocstyle support."""
THIRD_ARG = True
try:
#: Import for pydocstyle 2.0.0 and newer
from pydocstyle import ConventionChecker as PyDocChecker
except ImportError:
#: Backward compatibility for pydocstyle prior to 2.0.0
from pydocstyle import PEP257Checker as PyDocChecker
THIRD_ARG = False
from ... |
"""
Unit tests for decorators.py.
"""
# pylint: disable=W0613
import os
import sys
import time
import traceback
import unittest
from pylib import constants
from pylib.device import decorators
from pylib.device import device_errors
from pylib.utils import reraiser_thread
# TODO(jbudorick) Remove once the DeviceUtils... |
from pyspark.ml.feature import SQLTransformer
# $example off$
from pyspark.sql import SparkSession
if __name__ == "__main__":
spark = SparkSession\
.builder\
.appName("SQLTransformerExample")\
.getOrCreate()
# $example on$
df = spark.createDataFrame([
(0, 1.0, 3.0),
... |
from .dataObject import DataObject, DatatypeProperty
class Plot(DataObject):
"""
Object for storing plot data in owmeta.
Parameters
----------
data : 2D list (list of lists)
List of XY coordinates for this Plot.
Example usage ::
>>> pl = Plot([[1, 2], [3, 4]])
>>> pl... |
"""gsutil exceptions."""
class AbortException(StandardError):
"""Exception raised when a user aborts a command that needs to do cleanup."""
def __init__(self, reason):
StandardError.__init__(self)
self.reason = reason
def __repr__(self):
return 'AbortException: %s' % self.reason
def __str__(sel... |
import calendar
import logging
from datetime import date, datetime
import cssselect as cssselect
from lxml import etree
import requests
from dateutil.relativedelta import relativedelta
from scripts.config import Configuration
# assumeinitialstates default to an assumed state if the initial state is not
# ... |
'''
Created on Jun 9, 2014
@author: lzrak47
'''
from difflib import unified_diff
import hashlib
import os
import stat
import tempfile
import pathspec
from termcolor import colored
from constants import GITIGNORE_PATH
S_IFGITLINK = 0o160000
def write_to_file(path, content, mode=None):
dir = os.path.dir... |
"""Fixer for except statements with named exceptions.
The following cases will be converted:
- "except E, T:" where T is a name:
except E as T:
- "except E, T:" where T is not a name, tuple or list:
except E as t:
T = t
This is done because the target of an "except" clause must be a
... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import json
from units.compat.mock import patch
from ansible.modules.network.netvisor import pn_role
from units.modules.utils import set_module_args
from .nvos_module import TestNvosModule, load_fixture
class TestRoleModule(Test... |
from sparktk.frame.row import Row
import sparktk.frame.schema as schema_helper
def map_columns(self, func, schema):
"""
Create a new frame from the output of a UDF which over each row of the current frame.
Notes
-----
1. The row |UDF| ('func') must return a value in the same format as
s... |
from __future__ import print_function
import json
from shifty_utils import delete_shift, update_shift, get_all_shifts, get_shifts_by_day
from shifty_utils import get_all_trades, get_trades_by_day, respond
def lambda_handler(event, context):
print("Received api request: " + json.dumps(event, indent=2))
path = ... |
from flask import Flask, request, render_template, Response
import json
import time
from bson.json_util import dumps
from pymongo import MongoClient
from flask_cors import CORS, cross_origin
app = Flask(__name__, static_url_path='/static')
CORS(app)
client = MongoClient()
db = client['nearby']
# @app.route("/")
# de... |
"""Support functions and classes implementing the KinoSearch-like external sort
merging model. This module does not contain any user-level objects.
"""
import os, tempfile
from heapq import heapify, heapreplace, heappop
from struct import Struct
from whoosh.filedb.structfile import StructFile, pack_ushort, unpack_ush... |
# environment.py
# --------------
# Licensing Information: Please do not distribute or publish solutions to this
# project. You are free to use and extend these projects for educational
# purposes. The Pacman AI projects were developed at UC Berkeley, primarily by
# John DeNero (<EMAIL>) and Dan Klein (<EMAIL>).
# Stud... |
import random
import sys
import os
# User input
user_input = input("Type in 5 integers of any sequence separated by commas. Example: 1,2,3,4,5: ")
list_input = user_input.split(",")
# Convert numbered strings into integers in list
list_int = list(map(int, list_input))
# Check Arithmetic Sequence
list_arith = list_int... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'core'}
import os
import tempfile
from ansible.module_utils.basic import AnsibleModule
def add_job(modu... |
"""The Logitech Harmony Hub integration utils."""
import aioharmony.exceptions as harmony_exceptions
from aioharmony.harmonyapi import HarmonyAPI
from homeassistant.const import CONF_HOST, CONF_NAME
from .const import DOMAIN
def find_unique_id_for_remote(harmony: HarmonyAPI):
"""Find the unique id for both webs... |
import random
from collections import defaultdict
from cloudbot import hook
from cloudbot.util import formatting
table_status = defaultdict(lambda: None)
USE_FLIPPERS = True
replacements = {
'a': 'ɐ',
'b': 'q',
'c': 'ɔ',
'd': 'p',
'e': 'ǝ',
'f': 'ɟ',
'g': 'ƃ',
'h': 'ɥ',
'i': 'ᴉ',
... |
import os
try:
import dnf
from dnf import cli, const, exceptions, subject, util
HAS_DNF = True
except ImportError:
HAS_DNF = False
def _fail_if_no_dnf(module):
"""Fail if unable to import dnf."""
if not HAS_DNF:
module.fail_json(
msg="`python2-dnf` is not installed, but it... |
import mock
from neutron.agent.linux import ip_link_support as ip_link
from neutron.tests import base
class TestIpLinkSupport(base.BaseTestCase):
IP_LINK_HELP = """Usage: ip link add [link DEV] [ name ] NAME
[ txqueuelen PACKETS ]
[ address LLADDR ]
[ broa... |
# testClasses.py
# --------------
# Licensing Information: You are free to use or extend these projects for
# educational purposes provided that (1) you do not distribute or publish
# solutions, (2) you retain this notice, and (3) you provide clear
# attribution to UC Berkeley, including a link to http://ai.berkeley.e... |
import collections
from contextlib import contextmanager
import io
import json
import os
import sys
import time
import unittest
from unittest import mock
from mlperf_logging import mllog
@contextmanager
def _captured_stdout():
cap_out = io.StringIO()
old_out = sys.stdout
try:
sys.stdout = cap_out
yield... |
# EVENT.PY
#
# THIS MODULE IMPLEMENTS SELECTOR GRAMMAR (showed below)
#
# selector := stmt*
# stmt := proto.field [op] value [ or | and ]
# proto := ip | udp | tcp | dns
# field := src | dst | src-port | dst-port | domain | ipaddress
# op := comparison | function
# comparison := < | > | == | ... |
class RepositoryBase:
"""
Implements base class for package manager repository handling
Attributes
:param object root_bind: instance of :class:`RootBind`
:param str root_dir: root directory path name
:param str shared_location: shared directory between image root
and build system root
... |
"""MonfoDB support for Muffin Framework."""
import typing as t
from muffin import Application
from motor import motor_asyncio as motor
from muffin.plugins import BasePlugin
__version__ = "0.3.5"
__project__ = "muffin-mongo"
__author__ = "Kirill Klenov <<EMAIL>>"
__license__ = "MIT"
class Plugin(BasePlugin):
"... |
import json
from django.contrib.auth.models import User
from django.http import HttpRequest
from django.test import TestCase
from django.test.utils import override_settings
from tastypie.api import Api
from tastypie.exceptions import NotRegistered, BadRequest
from tastypie.resources import ModelResource
from tastypie... |
from __future__ import print_function
import contextlib
import ctypes
import struct
import sys
import llvmlite.llvmpy.core as lc
import llvmlite.binding as ll
import numpy as np
import numba.unittest_support as unittest
from numba import cgutils, types, typing
from numba.targets import cpu
from .support import TestC... |
from __future__ import print_function, unicode_literals
from nltk.data import load
from nltk.stem.api import StemmerI
class RSLPStemmer(StemmerI):
"""
A stemmer for Portuguese.
>>> from nltk.stem import RSLPStemmer
>>> st = RSLPStemmer()
>>> # opening lines of Erico Verissimo's "Músic... |
import math
from PIL import Image
from PIL import ImageChops
from huxley.errors import TestError
def rmsdiff_2011(im1, im2):
"Calculate the root-mean-square difference between two images"
diff = ImageChops.difference(im1, im2)
h = diff.histogram()
sq = (value * (idx ** 2) for idx, value in enumerate(... |
from tempest_lib import exceptions as lib_exc
from tempest.api.network import base
from tempest import config
from tempest import test
CONF = config.CONF
class ExternalNetworksAdminNegativeTestJSON(base.BaseAdminNetworkTest):
@test.attr(type=['negative'])
@test.idempotent_id('d402ae6c-0be0-4d8e-833b-a73889... |
"""Possible vm modes for instances.
Compute instance vm modes represent the host/guest ABI used for the
virtual machine / container. Individual hypervisors may support
multiple different vm modes per host. Available vm modes for a hypervisor
driver may also vary according to the architecture it is running on.
The 'vm... |
from webdriver import Element, WebDriverException
# WebDriver specification ID: dfn-error-response-data
errors = {
"element click intercepted": 400,
"element not selectable": 400,
"element not interactable": 400,
"insecure certificate": 400,
"invalid argument": 400,
"invalid cookie domain": 40... |
# -*- coding: utf-8 -*-
"""Tests for CommandChainDispatcher."""
from __future__ import absolute_import
#-----------------------------------------------------------------------------
# Imports
#-----------------------------------------------------------------------------
import nose.tools as nt
from IPython.core.erro... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import os
import json
import pytest
from mock import ANY
from ansible.module_utils.network.fortios.fortios import FortiOSHandler
try:
from ansible.modules.network.fortios import fortios_system_fortiguard
except ImportError:
... |
#!/usr/bin/env python3
import forth
import unittest
from forth import cmp_all, is_none
from pmlr import pmlr
DEBUG = True
print = pmlr.util.writer
dbg_write = pmlr.util.debug_write
class TestUtil(unittest.TestCase):
def test_isnone(self):
"none-tester"
self.assertEqual(is_none(None), True... |
"""
Italian-language mappings for language-dependent features of Docutils.
"""
__docformat__ = 'reStructuredText'
labels = {
'author': 'Autore',
'authors': 'Autori',
'organization': 'Organizzazione',
'address': 'Indirizzo',
'contact': 'Contatti',
'version': 'Versione',
'revis... |
"""API to simulate quantization on a python graph."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.contrib.quantize.python import copy_graph
from tensorflow.contrib.quantize.python import fold_batch_norms
from tensorflow.contrib.quantize.... |
from __future__ import print_function
import argparse
import os
import subprocess
import sys
import zipfile
import plistlib
archs = ['arm64', 'armv7']
def get_scheme_version_and_buildid(archive):
info = plistlib.readPlist(os.path.join(os.path.normpath(archive), "Info.plist"))
return (info["SchemeName"], info... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
from ansible.errors import AnsibleError
from ansible.utils.vars import combine_vars
class Group:
''' a group of ansible hosts '''
# __slots__ = [ 'name', 'hosts', 'vars', 'child_groups', 'parent_groups', 'depth', '_hosts... |
import socket
import sys
from thrift.transport import TTransport, TSocket
from thrift.protocol import TBinaryProtocol, TProtocol
import InstanceService
import ttypes
socket = TSocket.TSocket("localhost", 9090)
transport = TTransport.TFramedTransport(socket)
transport.open()
protocol = TBinaryProtocol.TBinaryProtocol(... |
import inspect
import re
class Enum(object):
@classmethod
def all(cls):
return [getattr(cls, a) for a in dir(cls) if not a.startswith('_') and not inspect.ismethod(getattr(cls, a))]
def normalize_search_string(search_string):
return re.sub(u"[, \" \+ \- : > < = \\\\ \( \) ~]", u" ", search_strin... |
# Core capabilities
from .app import *
from .window import *
from .command import *
# Font support
from .font import Font
# Widgets
from .widgets.box import *
from .widgets.button import *
from .widgets.icon import *
from .widgets.image import *
from .widgets.imageview import *
from .widgets.label import *
from .widg... |
from abc import ABC, abstractmethod
from copy import copy
import openmc
from openmc.checkvalue import check_greater_than, check_value
class CompositeSurface(ABC):
"""Multiple primitive surfaces combined into a composite surface"""
def translate(self, vector, inplace=False):
surf = self if inplace el... |
# coding=utf-8
"""
InaSAFE Disaster risk assessment tool developed by AusAid -
**Exception Classes.**
Custom exception classes for the IS application.
Contact : <EMAIL>
.. note:: This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as publishe... |
from __future__ import (absolute_import, division, print_function)
from ansible.module_utils.six import string_types, integer_types
__metaclass__ = type
import datetime
try:
from pymongo import ASCENDING, DESCENDING
from pymongo.errors import ConnectionFailure
from pymongo import MongoClient
except Import... |
import os
import pkgutil
import socket
from leapp.snactor import commands
from leapp.snactor.commands import workflow
from leapp.snactor.commands import messages
from leapp.snactor.commands import repo
from leapp.utils.clicmd import command, command_opt
from leapp.utils.repository import find_repository_basedir
from l... |
import os
from os.path import join, dirname, abspath
import re
import subprocess
import sys
import tempfile
def Check(output, errors):
failed = any([s.startswith('/system/bin/sh:') or s.startswith('ANDROID')
for s in output.split('\n')])
return 1 if failed else 0
def Execute(cmdline):
(fd_out, o... |
# -*- coding: utf-8 -*-
"""Module providing JSON storage for static asset assignanvts"""
from plone.autoform.interfaces import IFormFieldProvider
from plone.dexterity.interfaces import IDexterityContent
from plone.supermodel import model
from zope.component import adapter
from zope.interface import implementer
from zop... |
'''
CAN (Controller Area Network) is a field bus protocol for distributed
real-time control.
This decoder assumes that a single CAN_RX line is sampled (e.g. on
the digital output side of a CAN transceiver IC such as the Microchip
MCP-2515DM-BM).
It also has support for CAN-FD.
'''
from .pd import Decoder |
#!/usr/bin/env python
#
# dateparser documentation build configuration file, created by
# sphinx-quickstart on Tue Jul 9 22:26:36 2013.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# file.
import sys
impor... |
from __future__ import unicode_literals
import sys
import warnings
from collections import deque
from functools import total_ordering
from django.db.migrations.state import ProjectState
from django.utils import six
from django.utils.datastructures import OrderedSet
from django.utils.encoding import python_2_unicode_c... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.