content
string
''' Non-relativistic unrestricted Hartree-Fock zero-field splitting (In testing) Refs: JCP, 134, 194113 PRB, 60, 9566 JCP, 127, 164112 ''' import time from functools import reduce import numpy from pyscf import lib from pyscf.lib import logger from pyscf.gto import mole from pyscf.ao2mo import _ao2mo from...
from fife.extensions import pychan from fife.extensions.pychan.pychanbasicapplication import PychanApplicationBase from fife.extensions.pychan.fife_pychansettings import FifePychanSettings from fife.extensions.pychan import widgets from fife.extensions.pychan.widgets.buttons import Button from fife.extensions.pychan.in...
import numpy as np import os import itertools import matplotlib.pyplot as plt from parameter_prediction.datasets import dictionary def grouper(iterable, n, fillvalue=None): "Collect data into fixed-length chunks or blocks" # grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx args = [iter(iterable)] * n return ...
from __future__ import absolute_import from PySide import QtCore from PySide import QtGui from panucci import platform class DualActionButton(QtGui.QPushButton): def __init__(self, config, default_icon, default_action, longpress_icon=None, longpress_action=None): super(DualActionButton, self).__init__()...
import os import shutil import tarfile import tempfile from unittest import TestCase from nectar.config import DownloaderConfig from nectar.downloaders.local import LocalFileDownloader from pulp_node import constants, pathlib from pulp_node.distributors.http.publisher import HttpPublisher from pulp_node.manifest impo...
import uuid import os.path as path from resource_management.libraries.script.script import Script from resource_management.core.resources.system import Execute from resource_management.core.exceptions import ExecutionFailed, ComponentIsNotRunning from common import PRESTO_RPM_URL, PRESTO_RPM_NAME, create_connectors, \...
# Multiple Linear Regression # Importing the libraries import numpy as np import matplotlib.pyplot as plt import pandas as pd # Importing the dataset dataset = pd.read_csv('50_Startups.csv') X = dataset.iloc[:, :-1].values y = dataset.iloc[:, 4].values # Encoding categorical data from sklearn.preprocessing import On...
""" Test the ProxyPlugin class""" import unittest import mock from DIRAC import S_OK, S_ERROR from DIRAC.Resources.Catalog.ConditionPlugins.ProxyPlugin import ProxyPlugin __RCSID__ = "$Id $" def mock_getProxyInfo(): return S_OK( {'VOMS': ['/lhcb/Role=user'], 'chain': '[/DC=ch/DC=cern/OU=Organic Units...
import contextlib import logging import os from subprocess import CalledProcessError from snapcraft.internal import common, errors logger = logging.getLogger(__name__) class BasePlugin: @classmethod def schema(cls): """Return a json-schema for the plugin's properties as a dictionary. Of imp...
from __future__ import absolute_import, print_function import warnings import os.path import MDAnalysis as mda import MDAnalysis.analysis.align as align import MDAnalysis.analysis.rms as rms from MDAnalysis import SelectionError from numpy.testing import (TestCase, dec, assert_almost_equal,...
import sys from quantumclient.quantum.v2_0 import nvpnetworkgateway as nwgw from tests.unit import test_cli20 class CLITestV20NetworkGatewayJSON(test_cli20.CLITestV20Base): resource = "network_gateway" def setUp(self): super(CLITestV20NetworkGatewayJSON, self).setUp( plurals={'devices':...
"""Support for IQVIA.""" import asyncio from datetime import timedelta from functools import partial from pyiqvia import Client from pyiqvia.errors import IQVIAError from homeassistant.components.sensor import SensorEntity from homeassistant.const import ATTR_ATTRIBUTION from homeassistant.core import callback from h...
"""Translational Tetrahedral Order Sk ============================================================== """ from __future__ import print_function, division import os import six from six.moves import range import numpy as np from progress.bar import ChargingBar from . import oto class Translational(oto.Orientational): ...
#!/usr/bin/env python # -*- coding: utf-8 -*- import os, sys, pexpect import locale from PyQt4.QtCore import * from PyQt4.QtGui import * code = QTextCodec.codecForName(locale.getpreferredencoding()) QTextCodec.setCodecForLocale(code) # 设置程序能够正确读取到的本地文件的编码方式 QTextCodec.setCodecForTr(code) # 使用设定的code编...
from captcha.fields import ReCaptchaField from django.forms.widgets import Select from django import forms from django.forms.widgets import Textarea from django.utils.translation import get_language, ugettext_lazy as _ from rando.feedback.models import FeedbackCategory class CategorySelect(Select): def render_o...
"""Tests for KafkaDataset.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np import os from tensorflow.contrib.kafka.python.ops import kafka_dataset_ops from tensorflow.python.data.ops import iterator_ops from tensorflow.python.framewor...
import data_import as di import data_generator as dg import moments_cons as mc import feature_map as fm import binom_hmm as bh import numpy as np from scipy import stats import visualize as vis ''' Throughout we use the following conventions: l: length of the horizon pi: initial probability T: transition probability p...
import mock from oslo_vmware import exceptions as vexc from oslo_vmware import vim_util from nova import exception from nova.network import model as network_model from nova import test from nova.tests.unit import matchers from nova.tests.unit import utils from nova.tests.unit.virt.vmwareapi import fake from nova.virt....
'''Unit tests for grit.format.html_inline''' import os import re import sys if __name__ == '__main__': sys.path.append(os.path.join(os.path.dirname(__file__), '../..')) import unittest from grit import util from grit.format import html_inline class HtmlInlineUnittest(unittest.TestCase): '''Unit tests for Html...
"""VisualPyODE: A framework for using iVisual Python and PyODE libraries together. iVisualPyODE is a framework library to aid in using PyODE and Visual Python together. When you create objects they have both physical and visual properties. Supports collision, assemblies, and comes with some helpful enhanced joints ...
try: import sys, time import RPi.GPIO as GPIO except Exception, e: print e sys.exit(2) class Board(object): # Define GPIO pins to use # that are connected to 12 LEDs CHASER_LIGHTS = [7, 8, 10, 11, 12, 13, 15, 16, 18, 19, 21, 22] # 3 onboard LEDs # 2 bufferd 23, 26 # 1 unbufferd 26 ON_BOARD = [23, 24, 2...
from __future__ import unicode_literals import webnotes from webnotes.model import db_exists from webnotes.model.bean import copy_doclist from webnotes.model.code import get_obj sql = webnotes.conn.sql class DocType: def __init__(self, doc, doclist=[]): self.doc = doc self.doclist = doclist # Get Tax...
import Ice, Test, Twoways, TwowaysAMI, Oneways, OnewaysAMI, BatchOneways, sys import BatchOnewaysAMI def test(b): if not b: raise RuntimeError('test assertion failed') def allTests(communicator): ref = "test:default -p 12010" base = communicator.stringToProxy(ref) cl = Test.MyClassPrx.checkedC...
import gi gi.require_version("Gtk", "3.0") from gi.repository import Gtk from .i18n import _, P_ # ---------------------------------------------------------------------------- # class ListActions(object): """ List of childs of selected device .. note:: There are two types of 'actions': 'blivet actions...
from fabric.api import task from fabric.api import run from fabric.api import cd from fabric.api import sudo from fabric.context_managers import prefix from fabric.contrib.console import confirm, prompt from fabric.contrib.files import exists import os GIT_TOP_LEVEL = '/home/bongo/webapps/bongo' def install(package)...
from __future__ import (absolute_import, division, print_function) import unittest from mantid.api import FileProperty, FileAction, AlgorithmManager from mantid.kernel import Direction class FilePropertyTest(unittest.TestCase): def test_constructor_with_name_and_default_and_action(self): prop = FilePrope...
import claripy import logging import time from ... import sim_options as o l = logging.getLogger(name=__name__) ##################### # Dirty calls ##################### # they return retval, constraints # Reference: # http://www-inteng.fnal.gov/Integrated_Eng/GoodwinDocs/pdf/Sys%20docs/PowerPC/PowerPC%20Elapsed...
# encoding: utf-8 # module PyQt4.QtCore # from /usr/lib/python2.7/dist-packages/PyQt4/QtCore.so # by generator 1.135 # no doc # imports import sip as __sip from QObject import QObject class QIODevice(QObject): """ QIODevice() QIODevice(QObject) """ def aboutToClose(self, *args, **kwargs): # real...
import os import infra.basetest class TestLuaBase(infra.basetest.BRTest): config = infra.basetest.BASIC_TOOLCHAIN_CONFIG + \ """ BR2_TARGET_ROOTFS_CPIO=y # BR2_TARGET_ROOTFS_TAR is not set """ def login(self): cpio_file = os.path.join(self.builddir, "images", "rootfs....
# http://pylint-messages.wikidot.com/all-codes """ This module defines properties and functions for collecting LLDP information from a linux device using the ``lldpctl`` command """ from netshowlib.linux import common import xml.etree.ElementTree as ElementTree from collections import OrderedDict def _exec_lldp(iface...
from __future__ import annotations from math import sin, cos from anastruct.basic import FEMException import numpy as np from functools import lru_cache import copy from typing import TYPE_CHECKING, Dict, Optional, List if TYPE_CHECKING: from anastruct.vertex import Vertex from anastruct.fem.node import Node ...
import numpy as np from numpy.linalg import norm from plyfile import PlyData, make2d import zipfile filename = PINS.filename.get() if filename.endswith(".zip"): zipf = zipfile.ZipFile(filename) assert len(zipf.namelist()) == 1 zply = zipf.open(zipf.namelist()[0]) plydata = PlyData.read(zply) else: ...
from selenium import webdriver from selenium.webdriver.common.keys import Keys from django.test import LiveServerTestCase from profiles.models import SurmandlUser class VisitorTest(LiveServerTestCase): def setUp(self): self.browser = webdriver.Firefox() self.browser.implicitly_wait(3) self...
## \file ## \ingroup tutorial_dataframe ## \notebook -draw ## This tutorial shows how VecOps can be used to slim down the programming ## model typically adopted in HEP for analysis. ## ## \macro_code ## \macro_image ## ## \date March 2018 ## \author Danilo Piparo, Andre Vieira Silva import ROOT from math import sqrt ...
import os import sys from OpenGL.raw.GL import glColor3f from OpenGL.raw.GL import glDisable from OpenGL.raw.GL import glEnable from OpenGL.raw.GL import glLoadIdentity from OpenGL.raw.GL import glMatrixMode from OpenGL.raw.GL import glPopMatrix from OpenGL.raw.GL import glPushMatrix from OpenGL.raw.GL.constants impor...
from tests.utils import ( setup_test_env, ) setup_test_env() from softwarecenter.utils import htmlize_package_description #file-roller d1 = """ File-roller is an archive manager for the GNOME environment. It allows you to: * Create and modify archives. * View the content of an archive. * View a file contained in ...
from django.core.management.base import BaseCommand from build.management.commands.base_build import Command as BaseBuild from residue.models import ResidueDataType, ResidueDataPoint from protein.models import * import logging from urllib import request, parse import json,time class Command(BaseBuild): help = '...
from django.conf import settings from django.test import TestCase from django.utils.functional import wraps try: from django.contrib.gis.geos import GEOSGeometry except ImportError: """GDAL / GEOS not installed. Tests will fail if contrib.gis is installed, and will be skipped otherwise""" try: from dj...
import os import sys sys.path.insert(0, os.path.abspath('../..')) # -- General configuration ---------------------------------------------------- # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom ones. extensions = [ 'sphinx...
""" Tests for the views """ from datetime import datetime from urllib import urlencode import ddt from django.urls import reverse from edx_oauth2_provider.tests.factories import AccessTokenFactory, ClientFactory from mock import patch from opaque_keys import InvalidKeyError from pytz import UTC from rest_framework imp...
import re from django import template from django.core.exceptions import ObjectDoesNotExist try: from django.template.loaders.app_directories import _loader as Loader except ImportError: # Django 1.5+ from django.template.loaders.app_directories import Loader from django.utils.safestring import mark_safe f...
''' ThunderGate - an open source toolkit for PCI bus exploration Copyright (C) 2015-2016 Saul St. John 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 Lice...
from ..errors import * from ..logger import ppLogger logger = ppLogger(__name__) class baseVar(object): _typ = None _val = None _ID = None def __init__(self, typ, ID): self._typ = typ self._ID = ID def __str__(self): return str(self._val) def __repr__(self): ...
from __future__ import print_function import sys import os import time import numpy as np import theano import theano.tensor as T import lasagne from lasagne.updates import rmsprop from lasagne.layers import DenseLayer, DropoutLayer, InputLayer from lasagne.nonlinearities import rectify, softmax from lasagne.objective...
import base64 from writers import admx_writer from writers.admx_writer import AdmxElementType def GetWriter(config): '''Factory method for creating ADMXWriter objects for the Chrome OS platform See the constructor of TemplateWriter for description of arguments. ''' return ChromeOSADMXWriter(['chrome_os'], co...
""" Acceptance tests for Home Page (My Courses / My Libraries). """ from bok_choy.web_app_test import WebAppTest from flaky import flaky from opaque_keys.edx.locator import LibraryLocator from uuid import uuid4 from common.test.acceptance.fixtures.catalog import CatalogFixture, CatalogConfigMixin from common.test.acce...
from pykickstart.base import KickstartCommand from pykickstart.errors import KickstartParseError, formatErrorMsg from pykickstart.options import KSOptionParser from pykickstart.i18n import _ class RHEL6_UnsupportedHardware(KickstartCommand): removedKeywords = KickstartCommand.removedKeywords removedAttrs = Ki...
from __future__ import absolute_import, print_function from sentry.models import Environment, GroupRelease, Release from sentry.testutils import APITestCase class GroupEnvironmentDetailsTest(APITestCase): def test_no_data_empty_env(self): self.login_as(user=self.user) group = self.create_group()...
import os from testtools.matchers import Equals, FileExists from snapcraft import yaml_utils from tests import integration class BuildPropertiesTestCase(integration.TestCase): def test_build(self): self.assert_expected_build_state("local-plugin-build-properties") def test_build_legacy_build_propert...
"""Adapter between BigGraphite and Carbon.""" from __future__ import absolute_import # Otherwise carbon is this module. import time import datetime import prometheus_client from six.moves import queue try: from graphite.tags import utils as tags_utils from biggraphite.plugins import tags # TODO: change...
import bee from bee import * import dragonfly from dragonfly.commandhive import commandhive, commandapp from dragonfly.sys import exitactuator from dragonfly.io import display, commandsensor from dragonfly.logic import filter from dragonfly.op.pull import equal2 from dragonfly.std import variable, transistor from drago...
import py from rpython.jit.metainterp.test.support import LLJitMixin from rpython.rlib.jit import JitDriver class ListTests(object): def test_basic_list(self): myjitdriver = JitDriver(greens = [], reds = ['n', 'lst']) def f(n): lst = [] while n > 0: myjitdri...
import os import sys import numpy as np from settings import SMSTOOLS_MODELS, SAMPLES_HOME from src.datasource import MixedSpectrumStream, FlatStream, MPStandardStream, PcaStream, StandardStream from src.fourrier import Fourrier from src.preprocess import pca_fit_write, scaler_fit_write from src.util import play, obj...
import logging from enum import Enum from typing import Dict, Union from Util import Position, Pose from Util.constant import KEEPOUT_DISTANCE_FROM_GOAL, INDIRECT_KICK_OFFSET from Util.geometry import Area, Line from ai.GameDomainObjects import Ball class FieldSide(Enum): POSITIVE = 0 NEGATIVE = 1 # noinsp...
""" Setup script. """ from distutils.core import Command from setuptools import setup class Coverage(Command): """ Coverage setup. """ description = ( "Run test suite against single instance of" "Python and collect coverage data." ) user_options = [] def initialize_optio...
""" start_server.py Global launcher for the server that displays graphs. """ from __future__ import with_statement, absolute_import, print_function from os.path import abspath import sys # assumes the standard distribution paths PACKAGE_NAME = 'pytomo' PACKAGE_DIR = abspath(sys.path[0]) if PACKAGE_DIR not in...
#!/usr/bin/env python3 # -*- coding: UTF-8 -*- # # git-rebase-autotags # # git post-receive hook which will be called after a commit has been modified # by git amend or rebase command to move tags from old commit to new one __author__ = "Benjamin Braba...
#!/usr/bin/env python # -*- coding: utf-8 -*- import re from glob import glob import networkx as nx import numpy as np import matplotlib.pyplot as plt import matplotlib.cm from networkx.readwrite import json_graph import json import itertools import unicodedata as ud from difflib import SequenceMatcher import pickl...
import os.path import hashlib EMPTY_JPG_DATA = \ '\xff\xd8\xff\xe0\x00\x10JFIF\x00\x01\x01\x01\x00H\x00H\x00\x00\xff\xdb' \ '\x00C\x00\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff' \ '\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff' \ '\xff\xff\xff\xff\xff\xff\x...
{ 'name': 'Product Msl', 'version': '1.0', "summary": "Moisture Sensitive Level Management", 'category': 'warehouse', 'depends': ['base', 'stock', 'product_serial' ], 'author': 'TRESCLOUD Henry Granada, Santiago Orozco', 'description': """...
import pytest from runner import get_specs from recognizers_number_with_unit.number_with_unit.number_with_unit_recognizer import recognize_age, recognize_currency, recognize_dimension, recognize_temperature MODELFUNCTION = { 'Age': recognize_age, 'Currency': recognize_currency, 'Temperature': recognize_tem...
import re from oslo_log import log as logging import six from sahara import conductor as c from sahara import context from sahara import exceptions as e from sahara.i18n import _LI from sahara.utils.notification import sender conductor = c.API LOG = logging.getLogger(__name__) NATURAL_SORT_RE = re.compile('([0-9]+)...
"""Support for LG TV running on NetCast 3 or 4.""" from datetime import timedelta import logging from requests import RequestException import voluptuous as vol from homeassistant import util from homeassistant.components.media_player import ( MediaPlayerDevice, PLATFORM_SCHEMA) from homeassistant.components.media...
""" This module defines optimization flags and determines hardware features that some other modules and packages may use in addition to some optimized utilities. """ import os, sys import logging from collections import OrderedDict # Work around different Python versions to get runtime # info on hardware cache sizes _...
from __future__ import print_function import argparse import json import os def main(): args = usage() if not args.file: print("Please provide a json file of questions and answers") return if not os.path.exists(args.file): print("file not found") return q_and_a = get_da...
import smtplib from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from flask import current_app as app import requests from nyaa import models class EmailHolder(object): ''' Holds email subject, recipient and content, so we have a general class for all mail backends. ''...
from datetime import datetime from sqlalchemy import Column, Integer, Boolean, DateTime, String, ForeignKey from sqlalchemy.orm import relationship from courier.keygen import KeyGen from .base import DeclarativeBase from .route import route_message from .account import Account from .account_message import AccountMessag...
"""Support for Rflink sensors.""" import logging from rflink.parser import PACKET_FIELDS, UNITS import voluptuous as vol from homeassistant.components.sensor import PLATFORM_SCHEMA from homeassistant.const import ( ATTR_UNIT_OF_MEASUREMENT, CONF_NAME, CONF_UNIT_OF_MEASUREMENT, ) import homeassistant.helpe...
#!/usr/bin/env python import os.path import sys import re import configparser try: import requests except ImportError: print ("""module requests non trouvé.\ \ninstaller avec pip install requests""") sys.exit(1) try: from bs4 import BeautifulSoup except ImportError: print ("""module beau...
# Coordinate reference systems and functions. # # PROJ.4 is the law of this land: http://proj.osgeo.org/. But whereas PROJ.4 # coordinate reference systems are described by strings of parameters such as # # +proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs # # here we use mappings: # # {'proj': 'longlat', 'ellps': '...
from subprocess import Popen, PIPE, STDOUT # These are taken from http://ivory.idyll.org/blog/mar-07/replacing-commands-with-subprocess __all__ = ['getoutput', 'getstatusoutput'] def getoutput(cmd): "Replacement for commands.getoutput which does not work on Windows." pipe = Popen(cmd, shell=True, stdout=PIPE...
"""Tests for Adam.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np from tensorflow.python.client import session from tensorflow.python.eager import context from tensorflow.python.framework import constant_op from tensorflow.python.fra...
import logging import os import shutil import tempfile from django.conf import settings from django.test import TestCase from lizard_damage import models from lizard_damage import calc import numpy as np from . import factories logger = logging.getLogger(__name__) TESTDATA_DIR = os.path.join(settings.BUILDOUT_DI...
#!/usr/bin/env python # -*- coding: utf-8 -*- # kate: replace-tabs off; indent-width 4; indent-mode normal; remove-trailing-spaces all; # vim: ts=4:sw=4:noexpandtab import dbus import os import json from dbus.mainloop.glib import DBusGMainLoop import gobject # required to prevent the glib main loop to interfere wit...
import unittest from textwrap import dedent from unittest.mock import patch, Mock from blivet.devices import NVDIMMNamespaceDevice from blivet.formats import get_format from blivet.size import Size from tests.unit_tests.pyanaconda_tests import patch_dbus_publish_object, check_task_creation, \ clear_version_from_k...
# Django settings for repartee project. DEBUG = True TEMPLATE_DEBUG = DEBUG ADMINS = ( # ('Your Name', '<EMAIL>'), ) MANAGERS = ADMINS DATABASES = { 'default': { 'ENGINE': 'django.db.backends.', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'. 'NAME': '', # O...
import json import os import socket import sys import uuid import etcd from tendrl.commons import objects from tendrl.commons.utils import etcd_utils from tendrl.commons.utils import event_utils from tendrl.commons.utils import log_utils as logger NODE_ID = None class NodeContext(objects.BaseObject): def __i...
""" Commands specific to Exos """ import logging import os import requests from commands.base import Command, CommandResult from tempfile import NamedTemporaryFile logger = logging.getLogger(__name__) class HandleFileCommand(Command): """ Handle "hello" """ def run(self, parameters: str): ...
# Soma is a fashionable girl. She absolutely loves shiny stones that she can put on as jewellery accessories. # She has been collecting stones since her childhood - now she has become really good with identifying which # ones are fake and which ones are not. Her King requested for her help in mining precious stones, so...
''' Module that collects remote system information ''' import getpass import logging from yandextank.common.util import SecuredShell from ...common.interfaces import AbstractPlugin from ..Phantom import Plugin as PhantomPlugin logger = logging.getLogger(__name__) class Plugin(AbstractPlugin): '''Plugin that col...
#!/usr/bin/python import os, sys import caseAnalyses, globalAnalyses, plmd import plmd.caseFTP # This is the overall Analysis class which merges trajectories, # manages the analysis handler, and emails the final results class Analysis (plmd.PLMD_module): def __init__(self, config): # Load the con...
""" Runs the author disambiguation and identity matching algorithm. Use -h for help. """ from invenio.base.factory import with_app_context @with_app_context() def main(): from invenio.legacy.bibauthorid.cli import main as cli_main return cli_main()
""" Module with tests for the revealhelp preprocessor """ #----------------------------------------------------------------------------- # Copyright (c) 2013, the IPython Development Team. # # Distributed under the terms of the Modified BSD License. # # The full license is in the file COPYING.txt, distributed with thi...
import os import mandrill from faker import Faker from random import randint, choice from seeder import generate_location_json from flask.ext.script import Manager from carpool_app import create_app, db from carpool_app.tasks import build_carpools, send_unconfirmed_email from seeder import generate_vehicle from datetim...
import argparse import json from pprint import pprint from sphinxarg.parser import parse_parser, parser_navigate def test_parse_options(): parser = argparse.ArgumentParser() parser.add_argument('--foo', action='store_true', default=False, help='foo help') parser.add_argument('--bar', action='store_true', ...
import pytest from datetime import time, timedelta import numpy as np import pandas as pd import pandas.util.testing as tm from pandas.util.testing import assert_series_equal from pandas import Series, to_timedelta, isna, TimedeltaIndex from pandas._libs.tslib import iNaT class TestTimedeltas(object): _multipro...
#!/usr/bin/env python """ Ultra-lightweight wrapper around Solr's JSON API. Replaces sunburnt in PANDA. Not a generic solution. """ import datetime from django.conf import settings from django.core.serializers.json import DjangoJSONEncoder from django.utils import datetime_safe from django.utils import simplejson i...
from django.conf import settings _imported = {} _subject_processors = {} def import_target(src): try: module = src.rsplit('.', 1)[0] target = src.rsplit('.', 1)[1] mod = __import__(module, fromlist=[target]) klass = getattr(mod, target) return klass except: ret...
print('Flag functions are here') def many_flags(data, params, band): #input more than one flag print('Initial length is ',len(data)) nparam=len(params) for n in range(0, nparam): datas=data[data[band+params[n]]==False] print() data=datas print('Length after', band, params[n]...
#!/usr/bin/env python import re,sys def get_mRNA(fold_data,speed_scores): rna_seq = [] for datum in fold_data: #get rna for segment that was crystalised seg_start = int(datum.rna_aligned_start) - (int(datum.protein_aligned_start)-1)*3 - 1 seg_end = seg_start + len(datum.protein_sequence)*3 rna = datum.rna...
""" This implements a parallel map operation but it can accept more values than multiprocessing.Pool.apply() can. For example, apply() will fail to pickle functions if they're passed indirectly as parameters. """ from multiprocessing import Process, Pipe, Semaphore, Value __all__ = ['spawn', 'parmap', 'Barrier'] de...
from gettext import gettext as _ from django.db import models from django.db.models.loading import get_model from django.core.exceptions import ValidationError from ipaddr import AddressValueError, IPv4Address, IPv6Address from cyder.base.utils import transaction_atomic from cyder.base.models import BaseModel from cy...
""" Handling of block device information and mapping Module contains helper methods for dealing with block device information """ import itertools from os_win import constants as os_win_const from nova import block_device from nova import exception from nova.i18n import _ from nova import objects from nova.virt imp...
import numpy as np def softmax(x): e_x = np.exp(x - np.max(x)) return e_x / e_x.sum(axis=0) def smooth(loss, cur_loss): return loss * 0.999 + cur_loss * 0.001 def print_sample(sample_ix, ix_to_char): txt = ''.join(ix_to_char[ix] for ix in sample_ix) txt = txt[0].upper() + txt[1:] # capitalize fi...
from twisted.internet.defer import inlineCallbacks from Tribler.Core.Modules.channel.channel import ChannelObject from Tribler.Core.Modules.channel.channel_rss import ChannelRssParser from Tribler.Test.Core.base_test_channel import BaseTestChannel class TestChannel(BaseTestChannel): """ This class contains s...
import numpy as np import numbers from math import log from pyemma._base.serialization.serialization import SerializableMixIn from pyemma.util.annotators import deprecated from pyemma.util.types import is_float_vector, ensure_float_vector from pyemma.coordinates.data._base.streaming_estimator import StreamingEstimator...
""" owtf.shell.pexpect_sh ~~~~~~~~~~~~~~~~~~~~~ """ import logging import sys import pexpect from owtf.db.session import get_scoped_session from owtf.shell.base import BaseShell from owtf.utils.error import user_abort __all__ = ["PExpectShell"] class PExpectShell(BaseShell): def __init__(self): BaseS...
# -*- coding: UTF-8 -*- """ card: Library adapted to request (U)SIM cards and other types of telco cards. Copyright (C) 2010 Benoit Michau 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 versi...
from enum import IntEnum import abc import operator import math from random import getrandbits, randint SEARCH_HOME_RANDOM_FACTOR = 10 SEARCH_FOOD_RANDOM_FACTOR = 15 HOME_DISTANCE_FACTOR = 4.07 HOME_PHEROMONE_STRENGTH = 180 FOOD_PHEROMONE_STRENGTH = 75 def distance(x1, y1, x2, y2): return math.sqrt((x2-x1)**2+(y...
import web import re import karesansui from karesansui.lib.rest import Rest, auth from karesansui.lib.virt.virt import KaresansuiVirtConnection from karesansui.lib.rrd.rrd import RRD from karesansui.lib.utils import is_param, is_empty, \ str2datetime, create_epochsec, get_proc_cpuinfo, \ get_fs_info, get_hdd_l...