content
stringlengths
4
20k
from yowsup.layers.protocol_notifications.protocolentities import NotificationProtocolEntity from yowsup.structs import ProtocolTreeNode class EncryptNotification(NotificationProtocolEntity): """ <notification t="1419824928" id="2451228097" from="s.whatsapp.net" type="encrypt"> <count value="9"> ...
""" Check the numpy version is valid. Note that a development version is marked by the presence of 'dev0' or '+' in the version string, all else is treated as a release. The version string itself is set from the output of ``git describe`` which relies on tags. Examples -------- Valid Development: 1.22.0.dev0 1.22.0....
"""Ops related to candidate sampling.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.python.framework import dtypes from tensorflow.python.framework import ops from tensorflow.python.ops import array_ops from tensorflow.python.ops import...
""" The plugin module provides classes for implementation of suds plugins. """ from suds import * from logging import getLogger log = getLogger(__name__) class Context(object): """ Plugin context. """ pass class InitContext(Context): """ Init Context. @ivar wsdl: The wsdl. @type ws...
import simplejson from lxml import etree from ..exceptions import except_orm from ..models import ( MetaModel, BaseModel, Model, TransientModel, AbstractModel, MAGIC_COLUMNS, LOG_ACCESS_COLUMNS, ) # extra definitions for backward compatibility browse_record_list = BaseModel class browse_record(o...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations import sota.models class Migration(migrations.Migration): dependencies = [ ('sota', '0008_auto_20141010_1725'), ] operations = [ migrations.RemoveField( model_name='updat...
#!/usr/bin/env python3 from lib.posts import getPostTime, getText, post from lib.commands import vk, api, database from lib.config import group_id, test_id from lib.guilds import Eweek, Player from lib.errors import ErrorManager from re import search from logging import getLogger logger = getLogger("GM.make_eweek_pos...
from lib.hachoir_core.endian import BIG_ENDIAN, LITTLE_ENDIAN from lib.hachoir_core.error import info from lib.hachoir_core.log import Logger from lib.hachoir_core.bits import str2long from lib.hachoir_core.i18n import getTerminalCharset from lib.hachoir_core.tools import lowerBound from lib.hachoir_core.i18n import _ ...
""" Classes used to model the roles used in the courseware. Each role is responsible for checking membership, adding users, removing users, and listing members """ from abc import ABCMeta, abstractmethod from django.contrib.auth.models import User import logging from student.models import CourseAccessRole from xmodu...
from __future__ import (absolute_import, division, print_function) __metaclass__ = type import pytest from ansible import constants as C from ansible import context from ansible.cli.arguments import option_helpers as opt_help from ansible.errors import AnsibleError from ansible.playbook.play_context import PlayContex...
#! /usr/bin/env python # -*- coding: utf-8 -*- """Train the CTC model (SVC corpus).""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from os.path import join, isfile, abspath import sys import time import tensorflow as tf from setproctitle import setproc...
"""Testing for Spectral Biclustering methods""" import numpy as np import pytest from scipy.sparse import csr_matrix, issparse from sklearn.model_selection import ParameterGrid from sklearn.utils._testing import assert_almost_equal from sklearn.utils._testing import assert_array_equal from sklearn.utils._testing imp...
"""Custom SQLAlchemy types.""" from sqlalchemy.dialects import postgresql from sqlalchemy import types from nova import utils class IPAddress(types.TypeDecorator): """An SQLAlchemy type representing an IP-address.""" impl = types.String def load_dialect_impl(self, dialect): if dialect.name == ...
import importlib import logging import sys import unittest from os.path import sep, abspath from queue import Queue from tempfile import mkdtemp from threading import Thread import pytest from errbot.rendering import text from errbot.backends.base import Message, Room, Person, RoomOccupant, ONLINE from errbot.core_pl...
from HTMLParser import HTMLParser from cStringIO import StringIO import jsmin import os.path import sys class OrderedJSFilesExtractor(HTMLParser): def __init__(self, order_html_name): HTMLParser.__init__(self) self.ordered_js_files = [] order_html = open(order_html_name, 'r') sel...
import subprocess import time # Imports the monkeyrunner modules used by this program from com.android.monkeyrunner import MonkeyRunner, MonkeyDevice # Connects to the current device, returning a MonkeyDevice object print "Start Connction to Phone" device = MonkeyRunner.waitForConnection() print "Connect...
import os import sys import ssl import pprint import socket import urllib.parse # Rename HTTPServer to _HTTPServer so as to avoid confusion with HTTPSServer. from http.server import (HTTPServer as _HTTPServer, SimpleHTTPRequestHandler, BaseHTTPRequestHandler) from test import support threading = support.import_mod...
from msrest.pipeline import ClientRawResponse from .. import models class Polymorphism(object): """Polymorphism operations. :param client: Client for service requests. :param config: Configuration of service client. :param serializer: An object model serializer. :param deserializer: An objec mod...
from weboob.browser.elements import ListElement, ItemElement, method from weboob.browser.filters.html import Link, CSS, Attr from weboob.browser.filters.standard import CleanText, Duration, Regexp, Env from weboob.browser.pages import HTMLPage, pagination from weboob.capabilities.base import NotAvailable from weboob.ca...
# -*- coding: utf-8 -*- import sys from contextlib import contextmanager from fabric.api import cd, env, show, hide from .. import signal, configuration from ..utils import run def init(): configuration.setdefault('curl_url', '') configuration.setdefault('curl_output', '') configuration.setdefault('curl_...
from __future__ import print_function import cx_Oracle import SampleEnv connection = cx_Oracle.connect(SampleEnv.GetMainConnectString()) # show all of the rows available in the table cursor = connection.cursor() cursor.execute("select * from TestStrings order by IntCol") print("ALL ROWS") for row in cursor: prin...
import netCDF4 as cdf import numpy as np import os import re """ folder paths should end with a forward slash src: root path of product dst: destination of product bounds: bounds of the subset given as [latmin, latmax, longmin, longmax] """ def subSetFolder(src, dst, bounds): FILE_COORDS = "geo_coordin...
import abc import contextlib class FirewallDriver(object): """Firewall Driver base class. Defines methods that any driver providing security groups and provider firewall functionality should implement. Note port attribute should have information of security group ids and security group rules. ...
from django.db import router from .base import Operation class SeparateDatabaseAndState(Operation): """ Take two lists of operations - ones that will be used for the database, and ones that will be used for the state change. This allows operations that don't support state change to have it applied, o...
"""Figures for the publication "Entropic Equilibria Selection of Stationary Extrema in Finite Populations" """ from __future__ import print_function import math import os import pickle import sys import matplotlib from matplotlib import pyplot as plt import matplotlib.gridspec as gridspec import numpy as np import sc...
#!/usr/bin/env python # This is the GAP per Wolsey, pg 182, using Lagrangian Relaxation from gurobipy import GRB, Model model = Model('GAP per Wolsey with Lagrangian Relaxation') model.modelSense = GRB.MAXIMIZE model.setParam('OutputFlag', False) # turns off solver chatter b = [15, 15, 15] c = [ [ 6, 10, 1...
{ 'name': 'Singapore - Accounting', 'version': '1.0', 'author': 'Tech Receptives', 'website': 'http://www.techreceptives.com', 'category': 'Localization/Account Charts', 'description': """ Singapore accounting chart and localization. ======================================================= After...
"""Helpers shared by cloudstorage_stub and cloudstorage_api.""" __all__ = ['CS_XML_NS', 'CSFileStat', 'dt_str_to_posix', 'local_api_url', 'LOCAL_GCS_ENDPOINT', 'local_run', 'get_access_token', 'get_metadata', 'GCSFileStat', ...
def WebIDLTest(parser, harness): parser.parse(""" dictionary Dict2 : Dict1 { long child = 5; Dict1 aaandAnother; }; dictionary Dict1 { long parent; double otherParent; }; """) results = parser.finish() dict1 = results[1]; dict2 = results[0]; ...
""" The Touch Actions implementation """ from selenium.webdriver.remote.command import Command class TouchActions(object): """ Generate touch actions. Works like ActionChains; actions are stored in the TouchActions object and are fired with perform(). """ def __init__(self, driver): """ ...
"""Config flow for Netatmo.""" import logging import uuid import voluptuous as vol from homeassistant import config_entries from homeassistant.const import CONF_SHOW_ON_MAP from homeassistant.core import callback from homeassistant.helpers import config_entry_oauth2_flow, config_validation as cv from .const import (...
from .azure_sku import AzureSku from msrest.serialization import Model class UpdateWorkspaceCollectionRequest(Model): """UpdateWorkspaceCollectionRequest. Variables are only populated by the server, and will be ignored when sending a request. :param tags: :type tags: dict :ivar sku: :var...
ANSIBLE_METADATA = {'metadata_version': '1.0', 'status': ['preview'], 'supported_by': 'community'} ROCKETCHAT_INCOMING_WEBHOOK = '%s://%s/hooks/%s' def build_payload_for_rocketchat(module, text, channel, username, icon_url, icon_emoji, link_names, color, attachments): payl...
""" Wrapper for loading templates from "templates" directories in INSTALLED_APPS packages. """ import os import sys from django.conf import settings from django.core.exceptions import ImproperlyConfigured from django.template import TemplateDoesNotExist from django.template.loader import BaseLoader from django.utils....
from __future__ import (absolute_import, division, print_function) __metaclass__ = type HAVE_FUNC = False try: import func.overlord.client as fc HAVE_FUNC = True except ImportError: pass import os import tempfile import shutil from ansible.errors import AnsibleError try: from __main__ import display...
from __future__ import absolute_import, division, print_function __metaclass__ = type import pytest from ansible.module_utils._text import to_native from ansible.module_utils.common.validation import check_required_arguments @pytest.fixture def arguments_terms(): return { 'foo': { 'required'...
import pytz from datetime import datetime from mock import Mock from nose.tools import eq_ from django.test.client import RequestFactory from django.test.utils import override_settings from rest_framework import fields from kitsune.sumo import api from kitsune.sumo.tests import TestCase @override_settings(WIKI_DEF...
""" Test class for baremetal IPMI power manager. """ import os import stat import tempfile from nova.openstack.common import cfg from nova import test from nova.tests.baremetal.db import utils as bm_db_utils from nova import utils from nova.virt.baremetal import baremetal_states from nova.virt.baremetal import ipmi f...
from taboot.tasks import BaseTask, FuncTask, TaskResult JK_ENABLE = 0 JK_DISABLE = 1 JK_STOP = 2 class ToggleHost(FuncTask): def __init__(self, action, proxyhost, **kwargs): super(ToggleHost, self).__init__(proxyhost, **kwargs) self._action = action if action == JK_ENABLE: sel...
import itertools import math import pytest import bayeslite from bayeslite.guess import bayesdb_guess_population from bayeslite.guess import bayesdb_guess_stattypes from bayeslite.exception import BQLError def test_guess_stattypes(): n = ['a', 'b'] a_z = range(ord('a'), ord('z') + 1) rows = [[chr(c), c %...
import pooler import os from export_tools import * from osv import osv, fields class wiz_sneldev_products_import(osv.osv_memory): _name = 'sneldev.products.import' _description = 'Import orders' _columns = { } _defaults = { } def do_products_import(self, cr, uid, ids, context=None): ...
# -*- coding: utf-8 -*- from south.utils import datetime_utils as datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding field 'Receita.nota' db.add_column('financeiro_receita', 'nota',...
#!/usr/bin/python from __future__ import (absolute_import, division, print_function) # Copyright 2019 Fortinet, Inc. # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the Lic...
import argparse from neutronclient.common import exceptions from neutronclient.common import utils from neutronclient.i18n import _ from neutronclient.neutron import v2_0 as neutronV20 from neutronclient.neutron.v2_0.qos import policy as qos_policy def _format_subnets(network): try: return '\n'.join([' '...
import sys from os import path import numpy as np from numpy.testing import * from numpy.compat import asbytes, asunicode import warnings class TestFromrecords(TestCase): def test_fromrecords(self): r = np.rec.fromrecords([[456, 'dbe', 1.2], [2, 'de', 1.3]], names='col1,col2,c...
import logging import os import sys import threading import traceback from . import config from gi.repository import Gdk from gi.repository import GLib from gi.repository import GObject from gi.repository import Gtk class vmmGObject(GObject.GObject): _leak_check = True @staticmethod def idle_add(func, ...
import gdb from linux import utils from linux import constants radix_tree_root_type = utils.CachedType("struct radix_tree_root") radix_tree_node_type = utils.CachedType("struct radix_tree_node") def is_indirect_ptr(node): long_type = utils.get_long_type() return (node.cast(long_type) & constants.LX_RADIX_TR...
import json from django.contrib.messages.storage.base import BaseStorage from django.contrib.messages.storage.cookie import ( MessageDecoder, MessageEncoder, ) from django.utils import six class SessionStorage(BaseStorage): """ Stores messages in the session (that is, django.contrib.sessions). """ ...
"""Contrib data iterators for common data formats.""" from ..io import DataIter, DataDesc from .. import ndarray as nd class DataLoaderIter(DataIter): """Returns an iterator for ``mx.gluon.data.Dataloader`` so gluon dataloader can be used in symbolic module. Parameters ---------- loader : mxnet.g...
import base64 import logging import urlparse from common.chrome_proxy_measurements import ChromeProxyValidation from integration_tests import chrome_proxy_metrics as metrics from metrics import loading from telemetry.core import exceptions from telemetry.page import page_test class ChromeProxyDataSaving(page_test.Pa...
import os import fnmatch import sys from Tkinter import * import SearchEngine from SearchDialogBase import SearchDialogBase def grep(text, io=None, flist=None): root = text._root() engine = SearchEngine.get(root) if not hasattr(engine, "_grepdialog"): engine._grepdialog = GrepDialog(root, engine, f...
from __future__ import absolute_import import logging from collections import namedtuple import random from apparent_temperature.measure_generator import MeasureGeneratorSpout log = logging.getLogger('temperature_generator') TemperatureMeasure = namedtuple( "TemperatureMeasure", "id_sensor timestamp temper...
"""Common Policy Engine Implementation""" import logging import urllib import urllib2 from nova.openstack.common.gettextutils import _ from nova.openstack.common import jsonutils LOG = logging.getLogger(__name__) _BRAIN = None def set_brain(brain): """Set the brain used by enforce(). Defaults use Brain...
# -*- coding: utf-8 -*- """helper for the test""" import os __file__ = os.path.abspath(__file__) def TemplatePath() -> str: """ generating the template path for the tests Returns: str: the template path """ return os.path.join( os.path.dirname(os.path.dirname(os.path.dirname(__file__))), 'l...
"""Global context for install engine. Currently, this is just a bunch of global variables initialized via install_engine.py. Eventually, should refactor into a context object which is passed to each resource manager. """ import os.path import sys import getpass import engage.utils.pw_repository as pwr password_repo...
from __future__ import (absolute_import, division, print_function) __metaclass__ = type from ansible.module_utils.common._collections_compat import Mapping from ansible.template import Templar, AnsibleUndefined STATIC_VARS = [ 'ansible_version', 'ansible_play_hosts', 'ansible_dependent_role_names', 'a...
# -*- coding: utf-8 -*- """ Created on Thu Oct 5 17:03:55 2017 @author: a002087 """ import difflib import random import requests import ipywidgets as widgets import core def MultiCheckboxWidget(descriptions): """ Widget with a search field and lots of checkboxes """ search_widget = widgets.Text() opti...
""" Tests for the :py:class:`luma.lcd.device.hd44780` device. """ from luma.lcd.device import hd44780 from luma.core.render import canvas from luma.core.util import bytes_to_nibbles from luma.core.framebuffer import full_frame, diff_to_previous from luma.lcd.const import hd44780 as CONST from PIL import Image, ImageD...
from lib import l10n_utils import jingo from django.core.mail import EmailMessage from django.shortcuts import redirect from django.views.decorators.csrf import csrf_protect from funfactory.urlresolvers import reverse from forms import FraudReportForm FRAUD_REPORT_EMAIL_FROM = 'Mozilla.com <<EMAIL>>' FRAUD_REPORT_...
# -*- coding: utf-8 -*- import mock import pytest import urlparse from addons.base.tests import views from addons.base.tests.utils import MockFolder from addons.mendeley.models import Mendeley from addons.mendeley.tests.utils import MendeleyTestCase, mock_responses from tests.base import OsfTestCase from addons.mende...
#! /usr/bin/env python import os,sys,math,urllib2,urllib import optparse ########################################################################### class OptionParser (optparse.OptionParser): def check_required (self, opt): option = self.get_option(opt) # Assumes the option's 'default' is set to N...
# stdlib from mock import Mock # project from checks import AgentCheck from tests.checks.common import AgentCheckTest WinHttpAutoProxySvc_attr = { # Running Windows Service 'AcceptPause': False, 'AcceptStop': True, 'Caption': "WinHTTP Web Proxy Auto-Discovery Service", 'CheckPo...
import datetime import pytz from django.core.urlresolvers import reverse from mock import patch from nose.plugins.attrib import attr from courseware.access import has_access from courseware.tests.helpers import CourseAccessTestMixin, LoginEnrollmentTestCase from courseware.tests.factories import ( BetaTesterFacto...
from __future__ import unicode_literals from django import forms from django.contrib.auth import ( authenticate, get_user_model, password_validation, ) from django.contrib.auth.hashers import ( UNUSABLE_PASSWORD_PREFIX, identify_hasher, ) from django.contrib.auth.models import User from django.contrib.auth.tok...
''' Various code generation for Java. See README.md for details. @author: xixixao <<EMAIL>> @license: MIT (http://www.opensource.org/licenses/mit-license.php) @since: 2014-05-03 ''' import sublime import sublime_plugin import re from collections import namedtuple # Note: klass == class # Custom data structures Kla...
import itertools from _init_environment import SetHostMTurkConnection from _init_environment import config_environment def description_filter(substring): return lambda hit: substring in hit.Title def disable_hit(hit): return conn.disable_hit(hit.HITId) def dispose_hit(hit): # assignments must be first approved o...
import unittest import troposphere.rds as rds class TestRDS(unittest.TestCase): def test_it_allows_an_rds_instance_created_from_a_snapshot(self): rds_instance = rds.DBInstance( 'SomeTitle', AllocatedStorage=1, DBInstanceClass='db.m1.small', Engine='MySQL', ...
""" Tracking for bluetooth low energy devices. For more details about this platform, please refer to the documentation at https://home-assistant.io/components/device_tracker.bluetooth_le_tracker/ """ import logging from homeassistant.helpers.event import track_point_in_utc_time from homeassistant.components.device_tr...
from builtins import next from collections import Counter from pimlico.core.modules.map.multiproc import multiprocessing_executor_factory def process_document(worker, archive, filename, doc): term_keys = worker.info.options["term_keys"] output_data_points = [] for data_point in doc: # Look for ...
''' These are a common functions and classes for creating custom post processors. ''' from PySide import QtCore, QtGui import FreeCAD FreeCADGui = None if FreeCAD.GuiUp: import FreeCADGui class OldHighlighter(QtGui.QSyntaxHighlighter): def highlightBlock(self, text): myClassFormat = QtGui.QTextChar...
"""Tests for tpu_function helpers.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.contrib.tpu.python.tpu import tpu_feed from tensorflow.contrib.tpu.python.tpu import tpu_function from tensorflow.python.platform import test class Func...
from django import forms from django.utils.translation import ugettext, ugettext_lazy as _ from django.contrib.auth import authenticate from captcha.fields import CaptchaField from mezzanine.core.forms import Html5Mixin from mezzanine.accounts import forms as base from .models import InvitationCode, InviteCodeHasExp...
from ctypes import c_char_p, c_float, c_int, string_at, Structure, POINTER from django.contrib.gis.geoip.libgeoip import lgeoip, free #### GeoIP C Structure definitions #### class GeoIPRecord(Structure): _fields_ = [('country_code', c_char_p), ('country_code3', c_char_p), ('country...
''' A 'smoke test' for the dynamic package. Uses a fake data set to run the baseline ''' import cPickle as pickle import os import numpy as np import time import dynamic dynamic.parameters.DATASET = 'SMALL' import dynamic.SS import dynamic.TPI from dynamic import parameters, wealth, labor, demographics, income, SS, ...
#!/usr/bin/python # script find clusters of small RNA reads in the genome # version 3 - 24-12-2013 evolution to multiprocessing # Usage clustering.py <bowtie input> <output> <bowtie index> <clustering_distance> <minimum read number per cluster to be outputed> <collapse option> <extention value> <average_cluster_size> #...
from __future__ import unicode_literals from datetime import datetime from django.test import TestCase from django.utils import six from .models import Article, Reporter, Writer class M2MIntermediaryTests(TestCase): def test_intermeiary(self): r1 = Reporter.objects.create(first_name="John", last_name="...
import unittest class AuthTicketTests(unittest.TestCase): def _getTargetClass(self): from .._auth_tkt import AuthTicket return AuthTicket def _makeOne(self, *args, **kw): return self._getTargetClass()(*args, **kw) def test_ctor_defaults(self): import hashlib from...
from Screens.Screen import Screen from Components.ConfigList import ConfigListScreen from Components.Sources.StaticText import StaticText from Components.config import config, ConfigSubsection, ConfigBoolean, getConfigListEntry, ConfigSelection, ConfigYesNo, ConfigIP from Components.Network import iNetwork from Compone...
""" WAF Tool to select the correct toolchain based on the target archtecture. This tool loads compiler_c and compiler_cxx, so you don't need to load them (and you must not load them before this tool). Use the environment variable TOOLCHAIN to define the toolchain. Example:: def configure(cfg): cfg.env.TO...
"""Admin classes for the aps_production app.""" from django.contrib import admin from . import models # Inlines ==================================================================== class OrderLineInlineAdmin(admin.TabularInline): model = models.OrderLine class OrderRunInlineAdmin(admin.TabularInline): mod...
import datetime from urllib.parse import quote import warnings from django_jinja import library import jinja2 from django.forms.widgets import RadioSelect @library.global_function def describe_friendly_type(type_): if type_ is str: return "String" if type_ is int: return "Integer" if typ...
# Import XML Courses from git repos into the CMS. # Run with sudo and make sure the user can clone # the course repos. # Output Has per course #{ # repo_url: # repo_name: # org: # course: # run: # disposition: #} import argparse from os.path import basename import yaml if __name__ == '__main__': ...
from lib.common import helpers class Module: def __init__(self, mainMenu, params=[]): self.info = { 'Name': 'Invoke-Mimikatz Golden Ticket', 'Author': ['@JosephBialek', '@gentilkiwi'], 'Description': ("Runs PowerSploit's Invoke-Mimikatz function " ...
from __future__ import unicode_literals import sure # noqa from nose.tools import assert_raises import requests from moto import mock_ec2, settings if settings.TEST_SERVER_MODE: BASE_URL = 'http://localhost:5000' else: BASE_URL = 'http://169.254.169.254' @mock_ec2 def test_latest_meta_data(): res = req...
# -*- coding: utf-8 -*- """ Tests for opaque key transition in the LMS runtime. See https://github.com/edx/edx-platform/wiki/Opaque-Keys """ import mock from .base import XBlockHandlerTestCase, scenario class TestOpaqueKeys(XBlockHandlerTestCase): """ Test that the XBlock handles the opaque key transition gra...
"""Construct a dex manifest from a set of input .dex.zip files. Usage: %s <output manifest> <input zip file>* %s @<params file> Input files must be either .zip files containing one or more .dex files or .dex files. A manifest file is written that contains one line for each input dex in the following form: <i...
"""This is like pexpect, but will work on any file descriptor that you pass it. So you are reponsible for opening and close the file descriptor. $Id$ """ from pexpect import * import os __all__ = ['fdspawn'] class fdspawn (spawn): """This is like pexpect.spawn but allows you to supply your own open file de...
# -*- coding: utf-8 -*- """Bot tests for input_choice options.""" # # (C) Pywikibot team, 2015-2018 # # Distributed under the terms of the MIT license. # from __future__ import absolute_import, division, unicode_literals from pywikibot import bot, bot_choice from tests.aspects import unittest, TestCase message = bot...
"""Script to download sdk/extras packages on the bots from google storage. The script expects arguments that specify zips file in the google storage bucket named: <dir in SDK extras>_<package name>_<version>.zip. The file will be extracted in the android_tools/sdk/extras directory on the test bots. This script will no...
from __future__ import (absolute_import, division, print_function) __metaclass__ = type from ansible.plugins.action import ActionBase import re class ActionModule(ActionBase): TRANSFERS_FILES = False def run(self, tmp=None, task_vars=dict()): if self._play_context.check_mode: # in --che...
import json import sys def get_name(node): name = node.get_name() if name.startswith('"') and name.endswith('"'): name = name[1:-1] return name def positionGraph(g): import pydot graph = pydot.Dot() for node in g['nodes']: graph.add_node(pydot.Node(node)) for edge, (source, destination, data) i...
from core.himesis import Himesis, HimesisPreConditionPatternLHS import cPickle as pickle from uuid import UUID class HMoveOneTraceLinkDiffRulesLHS(HimesisPreConditionPatternLHS): def __init__(self): """ Creates the himesis graph representing the AToM3 model HMoveOneTraceLinkDiffRulesLHS. ""...
#!/usr/bin/env python from flask import Flask, request, abort import json import os import serial s = None #f = os.popen('ifconfig br-lan | grep "inet\ addr" | cut -d: -f2 | cut -d" " -f1') # AP model f = os.popen('ifconfig apcli0 | grep "inet\ addr" | cut -d: -f2 | cut -d" " -f1') # Station model inet_addr = f.rea...
import functools import jsonschema from sahara import exceptions as ex from sahara.i18n import _ from sahara.utils import api as u from sahara.utils import api_validator def validate(schema, *validators): def decorator(func): @functools.wraps(func) def handler(*args, **kwargs): reque...
"""Internationalization and localization support. This module provides internationalization (I18N) and localization (L10N) support for your Python programs by providing an interface to the GNU gettext message catalog library. I18N refers to the operation by which a program is made aware of multiple languages. L10N r...
from neutron.common import exceptions as qexc class OFCException(qexc.NeutronException): message = _("An OFC exception has occurred: %(reason)s") def __init__(self, **kwargs): super(OFCException, self).__init__(**kwargs) self.status = kwargs.get('status') self.err_msg = kwargs.get('er...
from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} import os import traceback try: from pymongo.errors import ConnectionFailure from ...
from mythbox.mythtv.enums import TVState, TVState44, TVState58 # MythTV Protcol Constants initVersion = 8 initToken = '' separator = u'[]:[]' serverVersion = None class ProtocolException(Exception): ''' Thrown on protcol version mismatch between frontend and backend or general protocol related errors. ...
""" *********** Evaluations *********** An evaluation_ object represents a collection of Synapse Entities that will be processed in a particular way. This could mean scoring Entries in a challenge or executing a processing pipeline. Imports:: from synapseclient import Evaluation, Submission, SubmissionStatus E...
import copy, random, string __all__ = [ 'TestDataContext', 'TestModel', 'TestDataItem', 'scope', 'ForeignKey', 'ManyToManyKey', ] class TestDataContext(object): MARKED = 'marked' def __init__(self): self.subcontexts = [{}] def tdi_id(self, tdi): """ Get a unique i...