content
string
""" Package to test the openlp.core.lib package. """ import os from unittest import TestCase from tests.functional import MagicMock, patch from tests.utils import assert_length, convert_file_service_item from openlp.core.common import Registry, md5_hash from openlp.core.lib import ItemCapabilities, ServiceItem, Servi...
# -*- coding: iso-8859-1 -*- """ MoinMoin - "text/plain" Formatter @copyright: 2000-2002 Juergen Hermann <<EMAIL>> 2007 by Timo Sirainen <<EMAIL>> @license: GNU GPL, see COPYING for details. """ from MoinMoin.formatter import FormatterBase class Formatter(FormatterBase): """ ...
import io import numpy as np import image_server from pprint import pprint from multiprocessing import Process, Queue, Condition import multiprocessing import threading from sharemem import SharedMemory from detector import Detector import itertools import math import time class Processor(io.BytesIO): def __init_...
"""SAC example for Mujoco. Warning!!! This code uses DeepMind wrappers which differ from OpenAI gym wrappers and the results may not be comparable. """ from absl import app from absl import flags from seed_rl.agents.sac import learner from seed_rl.agents.sac import networks from seed_rl.common import actor from see...
#!/usr/bin/env python import glob import os import runpy ore_helpers = runpy.run_path(os.path.join(os.path.dirname(os.getcwd()), "ore_examples_helper.py")) OreExample = ore_helpers['OreExample'] import sys oreex = OreExample(sys.argv[1] if len(sys.argv)>1 else False) # Case B oreex.print_headline("Run ORE (case B (...
# Initialization. Create your opts here. Runs before command line processing. def init(): # standart autoconf options opt_group_new('autoconf', 'Standart autoconf options') opt_new("build", group = 'autoconf', help = "configure for building on BUILD") opt_new("host", group = 'autoconf', ...
from wordbridge.html import HtmlBuilder html = HtmlBuilder() def no_op(self): return lambda html_stack: None def clear_stack(html_stack): while html_stack.current_element() is not None: html_stack.close_element() def open_element(tag_name): def apply(html_stack): html_stack.o...
import os import unittest import socket from collections import namedtuple from conpot.protocols.IEC104 import IEC104_server, frames import conpot.core as conpot_core import gevent.monkey from gevent.server import StreamServer gevent.monkey.patch_all() class TestBase(unittest.TestCase): def setUp(self): ...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('donations', '0004_goal_source_type'), ] operations = [ migrations.AddField( model_name='toplist', na...
from invenio.sequtils import SequenceGenerator from invenio.legacy.bibedit.utils import get_bibrecord from invenio.legacy.bibrecord import record_get_field_value, create_record # Imports related to the texkey generation daemon from invenio.legacy.search_engine import perform_request_search, get_record from invenio.leg...
from sklearn.cross_validation import train_test_split from sklearn.grid_search import GridSearchCV from sklearn.metrics import explained_variance_score, mean_absolute_error, mean_squared_error, r2_score from sklearn.linear_model import SGDRegressor, Ridge from sklearn.cross_validation import KFold from scipy.sparse imp...
"""Password related user model behaviour.""" import pytest import transaction from pyramid_fullauth.models import User from pyramid_fullauth.exceptions import EmptyError def test_hash_checkout(db_session, user): """User.check_password correct one.""" user = db_session.merge(user) assert user.check_passwo...
# coding: utf8 import os import time import tempfile from tempdir import TempDir import pytest from simplekv._compat import BytesIO, xrange, text_type from simplekv.decorator import PrefixDecorator from simplekv.crypt import HMACDecorator from simplekv.idgen import UUIDDecorator, HashDecorator from simplekv import Co...
import copy import ctypes import email import logging import os import platform import shutil import smtplib import subprocess import sys import types import pyauto_functional import pyauto import pyauto_utils """Commonly used functions for PyAuto tests.""" def CopyFileFromDataDirToDownloadDir(test, file_path): "...
from collections import OrderedDict import numpy as np import theano from dagbldr.datasets import fetch_binarized_mnist, minibatch_iterator from dagbldr.optimizers import adam from dagbldr.utils import add_datasets_to_graph, get_params_and_grads from dagbldr.utils import TrainingLoop from dagbldr.utils import create_o...
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import nose from nose.tools import assert_equal, assert_true, assert_false, raises from pypirc3.executor.creator import Creator class TestCreator(object): def setup(self): self.path = os.path.join(os.path.dirname(__file__), '.pypirc') se...
from contextlib import contextmanager from datetime import datetime from os import environ from titlecase import titlecase import html2text import logging import re from django.core.exceptions import ImproperlyConfigured from django import db logger = logging.getLogger(__name__) def nhs_abbreviations(word, **kwarg...
#!/usr/bin/python # -*- coding: utf-8 -*- # # Twitch Stream Title Generator # Writen by Jan Rokita # https://rokita.me # import requests, random token = "YOUR_ACCESS_TOKEN" channel_name = "YOUR_TWITCH_USERNAME" list1 = ["Watery", "Frozen", "Burning", "Firery", "Floating", "Dark", "Shadowed"] list2 = ["Tower", "Dunge...
""" Draw a sequence diagram of all transmitted messages, requires rx.msg.valid tracepoint """ import json from pathlib import Path from seqdiag import builder, drawer, parser as seq_parser from dmprsim.analyze._utils.extract_messages import all_tracefiles, \ extract_messages from dmprsim.scenarios.disappearing_no...
# -*- coding: utf-8 -*- from django.db import models from south.db import db from south.utils import datetime_utils as datetime from south.v2 import SchemaMigration class Migration(SchemaMigration): def forwards(self, orm): # Adding model 'Album' db.create_table(u'vkontakte_video_album', ( ...
from tigergrader.initdb import create_user import unittest from testhelper import TestHelper class LoginTestCases(TestHelper): def test_invalid_login(self): rv = self.login('nobody', 'sesame') assert "Invalid Credentials" in rv.data def test_no_login(self): rv = self.app.get('/report/...
# For the makeReport example from treedict import TreeDict t = TreeDict("mytree") t.x = 1 t.y = 2 t.a.z = [1,2,3] t.a.y = {1 : 2} t.b.x = "hello" t.a.x = None t.b.z = 2 print t.makeReport() print t.a.makeReport() print t.a.makeReport(add_path = True) print t.a.makeReport(add_path = True, add_tree_name = False) # Fo...
# -*- coding: utf-8 -*- from zerver.lib.test_classes import WebhookTestCase class OpsGenieHookTests(WebhookTestCase): STREAM_NAME = 'opsgenie' URL_TEMPLATE = "/api/v1/external/opsgenie?&api_key={api_key}&stream={stream}" FIXTURE_DIR_NAME = 'opsgenie' def test_acknowledge_alert(self) -> None: ...
from __future__ import unicode_literals from netmiko.base_connection import BaseSSHConnection import time import re class F5LtmSSH(BaseSSHConnection): def session_preparation(self): ''' Prepare the session after the connection has been established ''' self.disable_paging(command...
#!/usr/bin/env python """docker-compose.yml generator. It takes existing docker-compose.yml, replaces "build:" instructions with the "image:" instructions, preserves current binds - will read them from the running containers Usage: generate-compose.py [ --debug ] --file=file --jmaster-image=jm_image --jmas...
print("Writing interrupt stubs") int_handler.write(".macro intr_stub nr\n.global intr_stub_\\nr\n.align 16\nintr_stub_\\nr:\n pushl $0\n pushl $\\nr\n jmp intr_common_handler\n.endm\n.macro intr_stub_error_code nr\n.global intr_stub_\\nr\n.align 16\nintr_stub_\\nr:\n pushl $\\nr\n jmp intr_common_handler...
__author__ = 'jeff' from toolbox.plugin import ToolboxPlugin from toolbox.mixins import RegistryMixin from toolbox.scanner import find_modules from terminaltables import AsciiTable class ListPlugin(RegistryMixin, ToolboxPlugin): name = 'list' description = 'List all plugins' def prepare_parser(self, par...
"""Tests for release-granularity metric.""" import datetime import random import uuid from database import models from metrics import release_granularity from test import metric_test_case class TestReleaseGranularityMetric(metric_test_case.MetricTestCase): def new_metric_under_test(self): return release_gran...
import os import collections import time import logging import subprocess import xml.etree.ElementTree as ET import platform import sys import bz2 from threading import Lock if sys.version_info < (3,): from StringIO import StringIO else: from io import StringIO class Scan(object): # Fix race-condition i...
#!/usr/bin/env python3 """Example for aiohttp.web basic server with table definition for routes """ import textwrap from aiohttp import web async def intro(request): txt = textwrap.dedent("""\ Type {url}/hello/John {url}/simple or {url}/change_body in browser url bar """).format(url='127.0....
#!/usr/bin/env python """ sshdefaultscan Scan networks for SSH servers with default username and password. """ import argparse import logging import socket from time import time import nmap import paramiko SSH_DEFAULT_USERNAME = 'root' SSH_DEFAULT_PASSWORD = 'root' BATCH_TEMPLATE_DEFAULT = '{host}' def out(hostnam...
from __future__ import (absolute_import, division, print_function) __metaclass__ = type from ansible.playbook.task import Task from .. compat import unittest basic_shell_task = dict( name = 'Test Task', shell = 'echo hi' ) kv_shell_task = dict( action = 'shell echo hi' ) class TestTask(unittest.TestCase):...
# coding=utf-8 """Output test. .. note:: 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 2 of the License, or (at your option) any later version. """ __author__ = '<EM...
#!/usr/bin/python # -*- coding: utf-8 -*- """ Notifications by email. """ from django.core import mail from django.utils.translation import ugettext_lazy as _ from django.template.loader import get_template from django.template import Context from django.contrib.sites.models import Site from django.utils.encoding i...
from alignak.objects.satellitelink import SatelliteLink, SatelliteLinks from alignak.property import BoolProp, IntegerProp, StringProp, ListProp class ReactionnerLink(SatelliteLink): """Please Add a Docstring to describe the class here""" id = 0 my_type = 'reactionner' properties = SatelliteLink.prop...
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import print_function import os.path import warnings import sys try: from setuptools import setup setuptools_available = True except ImportError: from distutils.core import setup setuptools_available = False try: # This will create an...
from calendar import HTMLCalendar from .models import Event class Calendar(HTMLCalendar): def __init__(self, year=None, month=None): self.year = year self.month = month super(Calendar, self).__init__() # formats a day as a td # filter events by day def formatday(self, day, even...
# -*- coding: utf-8 -*- import os import csv import xml.etree.cElementTree as et from collections import defaultdict import numpy as np import zipfile import tempfile import pathomx.ui as ui import pathomx.db as db import pathomx.utils as utils from pathomx.data import DataDefinition from pathomx.plugins import Exp...
from .decimalize import decimalize def sum(data): """ This function returns the sum of numerical values in a data set. To reduce floating-point errors, I am using an implementation of the `Kahan summation algorithm`_. .. _`Kahan summation algorithm`: https://en.wikipedia.org/wiki/Kahan_summation_algo...
#!/usr/bin/env python """Downloads and decompresses required census files for pizza.""" import os import os.path import subprocess as sp def download(url, f): sp.check_call('curl -o %s %s' % (f, url), shell=True) if not os.path.exists('census'): os.mkdir('census') os.chdir('census') if not os.path.exists('addrfea...
import pickle from nose.tools import eq_ from .. import language, portuguese from ...datasources import diff, parent_revision, revision from ...dependencies import solve BAD = [ "babaca", "bixa", "boiola", "boiolas", "boquete", "bosta", "buceta", "bucetas", "bucetinha", "bunda", "bundinha...
# vi:ts=4:sw=4:syn=python PROGRAM_NAME = "koemyd" PROGRAM_DESC = "a Minimalistic HTTP/1.1 Link Procurator" VERSION_MAJOR = 1 VERSION_MINOR = 0 VERSION = "%d.%d" % (VERSION_MAJOR, VERSION_MINOR) SETTINGS_PROGRAM_CONFIG_FILE = "koemyd.conf" SETTINGS_DEFAULT_LISTEN_ADDR = "0.0.0.0" SETTINGS_DEFAULT_LISTEN_PORT = "11...
import logging from miasm2.jitter.jitload import jitter, named_arguments from miasm2.core import asmblock from miasm2.core.utils import pck32, upck32 from miasm2.arch.arm.sem import ir_armb, ir_arml log = logging.getLogger('jit_arm') hnd = logging.StreamHandler() hnd.setFormatter(logging.Formatter("[%(levelname)s]: %...
#!/usr/bin/python #=================================================================================================# # ____ __________ __ ____ __ # # /_ | ____ |__\_____ \ _____/ |_ /_ |/ |_ # #...
import unittest from cupy.core import internal from cupy import testing class TestProd(unittest.TestCase): def test_empty(self): self.assertEqual(internal.prod([]), 1) def test_one(self): self.assertEqual(internal.prod([2]), 2) def test_two(self): self.assertEqual(internal.prod...
__author__ = 'Irina.Chegodaeva' class SessionHelper: def __init__(self, app): self.app = app def login(self, username, password): wd = self.app.wd self.app.open_home_page() self.app.libs.change_field_value("user", username) self.app.libs.change_field_value...
from lxml import etree from django.conf import settings from django.contrib.auth.models import AnonymousUser from django.contrib.sessions.middleware import SessionMiddleware from django.urls import reverse from django.test import RequestFactory from django.test.utils import override_settings from django.utils.timezone...
import pytest from utils.conf import cfme_data, credentials from cfme.configure import configuration from utils.appliance import current_appliance from utils.ext_auth import disable_external_auth_ipa, disable_external_auth_openldap, \ setup_external_auth_ipa, setup_external_auth_openldap @pytest.fixture(scope='s...
"""Spectral Embedding""" # Wei LI <<EMAIL>> # License: BSD 3 clause import warnings import numpy as np from scipy import sparse from scipy.linalg import eigh from scipy.sparse.linalg import lobpcg from ..base import BaseEstimator from ..externals import six from ..utils import check_random_state from ..util...
import os from django.utils.translation import ugettext_lazy as _ from openstack_dashboard import exceptions DEBUG = {{ debug }} TEMPLATE_DEBUG = DEBUG # Required for Django 1.5. # If horizon is running in production (DEBUG is False), set this # with the list of host/domain names that the application can serve. # F...
import paddle import paddle.fluid as fluid import numpy as np import math import sys from functools import partial PASS_NUM = 100 EMBED_SIZE = 32 HIDDEN_SIZE = 256 N = 5 BATCH_SIZE = 32 word_dict = paddle.dataset.imikolov.build_dict() dict_size = len(word_dict) def inference_program(is_sparse): first_word = flu...
from odoo import models, fields, api, _ from odoo.exceptions import Warning class OrderCheckPricesWizardBrands(models.TransientModel): _name = 'invoice.update.payment.data.invoices' wizard_id = fields.Many2one('invoice.update.payment.data') invoice_id = fields.Many2one('account.invoice', "Invoice") cl...
from ehb_client.requests.base import JsonRequestBase, IdentityBase, RequestBase import json from ehb_client.requests.exceptions import InvalidArguments, PageNotFound class Organization(IdentityBase): def __init__(self, name, subject_id_label, modified=None, created=None, id=-1): self.name = name ...
from django.http import HttpResponse from django.views.generic import TemplateView, View from django import template from core.models import * import json import os import time import tempfile class MCordView(TemplateView): head_template = r"""{% extends "admin/dashboard/dashboard_base.html" %} {% load adm...
import logging import sys from werkzeug.contrib.wrappers import DynamicCharsetRequestMixin from werkzeug.wrappers import Request as BaseRequest, Response from werkzeug.exceptions import HTTPException from lymph.core.interfaces import Interface from lymph.core import trace from lymph.utils.logging import setup_logger ...
"""Test the Litter-Robot switch entity.""" from datetime import timedelta import pytest from homeassistant.components.litterrobot.entity import REFRESH_WAIT_TIME_SECONDS from homeassistant.components.switch import ( DOMAIN as PLATFORM_DOMAIN, SERVICE_TURN_OFF, SERVICE_TURN_ON, ) from homeassistant.const i...
import inspect import itertools import os import posixpath import re from tempfile import NamedTemporaryFile from zipfile import ZipFile from flask import g, request, session from flask.helpers import get_root_path from werkzeug.utils import secure_filename from indico.core.config import config from indico.core.plugi...
"""Interact with `eXist-db`_ XML databases. This package provides classes to ease interaction with eXist XML databases. It contains the following modules: * :mod:`eulexistdb.db` -- Connect to the database and query * :mod:`eulexistdb.query` -- Query :class:`~eulxml.xmlmap.XmlObject` models from eXist with semant...
# -*- coding: utf-8 -*- # Scrapy settings for scraper project # # For simplicity, this file contains only settings considered important or # commonly used. You can find more settings consulting the documentation: # # http://doc.scrapy.org/en/latest/topics/settings.html # http://scrapy.readthedocs.org/en/latest...
#!/usr/bin/env python """Simple library for parsing deeply nested structure (dict, json) into regular object. You can specify fields to extract, and argument names in created object. Example content = { 'name': 'Bob', 'details': { 'email': '<EMAIL>', } } fields = ( ...
import os import unittest from saml2.ident import IdentDB from pefimproxy.util.targetid import TargetIdHandler class TargetIdTestCase(unittest.TestCase): def setup_class(self): self.id = IdentDB({}) self.sp_entity_id = "https://localhost:/sp.xml" sp_id = "urn:mace:umu.se:sp" self....
# -*- coding: utf-8 -*- # ============================================================================= # Tasks to be callable async # ============================================================================= tasks = {} # ----------------------------------------------------------------------------- def maintenan...
''' Script to check the correctness of the analysis. The analysis is done on raw data and all results are compared to a recorded analysis. ''' import os import shutil import unittest from testbeam_analysis import result_analysis from testbeam_analysis.tools import analysis_utils, test_tools testing_path = os.path.dir...
""" This Files creates an additional manage.py command for Django https://docs.djangoproject.com/en/1.10/howto/custom-management-commands/ """ from django.core.management import BaseCommand from eve_data.generation.esi_builder import SwaggerAPIBuilder from eve_data.generation.static_data_builder import create_static_mo...
from .body import IgnoreLargeBody from .header import SetHeader from .status import RejectStatusCode, DetectSoft404, RejectSoft404 from .sampling import ContentHashSampling, ContentSimhashSampling, ContentSampling from .timeout import DynamicTimeout from .redirects import FollowRedirects, RejectCatchAllRedirect, Redire...
from HTMLComponent import HTMLComponent from GUIComponent import GUIComponent from skin import parseColor, parseFont from enigma import eListboxServiceContent, eListbox, eServiceCenter, eServiceReference, gFont, eRect from Tools.LoadPixmap import LoadPixmap from Tools.Directories import resolveFilename, SCOPE_CURRENT...
# Determing sources that require direction dependent calibration solutions # Lerato Sebokolodi <<EMAIL>> import matplotlib matplotlib.use('Agg') import Tigger from Tigger.Coordinates import angular_dist_pos_angle as dist import utils import numpy import math from astLib.astWCS import WCS import pyfits class load(obj...
import sys from utils import Message from hub import HubController from build import GridBuilder def fail(message): Message.fail(message) sys.exit(1) def ok(message): Message.ok(message) def info(message): Message.ok(message) def warning(message): Message.warning(message) def nodes(subject...
import os import sys import re import yaml import shutil import filecmp import collections from dvc.logger import logger from dvc.main import main from dvc import progress from dvc.repo import Repo as DvcRepo from dvc.system import System from dvc.utils import walk_files from tests.basic_env import TestDvc from tests...
import re from .base import RegexVocabulary, NoWildcardsVocabulary, NoCheckVocabulary, RevenueSourceVocabulary _ubrev_split_regex = re.compile('([0-9]+)([A-z]*)') def _ubrev_split(code): match = _ubrev_split_regex.match(code) number_part = match.groups()[0] letter_part = match.groups()[1] return number...
from contextlib import contextmanager from textwrap import dedent import os import subprocess import sys from utils import local_command, log @contextmanager def stdout_cm(): ''' Redirect the stdout or stderr of the child process to sys.stdout. ''' yield sys.stdout @contextmanager def stderr_cm(): ''' ...
#!/usr/bin/env python # -*- coding:utf-8 -*- import threading import time event = threading.Event() # 声明事件 def ligter(): count = 0 event.set() # 设置标志位,先设置绿灯 while True: if count in list(range(6,10)): # 改红灯 event.clear() # 清空标志位 print("\033[41;1mred light is on...\033[0m...
#!/usr/bin/env python """ This class is a container for a demoreport which does not exist and just an example. The report can be placed in the directory: $HOME/.sx/sxreports/ $ cp demoreport.py $HOME/.sx/sxreports/ @author : Shane Bradley @contact : <EMAIL> @version : 2.17 @copyright : GPLv2 """ import os...
#!/usr/bin/env python3 import numpy as np import matplotlib.pyplot as plt import sys import argparse try: from netCDF4 import Dataset as NC except: print("netCDF4 is not installed!") sys.exit(1) parser = argparse.ArgumentParser(description='show scatter plot P versus W from a PISM run') parser.add_argu...
""" Python program related metrics.""" import gc import psutil import traceback from heron.api.src.python.metrics import AssignableMetrics, MultiAssignableMetrics from .metrics_helper import BaseMetricsHelper import heron.common.src.python.system_constants as constants from heron.common.src.python.config import system_...
""" facts.py: A bunch of API methods for interacting with v4 facts in the PuppetDB API. Successful responses will be in application/json. Errors will be returned as non-JSON strings. The result will be a JSON array, with one entry per fact. Each entry is of the form: Generic Response Type { "certname": <node name>...
""" Find heights of pressure levels from models and save Run this first, then geopotential.py """ import os,sys import iris import iris.coords as coords import iris.unit as unit #from tempfile import mkdtemp import numpy as np import os.path as path import datetime import time import h5py #from scipy.interpolate...
""" A Twitter supported and maintained Ads API SDK for Python. """ from twitter_ads.enum import TRANSFORM from twitter_ads.http import Request from twitter_ads.cursor import Cursor from twitter_ads.resource import resource_property, Resource from twitter_ads.creative import Video from twitter_ads.audience import Tail...
# -*- coding: utf-8 -*- import 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 'CustomUser.new_posttweet' db.add_column('app_customuser', 'new_posttweet', ...
import pytest import sys @pytest.mark.skipif(sys.version_info > (3, 0), reason="python-memcached is not supported under python3") def test_default(): from vishnu.backend import PythonMemcached from vishnu.backend.config.memcache import DEFAULT_HOST, DEFAULT_PORT config = PythonMemcached() assert conf...
from __future__ import (absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement) import os import tempfile import unittest from pants.backend.jvm.subsystems.shader import Shader, Shading from pants.java.distribution.distribution import Distributio...
#!/usr/bin/env python #coding=utf-8 """ Author: Xia Kai <<EMAIL>/<EMAIL>> Filename: import.py Date created: 2016-03-20 11:23 Last modified: 2016-03-30 21:17 Modified by: Xia Kai <<EMAIL>/<EMAIL>> Description: Changelog: """ import os import sys from sh import ln, mv from django.conf import sett...
# -*- coding: utf-8 -*- __all__ = ('AdminSettingsForm') from django.contrib.localflavor.br.forms import BRZipCodeField import datetime from PIL import Image, ImageOps from lethusbox.municipios.models import MunicipioBrasil from lethusbox.municipios.constants import UF_CHOICES from lethusbox.django.models imp...
import io from cxio.cx_reader import CxReader from cxio.cx_constants import CxConstants from cxio.ndex_cx_helper import NdexCXHelper # ------- # WRITING # ------- # Writing to a string pretending to be a file/stream fo = io.StringIO("") # Creating a NdexCXHelper w = NdexCXHelper(fo) w.add_cx_context("uni", "unipro...
import sys import pandas as pd import numpy as np from sklearn.metrics import f1_score # # 1. read collectl output file # 2. read log file with the load tests informations (lables) # 3. merge data into one data set # 4. compute benchmark based on expert rules # 5. save dataset into data.csv # 6. create tabl...
from __future__ import print_function import ecto import ecto.ecto_test as ecto_test import subprocess import tempfile import unittest class TestLoadSavePlasm(unittest.TestCase): FILE = tempfile.mkstemp(text=True)[1] #def __del__(self): #os.remove(FILE) def test_0_save_plasm(self): n_nodes...
import json from telegram import InlineKeyboardButton # The dictionary key that will be used to encode callback actions in InlineCallbackButtons ACTION_DICT_KEY = 'a' class InlineCallbackButton(InlineKeyboardButton): def __init__(self, text, callback_action=None, params=None, **kwargs): if not isinstance...
from __future__ import print_function import sys import os import json import io import logging from .compat import JUPYTER log = logging.getLogger(__name__) log.setLevel(20) if JUPYTER: import notebook.nbextensions as nbe from IPython.paths import locate_profile from IPython.utils.py3compat import ca...
from blueman.plugins.ConfigPlugin import ConfigPlugin from gi.repository import GConf import os import subprocess BLUEMAN_PATH = "/apps/blueman" class Gconf(ConfigPlugin): __priority__ = 0 __plugin__ = "GConf" def on_load(self, section): self.section = section if self.section != "": self.section = "/" + s...
import random import string import hashlib from data import Redis EMAIL = 'e' def generate_token(): token = ''.join(random.choice(string.ascii_letters) for i in range(20)) return hashlib.sha224(token.encode('utf-8')).hexdigest() def unsalted_hash(phrase): result = '{0}'.format(hashlib.sha224(phrase.enco...
from core.strategies import MigrationStrategy class FakeMigration(MigrationStrategy): @MigrationStrategy.list_of_vms_to_migrate_strategy def list_of_vms_to_migrate(self, list_of_online_servers): return [] @MigrationStrategy.migrate_vms_strategy def migrate_vms(self, vms): pass
#!/usr/bin/env python # Beginning with the trivial [[0,1]], we can # loop through all primes and elect to add # a new prime or not, branching the recursion # at each step and updating the final sum # Example: # sum = 0 # Branch 1 (pairs=[[0,1]], primes = [5,13]): # 5 out # pairs = [[0,1]], primes = [13] --> 2a # don...
from __future__ import unicode_literals text_1_o = text_1_0 = text_1_1 = text_1_2 = '''{}''' ################################# text_2_o = ''' { } ''' text_2_0 = text_2_1 = text_2_2 = '''{}''' text_2c_o = ''' { # comment... # comments # .... } ''' text_2c_0 = text_2c_1 = text_2c_2 = '''{}''' ###############...
import re from jsonschema import _utils from jsonschema.exceptions import FormatError, ValidationError from jsonschema.compat import iteritems def patternProperties(validator, patternProperties, instance, schema): if not validator.is_type(instance, "object"): return for pattern, subschema in iterite...
""" #;+ #; NAME: #; qso_pca #; Version 1.0 #; #; PURPOSE: #; Module for generate QSO PCA templates #; 24-Nov-2014 by JXP #;- #;------------------------------------------------------------------------------ """ from __future__ import print_function, absolute_import, division, unicode_literals import numpy as n...
"""Settings that need to be set in order to run the tests.""" import os # import sys import tempfile import logging # compat import django if django.VERSION[:2] < (1, 10): from django.core.urlresolvers import reverse_lazy else: from django.urls import reverse_lazy DEBUG = True logging.getLogger("factory").s...
import os import sys from .base import BaseAction from ...misc.utils import prints_body, json_dumps from ..constants import ( BUFSIZE, HTTP_OK, HTTP_OK_CREATED, HTTP_OK_NO_CONTENT, HTTP_OK_PARTIAL_CONTENT, ) class CreateObjectAction(BaseAction): command = "create-object" usage = "%(prog)s...
"""The classes in that module can process image with any valid combination of detector and featurizer.""" import gc import sys import time from datetime import datetime import traceback import multiprocessing from ..detector.utils import get_detector, get_bbox_str from ..featurizer.generic_featurizer import get_featur...
"""Test BIP65 (CHECKLOCKTIMEVERIFY). Test that the CHECKLOCKTIMEVERIFY soft-fork activates at (regtest) block height 1351. """ from test_framework.blocktools import create_coinbase, create_block, create_transaction from test_framework.messages import CTransaction, msg_block, ToHex from test_framework.mininode import ...
from __future__ import print_function import os import sys import syslog import apt import apt_pkg from ubiquity import misc MAGIC_MARKER = "/var/run/ubiquity.updated" # Make sure that ubiquity is last, otherwise apt may try to install another # frontend. UBIQUITY_PKGS = ["ubiquity-casper", "ubiqu...