content
stringlengths
4
20k
from argparse import ArgumentParser from base64 import urlsafe_b64encode from binascii import hexlify from getpass import getpass from os import urandom import hmac def generate_salt(size): """Create size byte hex salt""" return hexlify(urandom(size)).decode() def generate_password(): """Create 32 byte b...
from __future__ import print_function from __future__ import unicode_literals import os import re import sys import datetime from argparse import ArgumentParser try: import kconfiglib except ImportError: message = """ Could not find the module 'kconfiglib' in the PYTHONPATH: """ message += "\n".join([" {...
import ldap class DS(object): """Abstract directory server instance.""" def __init__(self, dir, port, base_dn, admin_rdn, admin_pw): """ Initialize the instance. Arguments: dir Path to the root of the filesystem hierarchy to create ...
from __future__ import print_function import numpy as np import netCDF4 import xray import scipy.ndimage import subprocess import traceback try: import pandas as pd use_pandas = True except ImportError: use_pandas = False print('Pandas could not be imported. Functions will return data as tuple ' ...
# -*- coding: utf-8 -*- from __future__ import unicode_literals, division, absolute_import, print_function from builtins import * # pylint: disable=unused-import, redefined-builtin import logging import functools from flexget import plugin from flexget.event import event from flexget.manager import Session try: ...
import pickle import math import polyline import yaml geoCache = pickle.load(open('geoCache.p', 'rb')) directionsCache = pickle.load(open('directions.p','rb')) config = yaml.load(open("config.yml", 'r')) def getCoords(place): return geoCache[place] def getCoordString(place): return str(geoCache[pla...
from init_instantiation_data import * include_files = [] data = Instantiation(include_files) (f, inst) = (data.file_output, data.inst) handlers = ['IgFunctionHandler<0,0,0,1>'] for x in inst.all_phy_sp_dims: handler = 'IgFunctionHandler<%d,%d,%d,%d>' %(x.dim,x.codim,x.range,x.rank) handlers.append(handler...
from __future__ import unicode_literals import frappe from frappe.model.document import Document from frappe import _ from frappe.utils import get_fullname exclude_from_linked_with = True class DocShare(Document): no_feed_on_delete = True def validate(self): self.validate_user() self.check_share_permission() ...
from nova.openstack.common.gettextutils import _ # noqa from nova.openstack.common import log as logging from nova.openstack.common import rpc from nova.openstack.common.rpc import dispatcher as rpc_dispatcher from nova.openstack.common import service LOG = logging.getLogger(__name__) class Service(service.Service...
# -*- 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 'Product.image' db.add_column(u'products_product', 'image'...
#!/usr/bin/python #-*- coding: UTF-8 -*- import getopt import os, os.path import sys import re from glob import glob sys.path.append(os.path.join(os.path.dirname(sys.argv[0]), '../support/')) sys.path.append(os.path.join(os.path.dirname(sys.argv[0]), '../mishkal')) sys.path.append(os.path.join(os.path.dirname(sys.arg...
""" Base classes for test cases. """ __author__ = "David Rusk <<EMAIL>>" import os import unittest import wx from mock import Mock from ossos.gui import events class FileReadingTestCase(unittest.TestCase): def get_abs_path(self, relative_path): """ Get the absolute path of a file in the test d...
#!/usr/bin/env python """TriG content-type support for Open Annotation.""" __author__ = 'Sampo Pyysalo' __license__ = 'MIT' import rdftools # Short name for this format. format_name = 'trig' # The MIME types associated with this format. mimetypes = ['application/trig'] def from_jsonld(data, options=None): """...
"""Tools/Database Processing/Rebuild Secondary Indexes""" #------------------------------------------------------------------------- # # python modules # #------------------------------------------------------------------------- from gramps.gen.const import GRAMPS_LOCALE as glocale _ = glocale.translation.gettext #--...
from sos.report.plugins import Plugin, RedHatPlugin, UbuntuPlugin from fnmatch import translate from os import path import re class Kubernetes(Plugin): short_desc = 'Kubernetes container orchestration platform' plugin_name = "kubernetes" profiles = ('container',) option_list = [ ("all", "al...
from __future__ import (absolute_import, division, print_function) __metaclass__ = type from ansible.compat.tests import unittest from ansible.compat.tests.mock import patch, MagicMock from ansible.executor.task_result import TaskResult class TestTaskResult(unittest.TestCase): def test_task_result_basic(self): ...
import flask_login as login from flask_admin import Admin from .views import AdminHomeView, ProvinceView, CityView,\ CountryView, WeatherHistoryView from .models import AdminUser, User from WeatherServer.api.models import Province, City, Country,\ WeatherHist...
from ctypes import c_uint, c_ulong, Structure from bcc import BPF from time import sleep import sys from unittest import main, TestCase arg1 = sys.argv.pop(1) arg2 = "" if len(sys.argv) > 1: arg2 = sys.argv.pop(1) class TestBlkRequest(TestCase): def setUp(self): b = BPF(arg1, arg2, debug=0) sel...
source("../shared/qmls.py") def main(): editorArea = startQtCreatorWithNewAppAtQMLEditor(tempDir(), "SampleApp", "Text {") if not editorArea: return # write code with error (C should be lower case) testingCodeLine = 'Color : "blue"' type(editorArea, "<Return>") type(editorArea, testingC...
from gnuradio import gr, gr_unittest, blocks import lte_swig as lte import lte_test class qa_mib_unpack_vbm (gr_unittest.TestCase): def setUp (self): self.tb = gr.top_block () # setup some dummy data before block instatiation N_rb_dl = 50 phich_dur = 0 phich_res = 1.0 ...
from __future__ import print_function import sys, os sys.path.insert(1, os.path.join("..","..","..")) import h2o from tests import pyunit_utils from h2o.estimators.deepwater import H2ODeepWaterEstimator def cv_airlines(): if not H2ODeepWaterEstimator.available(): return df = h2o.import_file(path=pyunit_utils.loc...
import sys from pivy.coin import * from pivy.sogui import * ############################################################## ## CODE FOR The Inventor Mentor STARTS HERE # Positions of all of the vertices: vertexPositions = ( # 1st row (-13.0, 0.0, 1.5), (-10.3, 13.7, 1.2), ( -7.6, 21.7, 1.0), ( -5.0, 26.1, ...
from unittest import TestCase from mock import patch from mad.simulation.backoff import ConstantBackoff, ExponentialBackoff BASE_DELAY = 25 class ConstantDelayTests(TestCase): def test_constant_delay(self): backoff = ConstantBackoff(BASE_DELAY) for attempts in range(10): self.asser...
# -*- coding: utf-8 -*- """ *************************************************************************** RasterLayerCalculator.py --------------------- Date : November 2016 Copyright : (C) 2016 by Victor Olaya Email : volayaf at gmail dot com ***************...
from collections import deque import time import requests # Constants BRAZIL = 'br' EUROPE_NORDIC_EAST = 'eune' EUROPE_WEST = 'euw' KOREA = 'kr' LATIN_AMERICA_NORTH = 'lan' LATIN_AMERICA_SOUTH = 'las' NORTH_AMERICA = 'na' OCEANIa = 'oce' RUSSIA = 'ru' TURKEY = 'tr' queue_types = [ 'CUSTOM', # Cu...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Calculates possible pH values for a given water volume. Implementation -------------- """ import argparse import numpy as np import euston.io as io import euston.geometry as geo import math parser = argparse.ArgumentParser(description='Calculates possible pH values a...
# -*- coding: utf-8 -*- """ 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 License, or (at your option) any later version. This program is distributed in ...
# -*- 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 model 'Slider' db.create_table('nivoslider_slider', ( ('id', self.gf('django.db.models....
""" Sitemap for the announcements app. """ from django.contrib.sitemaps import Sitemap from .models import (Announcement, AnnouncementTag) class AnnouncementsSitemap(Sitemap): """ Sitemap for the announcements. """ changefreq = 'daily' priority = 0.4 def items(self): ...
"""SCons.Platform.cygwin Platform-specific initialization for Cygwin systems. There normally shouldn't be any need to import this module directly. It will usually be imported through the generic SCons.Platform.Platform() selection method. """ # # Copyright (c) 2001 - 2014 The SCons Foundation # # Permission is here...
"""Axis related components.""" import copy import logging from math import floor import numpy as np from crispy.items import ( BaseItem, DoubleItem, IntItem, Vector3DItem, ComboItem, ) from crispy.quanty import XDB logger = logging.getLogger(__name__) class Broadening(DoubleItem): @propert...
import pytest from django.template.context import RequestContext from cms.api import add_plugin from cms.plugin_rendering import ContentRenderer from cms.utils.plugins import build_plugin_tree from cmsplugin_cascade.models import CascadeElement from cmsplugin_cascade.bootstrap4.accordion import BootstrapAccordionGroupP...
#!/usr/bin/python import sys def read_levels(): f = open('../../../libxc/include/xentoollog.h', 'r') levels = [] record = False for l in f.readlines(): if 'XTL_NUM_LEVELS' in l: break if record == True: levels.append(l.split(',')[0].strip()) if 'XTL_NONE' in l: record = True f.close() olevels ...
from __future__ import print_function, unicode_literals import importlib import os import sys from django.apps import apps from django.db.models.fields import NOT_PROVIDED from django.utils import datetime_safe, six, timezone from django.utils.six.moves import input from .loader import MigrationLoader class Migrat...
""" SALTS XBMC Addon Copyright (C) 2014 tknorris 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 License, or (at your option) any later version. T...
__all__ = ['start', 'stop'] from sys import platform, exit from ctypes import (windll, Structure, sizeof, WINFUNCTYPE, pointer, byref, c_uint, c_int, c_char, c_wchar) from ctypes.wintypes import (HWND, HANDLE, HICON, HBRUSH, HMENU, POINT, LPCWSTR, WPARAM, LPARAM, MSG, RECT, DWORD, WORD) import os import asynci...
import sys #sys.path.append('/home/02608/grantdel/pythonlib/lib/python2.7/site-packages') import psycopg2 import datetime import io class Document: userID = "" userLat = "" userLong = "" fileFrom = "" Feature_Freq = {} total_words = 0 #Feature_Prob = {} def __init__(self, ID, latit...
import zipline from .finance import (commission, slippage) from .utils import math_utils from zipline.finance.slippage import ( FixedSlippage, VolumeShareSlippage, ) batch_transform = zipline.transforms.BatchTransform def symbol(symbol_str, as_of_date=None): """Default symbol lookup for any source that...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """Tests for the bencode parser plugin for Transmission BitTorrent files.""" import unittest from plaso.lib import definitions from plaso.parsers import bencode_parser from tests.parsers.bencode_plugins import test_lib class TransmissionPluginTest(test_lib.BencodePlug...
from spack import * class Tig(AutotoolsPackage): """Text-mode interface for git""" homepage = "https://jonas.github.io/tig/" url = "https://github.com/jonas/tig/releases/download/tig-2.2.2/tig-2.2.2.tar.gz" version('2.2.2', '3b4a9f0fd8d18c1039863e6c4ace6e46') depends_on('ncurses')
# -*- coding: utf-8 -*- from django.db import migrations from django.db.models import Count, Q from wagtail.core.models import Page as RealPage def ancestor_of_q(page): paths = [ page.path[0:pos] for pos in range(0, len(page.path) + 1, page.steplen)[1:] ] q = Q(path__in=paths) return ...
""" homeassistant.components.api ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Provides a Rest API for Home Assistant. """ import re import logging import threading import json import homeassistant as ha from homeassistant.helpers.state import TrackStates import homeassistant.remote as rem from homeassistant.const import ( URL_AP...
import socket import defaultKnownNodes import pickle import time from bmconfigparser import BMConfigParser from debug import logger import knownnodes import socks import state def addKnownNode(stream, peer, lastseen=None, self=False): if lastseen is None: lastseen = time.time() knownnodes.knownNodes[...
from flask import render_template, flash, redirect, url_for , g, session from .forms import LoginForm, SignupForm, EditProfileForm,PostForm from models import User, Post from flask_login import LoginManager, UserMixin, login_user, logout_user,current_user, login_required from apps import lm from apps import db from app...
import os from ctypes import CDLL, get_errno, create_string_buffer, c_ulong, byref from ctypes import RTLD_GLOBAL from ctypes.util import find_library class ChangelogException(OSError): pass libgfc = CDLL(find_library("gfchangelog"), use_errno=True, mode=RTLD_GLOBAL) def raise_oserr(): errn ...
#!/usr/bin/env python #-*- coding: UTF-8 -*- """ This program loads a model with PyASSIMP, and display it. It make a large use of shaders to illustrate a 'modern' OpenGL pipeline. Based on: - pygame + mouselook code from http://3dengine.org/Spectator_%28PyOpenGL%29 - http://www.lighthouse3d.com/tutorials - http:/...
class ModuleDocFragment(object): DOCUMENTATION = """ options: - See respective platform section for more details requirements: - See respective platform section for more details notes: - Ansible modules are available for EMC VNX. """ # Documentation fragment for VNX (emc_vnx) EMC_VNX = """ options: ...
from ptrace.cpu_info import CPU_POWERPC, CPU_INTEL, CPU_X86_64, CPU_I386 CPU_INSTR_POINTER = None CPU_STACK_POINTER = None CPU_FRAME_POINTER = None CPU_SUB_REGISTERS = {} if CPU_POWERPC: CPU_INSTR_POINTER = "nip" # FIXME: Is it the right register? CPU_STACK_POINTER = 'gpr1' elif CPU_X86_64: CPU_INSTR_...
from lib.common import helpers class Module: def __init__(self, mainMenu, params=[]): self.info = { 'Name': 'Get-DomainUser', 'Author': ['@harmj0y'], 'Description': ('Query information for a given user or users in the specified domain. Part of PowerView.'), ...
from __future__ import absolute_import, division, print_function __metaclass__ = type ################################################################################ # Documentation ################################################################################ ANSIBLE_METADATA = {'metadata_version': '1.1', ...
""" This module compiles the intercept library. """ import sys import os import os.path import re import tempfile import shutil import contextlib import logging __all__ = ['build_libear'] def build_libear(compiler, dst_dir): """ Returns the full path to the 'libear' library. """ try: src_dir = os.p...
from gi.repository import GLib, Gio from datetime import datetime import subprocess import json import hashlib import urllib.request from gnomemusic import log import logging logger = logging.getLogger(__name__) BASE_URL = 'http://ws.audioscrobbler.com/2.0/' AUTH_URL = 'http://www.last.fm/api/auth/' TRACK_PLAYING =...
"""Models for Oppia statistics.""" __author__ = 'Sean Lip' import datetime import logging from core.platform import models (base_models,) = models.Registry.import_models([models.NAMES.base_model]) import feconf import utils from google.appengine.ext import ndb MAX_ANSWER_HASH_LEN = 100 def hash_answer(answer): ...
from numba.extending import intrinsic, register_model from sdc.datatypes.hpat_pandas_rolling_types import ( gen_hpat_pandas_rolling_init, RollingType, RollingTypeModel) class SeriesRollingType(RollingType): """Type definition for pandas.Series.rolling functions handling.""" def __init__(self, data, win_ty...
"""Classes and methods related to model_fn.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import collections import six from tensorflow.python.estimator.export.export_output import ExportOutput from tensorflow.python.framework import ops from tensorf...
""" Hubs and authorities analysis of graph structure. """ #!/usr/bin/env python # Copyright (C) 2008-2010 by # Aric Hagberg <<EMAIL>> # Dan Schult <<EMAIL>> # Pieter Swart <<EMAIL>> # All rights reserved. # BSD license. # NetworkX:http://networkx.lanl.gov/ __author__ = """Aric Hagberg (<EMAIL>)""...
import matplotlib.pyplot as plt import networkx as nx import bstree as bst def _get_pos_list(tree): """ _get_pos_list(tree) -> Mapping. Produces a mapping of nodes as keys, and their coordinates for plotting as values. Since pyplot or networkx don't have built in methods for plotting binar...
""" unittest for grampstype """ import unittest from ..grampstype import GrampsType # some simple map items to test with vals = "zz ab cd ef".split() keys = list(range(len(vals))) MAP = [(k, v*2, v) for (k, v) in zip(keys, vals)] BLIST= [1,3] class GT0(GrampsType): _DEFAULT = 1 # just avoiding the pre-coded 0 ...
############################################################################### # Customizable Pickler with some basic reducers # # # adapted from multiprocessing/reduction.py (17/02/2017) # * Replace the ForkingPickler with a similar _LokyPickler, # * Add CustomizableLokyPickler to allow customizing pickling process...
"""Define tests for the AccuWeather config flow.""" import json from accuweather import ApiError, InvalidApiKeyError, RequestsExceededError from homeassistant import data_entry_flow from homeassistant.components.accuweather.const import CONF_FORECAST, DOMAIN from homeassistant.config_entries import SOURCE_USER from h...
from collections import defaultdict import argparse import csv import sys from juno_addresses import parser COLUMNS = [ 'Name', 'Given Name', 'Family Name', 'Nickname', 'E-mail 1 - Value', 'Phone 1 - Type', 'Phone 1 - Value', 'Phone 2 - Type', 'Phone 2 - Value', 'Address 1 - F...
"""pytest for iddgroups""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from six import StringIO import eppy.EPlusInterfaceFunctions.iddgroups as iddgroups iddtxt = """! W/m2, W or deg C ! W/s ! W/W ...
#!/usr/bin/env python # coding: utf-8 import settings import imp import os import sys try: import settings # Assumed to be in the same directory. except ImportError: import sys sys.stderr.write( """Error: Can't find the file 'settings.py' in the directory containing %r. It appears you've customiz...
#Blender 2.65 import bpy import os import struct def wrtf(a, b): file.write(struct.pack(a, b)) main_path = "c:/tmp/" outputfile = os.path.join(main_path, 'model.i3d') file = open(outputfile, 'wb') obj = bpy.context.active_object mesh = obj.data file.write(struct.pack("<i", len(mesh.polygons) * 3)) print(...
"""Utilities to facilitate handling SPF requests and responses.""" __author__ = '<EMAIL> (Alex Nicksay)' # pylint: disable=too-few-public-methods class Header(str): """String subclass representing a HTTP header.""" def cgi_env_var(self): """Formats the header as a CGI environment variable. ...
"""The Subaru integration.""" import asyncio from datetime import timedelta import logging import time from subarulink import Controller as SubaruAPI, InvalidCredentials, SubaruException from homeassistant.config_entries import ConfigEntry from homeassistant.const import CONF_DEVICE_ID, CONF_PASSWORD, CONF_PIN, CONF_...
from gi.repository import Gtk from lollypop.view_artist_albums import ArtistAlbumsView from lollypop.define import Lp, ArtSize class AlbumPopover(Gtk.Popover): """ An ArtistAlbumsView in a popover Not an AlbumDetailedWidget because we want a lazy loading view """ def __init__(self, album...
import os # Prevent Qt.py importing PySide2 and PyQt5. if not os.getenv("QT_PREFERRED_BINDING"): os.environ["QT_PREFERRED_BINDING"] = os.pathsep.join(["PySide", "PyQt4"]) from _appleseedstudio import *
from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} import os # import module snippets from ansible.module_utils.basic import AnsibleModule d...
import unittest from mock import patch from airflow.operators.presto_to_mysql import PrestoToMySqlTransfer class TestPrestoToMySqlTransfer(unittest.TestCase): def setUp(self): self.kwargs = dict( sql='sql', mysql_table='mysql_table', task_id='test_presto_to_mysql_tra...
import hosts, os BASE = '~/vm/images/base/' for hostname in hosts.vm_hosts: # the u below means that this won't overwrite newer files on destination, which could happen by accident if we were careless. cmd = "rsync --sparse -uaxvH %s %s:vm/images/base/ "%(BASE, hostname) print cmd os.system(cmd)
from java.lang import System try: from org.python.core.util import FileUtil create_py_file = FileUtil.wrap except ImportError: from org.python.core import PyFile create_py_file = PyFile from modjy_exceptions import * from modjy_input import modjy_input_object server_name = "modjy" server_param_prefix...
import logging from django.core.validators import MinValueValidator from django.db import models from django.db import transaction from django.utils.html import format_html from django.utils.safestring import mark_safe from django.utils.translation import ugettext_lazy as _ from repanier.const import * from repanier.f...
"""BibFormat element - Prints references """ __revision__ = "$Id$" def format_element(bfo, reference_prefix, reference_suffix): """ Prints the references of this record @param reference_prefix: a prefix displayed before each reference @param reference_suffix: a suffix displayed after each reference ...
from datetime import datetime as dt from django.db import models from django.template.defaultfilters import slugify from django.contrib.auth.models import User from thumbs import ImageWithThumbsField from docutils.core import publish_parts from apps.projects.models import Project class News(models.Model): class ...
from django.conf import settings from django.utils import translation import jingo from mock import Mock, patch from nose.tools import eq_ import amo import amo.tests from addons.models import Addon from translations import helpers from translations.fields import save_signal from translations.models import PurifiedTr...
""" Handles SVG files. """ import os from PyQt5.QtCore import Qt, QUrl import icons import plugin import signals import job.manager import resultfiles import listmodel class SvgFiles(plugin.DocumentPlugin): def __init__(self, document): self._files = None self.current = 0 document.load...
from decision_trees.vhdl_generators.VHDLCreator import VHDLCreator from typing import Union import numpy as np import sklearn.tree from decision_trees.utils.convert_to_fixed_point import convert_to_fixed_point, convert_fixed_point_to_integer from decision_trees.utils.constants import ClassifierType class Split: ...
# -*- coding: utf-8 -*- """Tests for the project and solution classes.""" import unittest from vstools import resources from tests import test_lib class VSConfigurationTest(test_lib.BaseTestCase): """Visual Studio configuration tests.""" def testInitialize(self): """Tests the __init__ function.""" con...
from datetime import datetime from openerp import pooler from openerp.report import report_sxw from openerp.tools.translate import _ from .common_balance_reports import CommonBalanceReportHeaderWebkit from .webkit_parser_header_fix import HeaderFooterTextWebKitParser def sign(number): return cmp(number, 0) cla...
# -*- coding: utf-8 -*- # Author Frank Hu # iDoulist Function 0 - output ''' std test output_list = ['http://book.douban.com/subject/1139336/', 'http://book.douban.com/subject/25724948/'] ''' def output_CLI(output_text, output_doulist): print output_text + ':' for i in output_doulist: print i def...
from __future__ import unicode_literals import datetime import json import re from .common import InfoExtractor from ..utils import ( remove_start, ) class BlinkxIE(InfoExtractor): _VALID_URL = r'^(?:https?://(?:www\.)blinkx\.com/#?ce/|blinkx:)(?P<id>[^?]+)' IE_NAME = 'blinkx' _TEST = { 'ur...
#-*- coding:utf-8 -*- """ This file is part of OpenSesame. OpenSesame 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 License, or (at your option) any later version. OpenSesame is distri...
# -*- coding: utf-8 -*- """ gdown.modules.rapidu ~~~~~~~~~~~~~~~~~~~ This module contains handlers for rapidu. """ import re from datetime import datetime, timedelta from ..module import browser, acc_info_template from ..exceptions import ModuleError def accInfo(username, passwd, proxy=False): """Returns acc...
import functools import operator import unittest from google.cloud import error_reporting from google.cloud.gapic.errorreporting.v1beta1 import ( error_stats_service_client) from google.cloud.proto.devtools.clouderrorreporting.v1beta1 import ( error_stats_service_pb2) from google.protobuf.duration_pb2 import D...
#!/usr/bin/env python from twisted.web import xmlrpc, server class DSACoreService(xmlrpc.XMLRPC): """ A service to start as XML RPC interface to run the DSA Core """ def __init__(self): xmlrpc.XMLRPC.__init__(self) import DsaDataBase3 as Data from astropy.utils.data import dow...
import os import os.path import math from decimal import Decimal import numpy import scipy import scipy.stats import uncertainties from uncertainties import ufloat from uncertainties.unumpy import nominal_values, std_devs def heaviside(x): if x > 0: return x else: return 0 # default is round ...
'''OpenGL extension EXT.separate_specular_color This module customises the behaviour of the OpenGL.raw.GL.EXT.separate_specular_color to provide a more Python-friendly API Overview (from the spec) This extension adds a second color to rasterization when lighting is enabled. Its purpose is to produce textured ...
from Axon.Scheduler import scheduler as _scheduler from Kamaelia.SimpleServerComponent import SimpleServer as _SimpleServer from Kamaelia.Internet.TCPClient import TCPClient as _TCPClient from Kamaelia.Util.Console import ConsoleEchoer as _ConsoleEchoer from Kamaelia.Util.Chargen import Chargen as _Chargen import Axo...
''' database initialization ''' import datetime from flaskext.bcrypt import Bcrypt from mongoengine import * from ivrhub import app bcrypt = Bcrypt(app) from models import * import utilities def seed(): ''' adds a default admin to the system based on your settings usage: $ . /path/to/venv/bin/activat...
"""Intent service for Mycroft's fallback system.""" from collections import namedtuple from .base import IntentMatch FallbackRange = namedtuple('FallbackRange', ['start', 'stop']) class FallbackService: """Intent Service handling fallback skills.""" def __init__(self, bus): self.bus = bus def _f...
"""Tests for Relu and ReluGrad.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np import tensorflow as tf class ReluTest(tf.test.TestCase): def _npRelu(self, np_features): return np.maximum(np_features, np.zeros(np_features.shape...
import re from ooo import FileInfo def get_category(name): tv = re.compile(".*S[0-9][0-9].*|.*complete.*|.*\\.E[0-9].*", re.IGNORECASE) if tv.match(name): return "tv" return "movie" assert get_category("Game of Thrones S01E07 HDTV XviD-ASAP") == "tv" assert get_category("Game of Thrones S01 HDTV...
from basetmmodel import BaseTMModel class TMModel(BaseTMModel): """This is a dummy (testing) translation memory model.""" __gtype_name__ = 'DummyTMModel' display_name = _('Dummy TM provider for testing') description = _('A translation memory suggestion providers that is only useful for testing') ...
from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} from ansible.module_utils.azure_rm_common import AzureRMModuleBase try: from azure.mgmt...
from netforce.controller import Controller from netforce.template import render from netforce.model import get_model from netforce.database import get_connection,get_active_db # XXX: move this from netforce.locale import set_active_locale,get_active_locale from netforce.utils import new_token from .cms_base import Base...
# -*- coding: utf-8 -*- import time import plexapi.utils as utils import pytest from plexapi.exceptions import NotFound def test_utils_toDatetime(): assert ( str(utils.toDatetime("2006-03-03", format="%Y-%m-%d")) == "2006-03-03 00:00:00" ) # assert str(utils.toDatetime('0'))[:-9] in ['1970-01-01'...
from matplotlib import transforms, pyplot as plt from pyrocko import gf from pyrocko.plot import beachball # create source object source1 = gf.DCSource(depth=35e3, strike=0., dip=90., rake=0.) # set size of beachball sz = 20. # set beachball offset in points (one point from each axis) szpt = (sz / 2.) / 72. + 1. / 7...
from django.db import NotSupportedError from django.db.models import Func, Index from django.utils.functional import cached_property __all__ = [ 'BloomIndex', 'BrinIndex', 'BTreeIndex', 'GinIndex', 'GistIndex', 'HashIndex', 'SpGistIndex', ] class PostgresIndex(Index): @cached_property def max_name_l...
from PyQt5.QtCore import Qt from PyQt5.QtWidgets import QFileDialog from tgit import fs from tgit.ui import locations class TrackSelectionDialog(QFileDialog): _FILTERS = {'mp3': "MP3 Files", 'flac': "FLAC files"} def __init__(self, parent, native, delete_on_close): super().__init__(parent) s...