content
stringlengths
4
20k
import sqlite3 import traceback #copy from https://github.com/binux/libMA/blob/master/basedb.py class BaseDB: ''' BaseDB dbcur should be overwirte ''' @property def dbcur(self): raise Exception("NOT IMPLEMENTED") def _execute(self, sql_query, values=[]): try: ...
# coding=utf-8 # email : <EMAIL> / <EMAIL> # # Monotchromator controller # # TODO: # Make documentation import time import numpy __all__ = ['MonochromatorController'] class MonochromatorController(object): ''' Monotchromator controller to be used with a step motor based harwdare ''' def _...
#!/usr/bin/env python import sys import os import re from collections import OrderedDict # scipy is kinda necessary import scipy import scipy.stats import numpy as np import math def mean_nonan(l): filtered = [x for x in l if not math.isnan(x)] return np.mean(filtered) def gmean_nonzero(l): filtered = [...
__license__ = "MIT <http://www.opensource.org/licenses/mit-license.php>" __author__ = "Tiago Cogumbreiro <<EMAIL>>" __copyright__ = "Copyright 2005, Tiago Cogumbreiro" __doc__ = """ Storage-Widget Persistency defines a set of objects to implement a persistency link between a widget and a certain data store. The data st...
#!/usr/bin/env python # -*- coding: utf-8 -*- '''http://codesnipers.com/?q=python-flyweights''' import weakref class Card(object): '''The object pool. Has builtin reference counting''' _CardPool = weakref.WeakValueDictionary() '''Flyweight implementation. If the object exists in the pool just ret...
""" IrDA infrared data communication. """ from scapy.packet import Packet, bind_layers from scapy.fields import BitEnumField, ByteEnumField, StrField, XBitField, \ XByteField, XIntField, XShortField from scapy.layers.l2 import CookedLinux # IR class IrLAPHead(Packet): name = "IrDA Link Access Protocol Heade...
import gi gi.require_version('Grl', '0.3') from gi.repository import GObject, Gtk from gnomemusic.corealbum import CoreAlbum from gnomemusic.utils import ArtSize from gnomemusic.widgets.twolinetip import TwoLineTip @Gtk.Template(resource_path='/org/gnome/Music/ui/AlbumCover.ui') class AlbumCover(Gtk.FlowBoxChild): ...
import rfc822, string, time, os try: import cStringIO as StringIO except ImportError: import StringIO from twisted.protocols import smtp def generateBounce(message, failedFrom, failedTo, transcript=''): if not transcript: transcript = '''\ I'm sorry, the following address has permanent errors: %(...
#!/usr/bin/env python import rospy # ROS library import rospkg # Scene Graph from turtlebot2i_scene_graph.msg import SceneGraph from turtlebot2i_safety.msg import VelocityScale, SafetyRisk import std_msgs.msg # Parse S-G import pydot # Default pydot doesn't work. pip install -I pydot==1.2.4 import re # Fuzzy logic p...
#!/usr/bin/env python """Simple parsers for OS X files.""" import cStringIO import os import stat from binplist import binplist from grr.lib import parsers from grr.lib.rdfvalues import client as rdf_client from grr.lib.rdfvalues import plist as rdf_plist class OSXUsersParser(parsers.ArtifactFilesParser): """Pa...
#python-encoding: UTF-8 from csc.nl.ja.util import * import re import operator class JaProperties(): ''' Subclass-based inheritance aggregator. Properties are automatically added to this class through the use of shared_property That is, if a child class of JaProperties uses @shared_property, it will appea...
from tempest_lib import decorators import testtools from tempest.common.utils import data_utils from tempest import config from tempest.openstack.common import log as logging from tempest.scenario import manager from tempest import test CONF = config.CONF LOG = logging.getLogger(__name__) class TestNetworkAdvancedS...
from __future__ import print_function, unicode_literals import math import socket import time from datetime import datetime import jsonrpclib import six import sickbeard from sickbeard import classes, logger, scene_exceptions, tvcache from sickbeard.common import cpu_presets from sickbeard.helpers import sanitizeSce...
# coding=utf-8 r""" This code was generated by \ / _ _ _| _ _ | (_)\/(_)(_|\/| |(/_ v1.0.0 / / """ from tests import IntegrationTestCase from tests.holodeck import Request from twilio.base.exceptions import TwilioException from twilio.http.response import Response class TollFreeTestCase(Integrat...
try: # Python 2 libraries. from urllib2 import urlopen from HTMLParser import HTMLParser except ImportError: # Python 3 libraries. from urllib.request import urlopen from html.parser import HTMLParser import time import xml.etree.ElementTree as ET """ This module parses the event page for a s...
import base64 import gzip import logging import math import os import re import requests import shutil import six import stat import tempfile import time from oslo_concurrency import processutils from oslo_config import cfg from oslo_utils import excutils from oslo_utils import units from ironic_lib.openstack.common....
from django.core.management.base import BaseCommand from optparse import make_option from rolemanager.sync import UserRoleSyncUtil class Command(BaseCommand): help = 'Synchronize user and role' option_list = BaseCommand.option_list + ( make_option( '-l', '--load', ...
# coding:utf-8 message_number_table = {'ReqLogin': 101, 'AckLogin': 102, 'ReqLogout': 105, 'AckLogout': 106, 'ReqUserData': 113, 'AckUserData': 114, 'ReqRankList': 107, ...
import abc import six from six.moves.urllib import parse from .. import strutils from . import exceptions def getid(obj): """Return id if argument is a Resource. Abstracts the common pattern of allowing both an object or an object's ID (UUID) as a parameter when dealing with relationships. """ ...
# -*- coding: utf-8 -*- """ tests.http ~~~~~~~~~~ HTTP parsing utilities. :copyright: (c) 2014 by Armin Ronacher. :license: BSD, see LICENSE for more details. """ import pytest from datetime import datetime from tests import strict_eq from werkzeug._compat import itervalues, wsgi_encoding_dance ...
""" Usage: nimbot [options] <host> <port> <nickname> <channel> nimbot -h | --help | --version Options: -c --check-id Force users registered with NickServ to be identified. Server must support account-notify. -f --force-id Force all users to be identified with NickServ. ...
from __future__ import unicode_literals from django.utils.datastructures import SortedDict from mezzanine import template from mezzanine.conf import settings from mezzanine.utils.models import get_user_model from mezzanine.accounts import (get_profile_form, get_profile_user_fieldname, ...
from django.contrib.auth.mixins import AccessMixin from django.contrib.auth import authenticate, login import base64 class SessionOrBasicAuthMixin(AccessMixin): """ Session or Basic Authentication mixin for Django. It determines if the requester is already logged in or if they have provided proper htt...
"""Mantém todas as configurações para da aplicação de cadastro de pontos de cultura. """ import os def get_path(*extrapaths): """Retorna o caminho para alguma coisa que esteja "próxima" ao arquivo de configuração. """ return os.path.join(os.path.dirname(__file__), '..', *extrapaths) TEMPLATE_DIR = get...
# -*- coding: utf-8 -*- from gluon import current from s3 import * from s3layouts import * try: from .layouts import * except ImportError: pass import s3menus as default # ============================================================================= class S3MainMenu(default.S3MainMenu): """ Custom Applica...
from mantid.simpleapi import * #back = 'NOM_1000_event.nxs'#'/SNS/NOM/2011_2_1B_SCI/1/1000/preNeXus/ #van = 'NOM_1000_neutron_event.dat' # 1GB #van = 'NOM_989_event.nxs' van = '/SNS/NOM/2011_2_1B_SCI/1/989/preNeXus/NOM_989_neutron_event.dat' #van = 'NOM_989_neutron_event.dat' # 73GB #dia = '/SNS/users/pf9/NOM_990_even...
# -*- coding: utf-8 -*- """ *************************************************************************** ParameterSelection.py --------------------- Date : August 2012 Copyright : (C) 2012 by Victor Olaya Email : volayaf at gmail dot com ********************...
import json import pytz from datetime import datetime from django import forms from django.test.utils import override_settings from django_webtest import WebTest from django.core.exceptions import ValidationError from . import build_test_urls def validate_xxi_century(value): utc = pytz.timezone("UTC") if val...
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys import os import subprocess import logging VALID_TYPES = ['image/jpeg', 'image/gif', 'image/tiff', 'image/png'] INVALID_TYPES = ['application/pdf'] # Settings recommended as a starting point by Jon Stroop. # See https://groups.google.com/forum/?hl=en#!searchin/...
"""Library for loading and applying the EvalSavedModel.""" from __future__ import absolute_import from __future__ import division # Standard __future__ imports from __future__ import print_function # Standard Imports import numpy as np import tensorflow as tf from tensorflow_model_analysis import types from tensorflo...
import os import logging import requests import yaml import consul from biomaj_process.process_service import ProcessService from biomaj_core.utils import Utils config_file = 'config.yml' if 'BIOMAJ_CONFIG' in os.environ: config_file = os.environ['BIOMAJ_CONFIG'] config = None with open(config_file, 'r') as...
""" Some tests for the App Editor module. """ import unittest from biokbase.narrative.appeditor import ( generate_app_cell ) import json from .util import TestConfig class AppEditorTestCase(unittest.TestCase): @classmethod def setUpClass(self): config = TestConfig() self.specs_list = confi...
""" SoftLayer.tests.config_tests ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :license: MIT, see LICENSE for more details. """ import mock from SoftLayer import config from SoftLayer import testing class TestGetClientSettings(testing.TestCase): @mock.patch('SoftLayer.config.SETTING_RESOLVERS', []) def test_no_...
from django.conf import settings from django.db.models import ( Model, CharField ) from cassandra.cqlengine.connection import get_cluster from cassandra.cqlengine.management import delete_keyspace from djangocassandra.db.backends.cassandra.base import DatabaseWrapper from djangocassandra.db.backends.cassandr...
#!/usr/bin/env python # -*- coding: utf-8 -*- # -*- Python -*- """ @file WiiRemoteTest.py @brief Test Component @date $Date$ """ import sys import time sys.path.append(".") # Import RTM module import RTC import OpenRTM_aist import os def cls(): os.system(['clear','cls'][os.name == 'nt']) # Import Service ...
import datetime import inspect import json import re from django import http from django import forms from django.conf import settings from django.contrib.auth.models import Permission from django.contrib.sites.requests import RequestSite # explicit import because django.forms has an __all__ from django.forms.forms im...
# Definition for singly-linked list. class ListNode(object): def __init__(self, x): self.val = x self.next = None # class Solution(object): # def swapPairs(self, head): # """ # :type head: ListNode # :rtype: ListNode # """ # dummy = ListNode(0) # ...
# -*- coding: utf-8 -*- """This code is a part of Hydra Toolkit .. module:: hydratk.translation.lib.network.inet.client.en.messages :platform: Unix :synopsis: English language translation for INET client messages .. moduleauthor:: Petr Rašek <<EMAIL>> """ language = { 'name': 'English', 'ISO-639-1': '...
import emcee as mc from pearce.emulator import OriginalRecipe, ExtraCrispy, SpicyBuffalo from pearce.mocks import cat_dict import numpy as np from os import path import GPyOpt #training_file = '/u/ki/swmclau2/des/xi_cosmo_trainer/PearceRedMagicXiCosmoFixedNd.hdf5' #training_file = '/u/ki/swmclau2/des/wt_trainer3/Pearc...
"""Support for ISY994 binary sensors.""" from datetime import timedelta from typing import Callable, Union from pyisy.constants import ( CMD_OFF, CMD_ON, ISY_VALUE_UNKNOWN, PROTO_INSTEON, PROTO_ZWAVE, ) from pyisy.nodes import Group, Node from homeassistant.components.binary_sensor import ( DE...
import numpy as np from PyQt4 import QtGui, QtCore class ConcatenateDialog(QtGui.QDialog): def __init__(self, model, parent=None): super(ConcatenateDialog, self).__init__(parent) self._model = model self._layer_names = [] self._name_editable = True self._init_gui() ...
# -*- 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 model 'Account' db.create_table(u'account_account', ( ...
# -*- coding: utf-8 -*- from django.core.urlresolvers import resolve from django.test import TestCase, TransactionTestCase from django.contrib.auth.models import User from django.views.generic import RedirectView from django.db import IntegrityError import shiori.bookmark.views from shiori.bookmark.models import Catego...
#!/usr/bin/env python import sys import os import stat import errno import urllib import zipfile import subprocess HOME_DIR = os.path.expanduser("~") AWS_CLI_DIR = HOME_DIR + "/.aws-cli" AWS_CLI_BIN = AWS_CLI_DIR + "/bin/aws" AWS_CLI_ZIP = AWS_CLI_DIR + "/aws.zip" AWS_CLI_URL = "https://s3.amazonaws.com/aws-cli/awscl...
import numpy as np from .kern import Kern from ...core.parameterization import Param from paramz.transformations import Logexp from paramz.caching import Cache_this class Poly(Kern): """ Polynomial kernel """ def __init__(self, input_dim, variance=1., scale=1., bias=1., order=3., active_dims=None, nam...
from __future__ import absolute_import, unicode_literals import logging import pykka from mopidy import backend from mopidy.local import storage from mopidy.local.library import LocalLibraryProvider from mopidy.local.playback import LocalPlaybackProvider from mopidy.local.playlists import LocalPlaylistsProvider lo...
""" code for transposition of annotations from the annotated source generated in the browser to the final template. """ import json from scrapely.htmlpage import parse_html, HtmlPage, HtmlTag, HtmlTagType from .utils import serialize_tag TAGID = u"data-tagid" def _is_generated(htmltag): template_attr = htmltag.a...
"""Triplets from http://www.jstatsoft.org/v08/i14/paper page 3.""" TRIPLETS = ( (1, 1, 54), (1, 1, 55), (1, 3, 45), (1, 7, 9), (1, 7, 44), (1, 7, 46), (1, 9, 50), (1, 11, 35), (1, 11, 50), (1, 13, 45), (1, 15, 4), (1, 15, 63), (1, 19, 6), (1, 19, 16), ...
# -*- coding: utf-8 -*- from __future__ import absolute_import import datetime import mock import time from django.contrib.auth.models import User from sentry.models import Project from sentry.exceptions import InvalidTimestamp, InvalidInterface, InvalidData from sentry.coreapi import project_from_id, project_from_...
""" Copyright (c) 2016-2017 Tony Lechner and contributors testrattingcapitals.com is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later ve...
# -*- coding: utf-8 -*- import logging import re import werkzeug from openerp.addons.auth_signup.res_users import SignupError from openerp.addons.auth_signup.controllers.main import AuthSignupHome from openerp import http, SUPERUSER_ID from openerp.http import request from openerp.tools.translate import _ _logger = l...
__author__ = 'matt' import re from os.path import splitext, dirname, basename from glob import glob #from Data_Production.TK_files import tk_control #gk_files = tk_control("askopenfilenames(title='Where are your Greek source file?')") #replace the list below with the forms of the word that you want to replace #puttin...
# coding=utf-8 # -------------------------------------------------------------------------- # -------------------------------------------------------------------------- from msrest.serialization import Model class Usage(Model): """ Describes Storage Resource Usage. :param unit: Gets the unit of measurem...
import os import re def find_data_dir(wd, fpath): fpath = fpath.strip() def right_splits(p): yield p while p not in ['', None]: p = p.rsplit(os.path.sep, 1)[0] yield p def left_splits(p): yield p while len(p.split(os.path.sep, 1)) > 1: ...
from openerp.osv import osv, fields class res_user(osv.osv): _inherit = 'res.users' _columns = { 'smtp_server_id': fields.one2many('ir.mail_server', 'user_id', 'Email Server'), }
from __future__ import absolute_import import functools import sys from django.core.urlresolvers import reverse from sentry import tsdb from sentry.testutils import APITestCase class OrganizationStatsTest(APITestCase): def test_simple(self): self.login_as(user=self.user) org = self.create_orga...
from __future__ import unicode_literals from .common import InfoExtractor from ..utils import float_or_none class CanvasIE(InfoExtractor): _VALID_URL = r'https?://(?:www\.)?canvas\.be/video/(?:[^/]+/)*(?P<id>[^/?#&]+)' _TEST = { 'url': 'http://www.canvas.be/video/de-afspraak/najaar-2015/de-afspraak-v...
import logging import unittest import shlex import sys from azure.cli.core.application import APPLICATION, Application, Configuration from azure.cli.core.commands import CliArgumentType, register_cli_argument from azure.cli.core.commands.arm import cli_generic_update_command from azure.cli.core.util import CLIError c...
import re from b2.util.utility import * from b2.build import feature from b2.util import sequence, qualify_jam_action import b2.util.set from b2.manager import get_manager __re_two_ampersands = re.compile ('&&') __re_comma = re.compile (',') __re_split_condition = re.compile ('(.*):(<.*)') __re_split_conditi...
from google.appengine.ext import webapp from google.appengine.ext.webapp import util class MainHandler(webapp.RequestHandler): def get(self): # Set the cross origin resource sharing header to allow AJAX self.response.headers.add_header("Access-Control-Allow-Origin", "*") # Print some JSON ...
""" Fast versions of equilibrium and calculate that "override" the equivalent pycalphad functions for very fast performance. """ from collections import OrderedDict from typing import Sequence, Dict, Optional from numpy.typing import ArrayLike import numpy as np from pycalphad import Model, variables as v from pycalph...
# Implementation of the UCSC genome binning strategy -- heavily commented and # with tests to help understand what's going on. # # Ryan Dale 2013 # # With help from implementations in kent src and Brent Pedersen's cruzdb, # specifically: # # http://genome-source.cse.ucsc.edu/gitweb/?p=kent.git\ # ...
import random import psycopg2 conn = psycopg2.connect("dbname=YOUR_DB_NAME host=YOUR_DB_URL port=YOUR_PORT user=YOUR_USERNAME password=YOUR_PASSWORD") # ^ Just copy line from updateflairs.py. Must match exactly ^ cur = conn.cursor() cur.execute("SELECT * FROM flairs;") result = cur.fetchall() cur.close() conn.close(...
import colorsys import sys import xml.etree.cElementTree as ET # from io import BytesIO from gi.repository import Gtk, Gdk, GObject, Pango from gi.repository.GdkPixbuf import Pixbuf from pychess.compat import PY3 from pychess.System import conf from pychess.System.Log import log from pychess.System.prefix import addD...
#!/usr/bin/env python import os import shutil import glob import time import sys import subprocess import string from optparse import OptionParser, make_option SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__)) PKG_NAME = os.path.basename(SCRIPT_DIR) PARAMETERS = None #XW_ENV = "export DBUS_SESSION_BUS_ADDRESS=...
"""Tests for `round2` and `round2sigfig`.""" import numpy as np import pytest from dapper.tools.rounding import round2, round2sigfig class ca(float): """Make `==` approximate. Example: >>> ca(1 + 1e-6) == 1 True This might be a roundabout way to execute `np.isclose`, but it is a fun way. ...
import datetime import os import requests import time import unittest import unittest.mock import dateutil import httpretty import pkg_resources pkg_resources.declare_namespace('perceval.backends') from grimoirelab_toolkit.datetime import str_to_datetime from perceval.backend import BackendCommandArgumentParser from...
#!/usr/bin/env python """PySide port of the layouts/dynamiclayouts example from Qt v4.x""" from PySide.QtCore import Qt, QSize from PySide.QtGui import (QApplication, QDialog, QLayout, QGridLayout, QMessageBox, QGroupBox, QSpinBox, QSlider, QProgressBar, QDia...
import trio import boto3 from botocore.exceptions import ( ClientError as S3ClientError, EndpointConnectionError as S3EndpointConnectionError, ) from uuid import UUID from functools import partial from parsec.api.protocol import OrganizationID from parsec.backend.blockstore import BaseBlockStoreComponent from ...
#!/usr/bin/python import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt import numpy as np import inspect, os #from rafem.riverbmi import BmiRiverModule N_DAYS = 1000 Save_Daily_Timesteps = 1 Save_Yearly_Timesteps = 0 Save_Fluxes = 1 save_int = 100 # (in days) def plot_coast(spacing, z): import...
import datetime import uuid from oslo.utils import timeutils import six from testtools import matchers from keystone.contrib import revoke from keystone.contrib.revoke import model from keystone.tests import test_v3 from keystone.token import provider def _future_time_string(): expire_delta = datetime.timedelta...
from __future__ import absolute_import from __future__ import unicode_literals import codecs import hashlib import json import json.decoder import logging import six from .errors import StreamParseError json_decoder = json.JSONDecoder() log = logging.getLogger(__name__) def get_output_stream(stream): if six....
import json import os from django.http import HttpResponse, HttpResponseRedirect from django.views.generic import View from django.shortcuts import render, redirect from django.utils.decorators import method_decorator from django.contrib.auth.decorators import login_required from django.views.decorators.csrf import c...
import os, sys import urllib import json import asyncio import tempfile import shutil from cerbero.commands import Command, register_command from cerbero.build.cookbook import CookBook from cerbero.enums import LibraryType from cerbero.errors import FatalError from cerbero.packages.packagesstore import PackagesStore f...
#!/usr/bin/env python # -*- coding: utf-8 -*- # Packetdump for wireshark # sudo tcpdump -nnXSs 0 -i eth0 -s 65535 -w bs_dump 'port 8001' PORT=8001 import logging import datetime import binascii import hashlib from twisted.internet import reactor, protocol, endpoints from twisted.protocols import basic header = False...
''' One-sample confidence intervals for 1D data: NOTES: 1. If mu=None then explicit hypothesis testing is suppressed (i.e. exploratory analysis) Note that the hypothesis test is still conducted implicitly (to compute the CI). However, the explicit null hypothesis rejection decision will not appear when using either "...
""" Mendeley OAuth1 backend, docs at: http://psa.matiasaguirre.net/docs/backends/mendeley.html """ from social.backends.oauth import BaseOAuth1, BaseOAuth2 class MendeleyMixin(object): SCOPE_SEPARATOR = '+' EXTRA_DATA = [('profile_id', 'profile_id'), ('name', 'name'), (...
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import re import sys from setuptools import setup, find_packages # Get the version version_regex = r'__version__ = ["\']([^"\']*)["\']' with open('src/pycohttpparser/__init__.py', 'r') as f: text = f.read() match = re.search(version_regex, text) if...
import os import re from invenio.shellutils import run_shell_command, run_process_with_timeout, Timeout from invenio.plotextractor_output_utils import get_converted_image_name, \ write_message def untar(original_tarball, sdir): """ Here we decide if our file is a...
# -*- coding: utf-8 -*- """ oss2.exceptions ~~~~~~~~~~~~~~ 异常类。 """ import re import xml.etree.ElementTree as ElementTree from xml.parsers import expat from .compat import to_string from .headers import * _OSS_ERROR_TO_EXCEPTION = {} # populated at end of module OSS_CLIENT_ERROR_STATUS = -1 OSS_REQUEST_ERROR...
__author__ = 'Mark Baker email: <EMAIL>' import tkinter as tk from tkinter import ttk as ttk class Dialog(tk.Toplevel): """Framework that's used for generating user alerts - provides more control over standard tcl/tk alert windows such as size, position and focus as well as allowing message checking etc...
try: import start as start cubit = start.start_cubit() except: try: import cubit except: print 'error importing cubit, check if cubit is installed' pass def mesh(filename=None): """create the mesh""" import start as start cfg ...
from settings import * # Make this unique, and don't share it with anybody. # you should not use this one but create another 50 character random string. # Assuming Django Extensions are installed you can accomplish this by # python manage.py generate_secret_key SECRET_KEY = 'c-smw%fitci+m72a48g0&1z9_%q+)gpjg2r%79e(...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import math def inches_to_centi_meters(inches): centi_meters = inches * 2.54 return centi_meters def pounds_to_kilo_grams(pounds): kilo_grams = pounds * 0.453592 return kilo_grams def strip(data): # TODO: Needs documentation # TODO: Needs verif...
"""Module tests.""" from __future__ import absolute_import, print_function from flask import Flask, url_for from invenio_groups import InvenioGroups def test_version(): """Test version import.""" from invenio_groups import __version__ assert __version__ def test_init(): """Test extension initiali...
from datetime import datetime import unittest import shutil import tempfile import os.path import createrepo_c as cr from fixtures import * class TestCaseUpdateRecord(unittest.TestCase): def test_updaterecord_setters(self): now = datetime.now() # Microseconds are always 0 in updateinfo no...
import mock from oslo.config import cfg from oslo.serialization import jsonutils import webob from nova import compute from nova import exception from nova import test from nova.tests.api.openstack import fakes CONF = cfg.CONF CONF.import_opt('password_length', 'nova.utils') def rescue(self, context, instance, resc...
# the python stuff import sys import math import signal import time # numerics import numpy as np # the interface stuff from PyQt4 import QtCore, QtGui # the messaging stuff import lcm from mithl import trigger_t from mithl import state_estimator_particle_set from mithl import state_estimator_particle from data_plot...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations from django.conf import settings def default_categories(apps, schema_editor): Category = apps.get_model("spirit_category", "Category") if not Category.objects.filter(pk=settings.ST_TOPIC_PRIVATE_CATEGORY...
import pyglet from pyglet.gl import * from pyglet.window import key from vec2d import vec2d from collision import line_intersect, calc_new_pos window = pyglet.window.Window(width = 1024, height = 768) fps_display = pyglet.clock.ClockDisplay() pyglet.resource.path = ['assets'] pyglet.resource.reindex() cell_image = py...
from __future__ import absolute_import import io import json import math import os import tarfile import zipfile import flask import werkzeug.exceptions from . import images as model_images from . import ModelJob from origae.pretrained_model.job import PretrainedModelJob from origae import frameworks, extensions fro...
""" EC2 Container Service wrapper for Luigi From the AWS website: Amazon EC2 Container Service (ECS) is a highly scalable, high performance container management service that supports Docker containers and allows you to easily run applications on a managed cluster of Amazon EC2 instances. To use ECS, you create...
#!/usr/bin/env python #! encoding: utf8 import RPi.GPIO as GPIO #importamos la libreria y cambiamos su nombre por "GPIO" import time #necesario para los delays ((tsecs % 3600)%60) class Sensor(): pin=0 boolUpDown=True boolActivate=True firstTime=0.0 secondTime=0.0 time=0.0 space=0.02 speed=0.0 def __init__(se...
{ 'name': 'bird_config', 'summary': """FS-Online BIRD Modifications""", 'description': """ FS-Online Customer Modifications =========================== Use this Addon as a Base for all Customer specific Modifications containing: - Default Settings (User Defaults, Accounts, Taxes, Project Stages, ...) - Vi...
from django import forms from django.forms.utils import flatatt from django.utils.encoding import smart_text from django.utils.safestring import mark_safe from json import dumps class JQueryAutoCompleteWidget(forms.TextInput): def __init__(self, options, *args, **kwargs): self.options = dumps(options) ...
""" Copyright 2017 Red Hat, Inc. Red Hat licenses this file to you 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...
'''lesson_1_5 homework Имеется группа студентов, у каждого из которых есть следующие характеристики: имя, фамилия, пол, предыдущий опыт в программировании (бинарная переменная), 5 оцененных по 10-бальной шкале домашних работ, оценка за экзамен по 10-балльной шкале. Необходимо написать программу, которая в зависимости о...
__author__ = 'xb' import threading import unittest try: from unittest.mock import patch except ImportError: from mock import patch import requests import requests_mock from onedrive_d.api import restapi from onedrive_d.common import netman @requests_mock.Mocker() class TestNetworkMonitor(unittest.TestCase...
import unittest from PySide.QtCore import QPointF from PySide.QtGui import QTransform, QPolygonF, QPolygonF class QTransformTest(unittest.TestCase): def testMap(self): transform = QTransform() values = (10.0, 20.0) tx, ty = transform.map(*values) self.assert_(isinstance(tx, float))...
import os import signal import asyncio import aioredis import traceback import sys class CancelJob(Exception): pass class ImmediateExit(Exception): pass class HandledExit(Exception): pass class TerminateWorker(Exception): pass class Worker: def __init__(self, *, loop: asyncio.A...