content
string
from textwrap import dedent from dxr.plugins.python.tests import PythonSingleFileTestCase class BasesTests(PythonSingleFileTestCase): source = dedent(""" class Grandparent(object): pass class Parent(Grandparent): pass class Parent2(Grandparent): pass class Child(Parent,...
#!/usr/bin/env python # -*- coding: utf-8 -*- """Update encrypted deploy password in Travis config file.""" from __future__ import print_function import base64 import json import os from getpass import getpass import yaml from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives.as...
from components import helpers from django.db import connection def getNormalizationReportQuery(sipUUID, idsRestriction=""): if idsRestriction: idsRestriction = 'AND (%s)' % idsRestriction cursor = connection.cursor() # not fetching name of ID Tool, don't think we need it. ...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Test of the scripts plugin Copyright 2010-2013 Glencoe Software, Inc. All rights reserved. Use is subject to license terms supplied in LICENSE.txt """ import pytest from omero.cli import CLI, NonZeroReturnCode from omero.config import ConfigXml from omero.p...
""" Grade service """ from datetime import datetime from django.contrib.auth import get_user_model import pytz from six import text_type from lms.djangoapps.grades.course_data import CourseData from lms.djangoapps.grades.subsection_grade import CreateSubsectionGrade from lms.djangoapps.utils import _get_key from opaq...
"""Tests for perfkitbenchmarker.packages.netperf.""" import os import unittest from perfkitbenchmarker.linux_packages import netperf class NetperfParseHistogramTestCase(unittest.TestCase): def setUp(self): data_dir = os.path.join(os.path.dirname(__file__), '..', 'data') result_path = os.path.join(data_d...
import math def fib(n): if n < 2: return 1 a, b, c = 1, 1, 2 for i in range(n-2): a, b, c = b, c, b+c return c # prices = [1.18, 3.19, 5.6, 7.501] # sum(prices) = 10.57 # final price = $11 # constraint 1: sum(your_rounded_prices) == final price # constraint 2: minimize sum(rounding_er...
from music21 import * import numpy as np from music21_chord_tools import root_interval from load_songs_tools import get_train_test_data END_SYMBOL = '' # def add_attributes(seqs): # for seq in seqs: # # attributes # attributes = np.zeros(()) def compute_interval(sym1, sym2): interval_set = ...
from django import forms from allauth.account.forms import (LoginForm, ChangePasswordForm, AddEmailForm, SignupForm, ResetPasswordForm, SetPasswordForm, ResetPasswordKeyForm) from allauth.socialaccount.forms import SignupForm as SocialSignupForm from django.contrib.auth import get_use...
import copy import os import pyauto_functional # Must be imported before pyauto import pyauto import test_utils class NTPTest(pyauto.PyUITest): """Test of the NTP.""" # Default apps are registered in ProfileImpl::RegisterComponentExtensions(). _EXPECTED_DEFAULT_APPS = [ {u'title': u'Chrome Web Store'}, ...
# -*- coding: utf-8 -*- from datetime import datetime from openerp import models, fields, api, _ class livestock_weighing(models.Model): _name = 'livestock.weighing' _description = "Livestock Weighing Model" _order = "animal_id, weighing_date desc" @api.one @api.depends('animal_id', 'current_weig...
from eventlet import tpool from oslo_config import cfg from oslo_utils import importutils import six from nova import exception from nova.i18n import _ from nova.i18n import _LW from nova.openstack.common import log as logging from nova.virt.disk.vfs import api as vfs LOG = logging.getLogger(__name__) guestfs = Non...
from __future__ import division import os import numpy as np import nibabel as nib import matplotlib.pyplot as plt import nose import nose.tools as nt import numpy.testing as npt from .. import mosaic class TestMosaic(object): if "FSLDIR" not in os.environ: raise nose.SkipTest anat_file = os.path.j...
#!/usr/bin/env python # Todo: Record and print total stats at end of run, write out to file, maybe csv. # Todo: Option to record video and xyz # Todo: Turn display on and off. # Todo: conf binary options # Todo: conf write in number option # Todo: Think of ways to make needs_ vars more elegant, maybe a service. # Todo...
import os import shutil import unittest import git from tito.common import * from fixture import TitoGitTestFixture, TEST_SPEC, tito #TITO_REPO = os.path.dirname(os.path.dirname(os.path.dirname(__file__))) PKG_NAME = "titotestpkg" class SingleProjectTests(TitoGitTestFixture): def setUp(self): TitoGitT...
#!/usr/bin/python # -*- coding: utf-8 -*- ''' Unit tests for the loading of configuration files. Tests for the structure of configuration files and the output of functions that load them. ''' import os import unittest import app.utilities.load as Load class TestUtilityLoad(unittest.TestCase): ''' Unit tests for t...
#-*- coding:utf-8 -*- from libopensesame.py3compat import * from libopensesame.exceptions import osexception from libopensesame import item from libqtopensesame.items.qtautoplugin import qtautoplugin from libqtopensesame.misc import _ class psynteract_push(item.item): """Push data to server.""" initial_view = 'c...
import numpy as _np from scipy.special import factorial as _factorial def cross_spectrum(clm1, clm2, normalization='4pi', degrees=None, lmax=None, convention='power', unit='per_l', base=10.): """ Return the cross-spectrum of the spherical harmonic coefficients as a function of spherical...
import posixpath import unittest from extensions_paths import PUBLIC_TEMPLATES from local_file_system import LocalFileSystem from object_store_creator import ObjectStoreCreator from path_canonicalizer import PathCanonicalizer from special_paths import SITE_VERIFICATION_FILE class PathCanonicalizerTest(unittest.TestC...
""" Test libvirt support features in qemu cmdline. BTW it not limited to hypervisors CPU/machine features. """ import logging from autotest.client.shared import error from virttest import virsh from virttest.libvirt_xml import vm_xml from virttest.utils_test import libvirt from provider import libvirt_version def ...
from webscraper import TradeList from datacleaner import DataCleaner from analysis import MarketValue def main(): # Web scraper instance listings = TradeList('Toyota', 'Yaris', 'OX12JD', '100') # Initiate loop price_array, attributes, url_ids, urls, category = listings.run(listings, pages=3, start_pa...
import os import sys import urllib import urllib2 import re import shutil import zipfile import time import xbmc import xbmcgui import xbmcaddon import xbmcplugin import re,urllib,urllib2,sys import plugintools,ioncube addonName = xbmcaddon.Addon().getAddonInfo("name") addonVersion = xbmcaddon.Addo...
""" 3-D variables: -------------- Instantaneous: ['U', 'V', 'OMEGA', 'T', 'QV', 'H'] Time-average: ['DUDTANA'] 2-D variables: -------------- Time-average surface fluxes: ['PRECTOT', 'EVAP', 'EFLUX', 'HFLUX', 'QLML', 'TLML'] Time-average vertically integrated fluxes: ['UFLXQV', 'VFLXQV', 'VFLXCPT', 'VFLXPHI'] Instan...
from collections import defaultdict, Iterable import logging assert logging # silence pyflakes from pymachine.machine import Machine from matcher import Matcher from avm import AVM class FSA(object): def __init__(self): self.states = set() self.input_alphabet = set() self.init_states = se...
"""Django middleware for NDB.""" from google.appengine.ext.ndb import eventloop, tasklets class NdbDjangoMiddleware(object): """Django middleware for NDB. To use NDB with django, add 'ndb.NdbDjangoMiddleware', to the MIDDLEWARE_CLASSES entry in your Django settings.py file. Or, if you are using the ...
"""Perlin noise implementation.""" # Licensed under ISC from itertools import product import math import random def smoothstep(t): """Smooth curve with a zero derivative at 0 and 1, making it useful for interpolating. """ return t * t * (3. - 2. * t) def lerp(t, a, b): """Linear interpolation be...
""" test batched_dot behaviors between NervanaCPU, and NervanaGPU backend against numpy. In NervanaGPU, it supports both N as inside dimension or as outer dimension. In NervanaCPU, it only supports N as inside dimension, since this is what we use. """ import numpy as np from neon.backends.nervanagpu import NervanaGPU ...
""" Module for customer matchers used in testing """ from hamcrest.core import anything from hamcrest.core.base_matcher import BaseMatcher from hamcrest.core.helpers.wrap_matcher import wrap_matcher from pyherc.data import get_items class ContainsItem(BaseMatcher): """ Class to check if given level has Items...
import json import os import sys import time from typing import List, Optional, Dict import progressbar from dateutil.parser import parse sys.path.insert(0, os.path.abspath(os.path.join( os.path.dirname(__file__), "..", '..'))) import pypi_secure.data.db_session as db_session from pypi_secure.data.languages impo...
#! /usr/bin/env python # -*- coding: utf-8 -*- """system.py Unit Tests ..moduleauthor:: Timothy Helton <<EMAIL>> """ import logging import os import os.path as osp import shutil import subprocess import pytest import numpy as np from strumenti.tests.fixtures import \ ChromalogLogCapture from strumenti import s...
"""Utilities related to SSH connection management.""" import os from eventlet import pools from oslo_config import cfg from oslo_log import log as logging import paramiko import six from cinder import exception from cinder.i18n import _, _LI LOG = logging.getLogger(__name__) ssh_opts = [ cfg.BoolOpt('strict_ss...
import logging from simuvex import SimRegisterVariable, SimConstantVariable from angr import Analysis, register_analysis from angr import knowledge from angr.analyses.ddg import DDG, ProgramVariable from ...errors import StaticPoliceTypeError, StaticPoliceKeyNotFoundError from .return_values import ConstantReturnValu...
"""Example extension, also used for testing. See extend.txt for more details on creating an extension. See config-extension.def for configuring an extension. """ from idlelib.config import idleConf from functools import wraps def format_selection(format_line): "Apply a formatting function to all of the selected...
__author__ = 'Stefan Hechenberger <<EMAIL>>' import re import math import logging from .utilities import matrixMult, parseFloats from .svg_attribute_reader import SVGAttributeReader from .svg_path_reader import SVGPathReader log = logging.getLogger("svg_reader") class SVGTagReader: def __init__(self, svgread...
from opus_core.variables.variable import Variable from numpy import zeros, logical_and class n_recent_transitions_to_developed(Variable): """Returns number of times each gridcell transitions from un-developed to developed. """ _return_type="int32" def dependencies(self): return [] ...
# -*- coding: utf8 -*- from django import forms from social.models import Comment, Profil, Message class ConnectProfil(forms.Form): """ formulaire de connexion minimal """ username = forms.CharField(label="Nom d'utilisateur", max_length=30) password = forms.CharField(label="Mot de passe", widget=f...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ compute: Calculate the CIE functions provided by CIE TC 1-97. Copyright (C) 2019 Ivar Farup 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 ...
# coding=utf-8 from PyQt4.QtCore import * from PyQt4.QtGui import * import string, random from modules.mlogviewer import main as mlogviewer from modules.mnote import main as mnote from modules.mexplorer import main as mexplorer from modules.mshell import main as mshell from modules.mscript import main as mscript from m...
import os from xpybuild.propertysupport import * from xpybuild.buildcommon import * from xpybuild.pathsets import * from xpybuild.targets.native import * from xpybuild.targets.copy import Copy from xpybuild.utils.compilers import GCC, VisualStudio include(os.environ['PYSYS_TEST_ROOT_DIR']+'/build_utilities/native_con...
# * * # * If you have any questions about the licensing restrictions on using * # * Nmap in other works, are happy to help. As mentioned above, we also * # * offer alternative license to integrate Nmap into proprietary * # * appl...
from time import ctime # HTML page names SUPVISORS_PAGE = 'index.html' HOST_ADDRESS_PAGE = 'hostaddress.html' PROC_ADDRESS_PAGE = 'procaddress.html' APPLICATION_PAGE = 'application.html' TAIL_PAGE = 'tail.html' STDOUT_PAGE = 'logtail/%s' STDERR_PAGE = 'logtail/%s/stderr' # gravity classes for messages # use of 'erro'...
""" .. module:: l_event_instrument The **L Event Instrument** Model. PostgreSQL Definition --------------------- The :code:`l_event_instrument` table is defined in the MusicBrainz Server as: .. code-block:: sql CREATE TABLE l_event_instrument ( -- replicate id SERIAL, link ...
import re from oslo_log import log as logging from tempest import config, test from tempest.lis import manager from tempest.scenario import utils as test_utils CONF = config.CONF LOG = logging.getLogger(__name__) class Clocksource(manager.LisBase): def setUp(self): super(Clocksource, self).setUp() ...
import logging import os import threading import time import traceback from pilot.common.exception import PilotException, MessageFailure logger = logging.getLogger(__name__) class MessageThread(threading.Thread): """ A thread to receive messages from payload and put recevied messages to the out queues. ...
import time from api import app from datetime import datetime, timedelta import pprint from rethinkdb import RethinkDB; r = RethinkDB() from rethinkdb.errors import ReqlTimeoutError import logging as log from .flask_rethink import RDB db = RDB(app) db.init_app(app) from .apiv2_exc import * from .ds import DS ds = ...
from typing import List from federatedml.protobuf.model_migrate.converter_factory import converter_factory import copy def generate_id_mapping(old_id, new_id): if old_id is None and new_id is None: return {} elif not (type(old_id) == list and type(new_id) == list): raise ValueError('illegal i...
from .field import Field from .exceptions import BadValidation class Form(object): def __init__(self, data=None): self.fields, self.forms = self._get_fields_and_nested_forms() self._initialize_data(data) self.errors = {} self.valid = None def _get_fields_and_nested_forms(self...
import copy from tempest.lib.common.utils import data_utils from tempest import test from neutron.tests.api import base class TestTimeStamp(base.BaseAdminNetworkTest): ## attributes for subnetpool min_prefixlen = '28' max_prefixlen = '31' _ip_version = 4 subnet_cidr = '10.11.12.0/31' new_pr...
""" This is a modified version of the code discussed in Lab 2 as a starting point for Homework 1. qroots has been modified to return real or complex roots. plotq has been modified to plot the quadratic function as a function of a real variable x and the real part of the roots. The homework problem is to modify plo...
# -*- coding: utf-8 -*- ''' Created on Aug 24, 2013 @author: shywel ''' #=============================================================================== # Loops # # Habia dicho que que no necesitamos ningun nuevo contructor; pero vamos a introducir uno y esto hará que construir el motor de busqueda sea mas practico...
from __future__ import division def imagedisp(input): return("\includegraphics[width=3in]{"+input+"}") #Takes input of sympy matrix and outputs pmatrix in LaTeX. def display_matrix(matrix): a=matrix i=0 matsri='\\begin{pmatrix}' while i < len(a[0,:]): j=0 while j < len(a[:,0]): matsri=matsri+st...
import inspect import os from gi.repository import GLib, GObject class MusicLogger(GObject.GObject): """GLib logging wrapper A tiny wrapper aroung the default GLib logger. * Message is for user facing warnings, which ideally should be in the application. * Warning is for logging non-fatal err...
# -*- coding: utf-8 -*- from __future__ import unicode_literals import re import json try: from html.parser import HTMLParser # py3 except ImportError: from HTMLParser import HTMLParser # py2 from django.core.exceptions import ValidationError from django.forms import widgets from django.utils import six from ...
# Configuration file for the Sphinx documentation builder. # # This file only contains a selection of the most common options. For a full # list see the documentation: # https://www.sphinx-doc.org/en/master/usage/configuration.html # -- Path setup -------------------------------------------------------------- # If ex...
# coding: utf-8 import os import codecs import datetime from django.core.validators import email_re from stjornbord.student.models import Student, Klass, LegalGuardian from stjornbord.ou.models import Status from stjornbord.user.models import UserStatus FIELDS = ["Kennitala", "Nafn", "Bekkur", "Netfang forrm1", "Ne...
#{} means just the next positional argument, with default format; #{0} means the argument with index 0, with default format; #{:d} is the next positional argument, with decimal integer format; #{0:d} is the argument with index 0, with decimal integer format. # %r -> raw data hilarious = False joke_eval = "Funny? %r" pr...
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'contents/ui/definition-tabbed.ui' # # by: PyQt4 UI code generator 4.5.2 # # WARNING! All changes made in this file will be lost! from PyQt4 import QtCore, QtGui class Ui_Definition(object): def setupUi(self, Definition): D...
import glob import logging import os.path import pytest import numpy as np from metpy.io.nexrad import Level2File, Level3File, is_precip_mode from metpy.cbook import get_test_data # Turn off the warnings for tests logging.getLogger("metpy.io.nexrad").setLevel(logging.CRITICAL) # # NEXRAD Level 2 Tests # # 1999 fi...
from inspect import getmembers, isclass, ismethod, isfunction import six from .util import _cfg, getargspec __all__ = [ 'expose', 'transactional', 'accept_noncanonical', 'after_commit', 'after_rollback' ] def when_for(controller): def when(method=None, **kw): def decorate(f): _cfg(f...
from flask import Flask from google.cloud import datastore from sklearn.tree import DecisionTreeRegressor import numpy as np import pandas as pd app = Flask(__name__) @app.route('/regression-analysis') def main(): df = load_dataframe() fit_regressor = train_model(df) add_predictions(fit_regressor) def l...
import glob import logging import os from pylib import android_commands from pylib import constants from pylib import perf_tests_helper from pylib.android_commands import errors from pylib.base import base_test_runner from pylib.base import test_result from pylib.utils import run_tests_helper import test_package_apk ...
""" Input-driven parsing for s-expression (sxp) format. Create a parser: pin = Parser(); Then call pin.input(buf) with your input. Call pin.input_eof() when done. Use pin.read() to see if a value has been parsed, pin.get_val() to get a parsed value. You can call ready and get_val at any time - you don't have to wait un...
import os from datetime import datetime, timezone from dateutil.parser import parse from csv import DictWriter, DictReader from .postTable import PostTable from .stack_tools import readRows, latest_dump_date, tags_re class UserTable(): def __init__(self, xmldir, post_t=None): self.xmldir = xmldir self.ta...
from django.db import models from django.utils.translation import ugettext_lazy as _ class DialerSetting(models.Model): """This defines the settings to apply to a user **Attributes**: * ``name`` - Settings name. * ``max_frequency`` - Max frequency, speed of the campaign.\ This is the...
import tensorflow as tf import functools from baselines.common.tf_util import get_session, save_variables, load_variables from baselines.common.tf_util import initialize try: from baselines.common.mpi_adam_optimizer import MpiAdamOptimizer from mpi4py import MPI from baselines.common.mpi_util import sync_...
from pytest_bdd import given, when, then from models.contact import Contact import random from random import randrange @given('a contact list') def contact_list(orm): return orm.get_contact_list() @given('a contact with attributes <firstname>, <lastname>, <address>, <email>, <home_number>, <mobile_number>, <work...
# coding: utf-8 from __future__ import unicode_literals import os import sys import unittest import warnings from tempfile import NamedTemporaryFile, TemporaryDirectory from unittest.mock import patch, Mock if sys.version_info.major < 3: import __builtin__ as builtins else: import builtins from histogram im...
from nextcloudappstore.core.facades import resolve_file_relative_path, \ read_relative_file from nextcloudappstore.core.models import App from nextcloudappstore.core.tests.e2e import TEST_APP_SIG from nextcloudappstore.core.tests.e2e.app_dev_steps import AppDevSteps from nextcloudappstore.core.tests.e2e.base import...
import datetime from flask import Flask, request, session, g, redirect, url_for, \ abort, render_template, flash from contextlib import closing from google.appengine.ext import ndb from config import * app = Flask(__name__) # Should the next line be removed from the mockup? app.con...
"""Base classes for all estimators.""" # License: BSD 3 clause import copy import inspect import warnings import numpy as np from scipy import sparse from .externals import six ############################################################################### def clone(estimator, safe=True): """Constructs a new es...
from setuptools import setup, find_packages from os import path # here = path.abspath(path.dirname(__file__)) # # Get the long description from the README file with open(path.join(here, 'README.md')) as f: long_description = f.read() # setup( name='dicomtools', version='0.0.1', description='Tools for re...
from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User from .models import UserProfile, HostRegistration from django import forms class UserForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput()) class Meta: model = User field...
"""Kea config backend testing relay.""" import pytest from dhcp4_scen import get_address, get_rejected from cb_model import setup_server_for_config_backend_cmds pytestmark = [pytest.mark.v4, pytest.mark.v6, pytest.mark.kea_only, pytest.mark.controlchannel, pyt...
import os,unittest,json import pandas as pd from sqlalchemy import create_engine from igf_data.igfdb.igfTables import Base from igf_data.utils.dbutils import read_dbconf_json from igf_data.igfdb.baseadaptor import BaseAdaptor from igf_data.igfdb.fileadaptor import FileAdaptor from igf_data.igfdb.projectadaptor i...
"""Unit tests for hxl.formulas.functions """ import unittest import hxl.model, datetime import hxl.formulas.functions as f, hxl.formulas.parser as p, hxl.formulas.lexer as l, hxl.formulas.eval as e class TestFunctions(unittest.TestCase): """Test the hxl.formulas.functions class""" TAGS = ["#org", "#adm1", "...
class Config: evristics = { '.m':[ 'Loc *\( *@\"(.*?)\" *\)', 'NSLocalizedString *\( *@\"(.*?)\" *, *.*\)', 'setTitle: *@\"(.*?)\"', '.title *= *@\"(.*?)\"', 'alertMessage:@\"(.*?)\"' ], '.mm':[ 'Loc *\( *@\"(.*?)\" *\)'...
from .common import TestCrmCommon class NewLeadNotification(TestCrmCommon): def test_new_lead_notification(self): """ Test newly create leads like from the website. People and channels subscribed to the Sales Team shoud be notified. """ # subscribe a partner and a channel to the Sales Tea...
''' Websocket proxy that is compatible with OpenStack Nova. Leverages websockify.py by Joel Martin ''' import socket import sys from oslo_log import log as logging from oslo_utils import encodeutils import six from six.moves import http_cookies as Cookie import six.moves.urllib.parse as urlparse import websockify fr...
from django.core.urlresolvers import reverse from django.test import TestCase from django_factory_boy import auth as auth_factories from conference.tests.factories.attendee_profile import AttendeeProfileFactory from conference.tests.factories.conference import ConferenceFactory if 0: from p3.tests.factories.hotelb...
from odoo import _, fields, models class StockWarehouse(models.Model): _inherit = "stock.warehouse" wh_consume_loc_id = fields.Many2one("stock.location", "Consume Location") wh_usage_loc_id = fields.Many2one("stock.location", "Usage Giving Location") consume_type_id = fields.Many2one("stock.picking.t...
#!/usr/bin/env python import argparse import json import sys sys.path.append('../../marathon_autoscaler') from marathon_autoscaler.marathon import Marathon """ This script constructs an Marathon application definition for the Marathon Autoscaler container. Be sure to deploy the latest Marathon Autoscaler docker image...
"""Build a Pyrex file from .pyx source to .so loadable module using the installed distutils infrastructure. Call: out_fname = pyx_to_dll("foo.pyx") """ import os import sys from distutils.errors import DistutilsArgError, DistutilsError, CCompilerError from distutils.extension import Extension from distutils.util impo...
import os import gym import numpy as np import tensorflow as tf from gym import spaces from collections import deque def sample(logits): noise = tf.random_uniform(tf.shape(logits)) return tf.argmax(logits - tf.log(-tf.log(noise)), 1) def cat_entropy(logits): a0 = logits - tf.reduce_max(logits, 1, keep_dim...
# -*- coding: utf-8 -*- import logging import urllib import urllib2 import xml.etree.ElementTree as ET from app.sdk.exceptions import SMS_ERROR from django.conf import settings class SMS(object): CODE = { '00': u'批量短信提交成功(批量短信待审批)', '01': u'批量短信提交成功(批量短信跳过审批环节)', '02': u'IP限制', '03...
from __future__ import unicode_literals from django.db import models from app import settings import uuid, os, logging logger = logging.getLogger(__name__) class Language: ENGLISH = 'en' CHINESE = 'zh' LANGUAGES = ( (ENGLISH, 'English'), (CHINESE, 'Chinese'), ) class Page(mo...
import unittest import magicgraph import random from magicgraph.generators import clique class TestDiGraph(unittest.TestCase): def test_nodes(self): network = clique(5) self.assertEqual(set(range(1, 6)).difference(network.nodes()), set()) def test_adjacency_iter(self): network = clique(3) self...
from django.core.management import call_command from onadata.apps.api.models.project import Project from onadata.apps.api.models.project_xform import ProjectXForm from onadata.apps.main.tests.test_base import TestBase class CommandCreateDefaultProjectTests(TestBase): def setUp(self): TestBase.setUp(self...
class PerShare(object): """ Calculates a commission for a transaction based on a per share cost with an optional minimum cost per trade. """ def __init__(self, cost=0.03, min_trade_cost=None): """ Cost parameter is the cost of a trade per-share. $0.03 means three cents per s...
from gi.repository import Gtk from gi.repository import Pango class AboutWindow(): def __init__(self): self.book=None self.showing=False self.win=Gtk.Window() self.win.set_title("About") self.win.set_default_size(300, 200) self.win.set_geometry_hints(self.win, min...
# -*- coding: utf-8 -*- import glob import logging import pandas as pd import numpy as np from os.path import exists, join from os import path, makedirs from joblib import Parallel, delayed from sklearn.ensemble import RandomForestClassifier from sklearn.linear_model import LogisticRegression from sklearn.svm import...
################################################################################ ### Jensen-Renyi divergences # TODO: make them work for arbitrary sample sizes, integrate into estimate_divs? def renyi_entropy_knns(knns, dim, alphas, Ks): ''' Estimates Renyi entropy using a special case of our estimator above ...
from falcon.util.uri import parse_query_string from werkzeug.http import parse_options_header from werkzeug.formparser import parse_form_data from cStringIO import StringIO import json import datetime def generate_formdata(req, resp, params): """sets prarams['form'] to pass to every endpoint. """ #print "...
from django.conf import settings from django.contrib.auth.models import User, AnonymousUser, Group from django.test import TestCase from object_permissions_m2m.backend import ObjectPermBackend global user, anonymous, object_ class TestBackend(TestCase): def setUp(self): self.tearDown() settings...
# -*- coding: utf-8 -*- # # Basemap documentation build configuration file, created by # sphinx-quickstart on Fri May 2 12:33:25 2008. # # This file is execfile()d with the current directory set to its containing dir. # # The contents of this file are pickled, so don't put values in the namespace # that aren't picklea...
#!/usr/bin/env python import os import time import unittest import proctest import signal import mozunit from mozprocess import processhandler here = os.path.dirname(os.path.abspath(__file__)) class ProcTestKill(proctest.ProcTest): """ Class to test various process tree killing scenatios """ def test_kil...
from smart.backends.slack.loader import SlackDirLoader from smart.channel import PackageChannel from smart import * import os class SlackDirChannel(PackageChannel): def __init__(self, path, recursive, *args): super(SlackDirChannel, self).__init__(*args) self._path = path self._recursive = ...
#!/usr/bin/env python2.7 import sys import requests import xmltodict from collections import OrderedDict ## This script makes use of the NS API, documented extensively here: ## http://www.ns.nl/en/travel-information/ns-api ## The below imports settings.py, which contains your NS login and API key. ## You can sign up...
import Tix class EnumHolder: def __init__(self): self.value = "" return def get(self): return self.value def set(self, val): self.value = val def SelectType(self, newbutton, selected): if (selected == "0"): return self.value = newbutton ...
#!/usr/bin/env python # encoding: utf-8 """ @version: ?? @author: liangliangyy @license: MIT Licence @contact: <EMAIL> @site: https://www.lylinux.net/ @software: PyCharm @file: urls.py @time: 2016/11/2 下午7:15 """ from django.urls import path from django.views.decorators.cache import cache_page from . import views fr...
from flask import request, url_for from funcy import project, rpartial from flask_restful import abort from redash import models, serializers from redash.handlers.base import (BaseResource, get_object_or_404, paginate, filter_by_tags, order_results as...