content stringlengths 4 20k |
|---|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
# generic imports
import logging
import time
# django imports
from django.db import models
# core models imports
from core.models.organization import Organization
# Get an instance of a LOGGER
LOGGER = logging.getLogger(__name__)
# Set logging levels ... |
# import numpy as np
# import matplotlib.pyplot as plt
# import sys
from cv2 import *
from pylab import *
from skimage.color import rgb2gray
from skimage.util import *
from scipy import misc
sys.path.append( '../../core' )
# from imgutils import *
class xor(object):
"""
Class that creates a xor dataset. Note ... |
#!/usr/bin/env python2
import glob, os, sys, time, re
sys.path.append(os.path.join(os.path.dirname(__file__), ".."))
from . import html_output
def write_addon_overview(folder, addon):
out = open(os.path.join(folder, "index.html"), "w")
def w(x): out.write(x + "\n")
name = addon["name"]
path = "..... |
# To change this template, choose Tools | Templates
# and open the template in the editor.
import time
class GPGEncryption():
ON_POSIX = 'posix' in sys.builtin_module_names
def __init__(self, encrypt_or_decrypt, iterable = None, user = None, passphrase = None, test_branch = False):
self.test_branch =... |
from __future__ import unicode_literals
import frappe, requests, json
from frappe.utils import now, nowdate, cint
from frappe.utils.nestedset import get_root_of
from frappe.contacts.doctype.contact.contact import get_default_contact
@frappe.whitelist()
def enable_hub():
hub_settings = frappe.get_doc('Hub Settings')
... |
from botsocket import twitchStream
import time
import _thread
from time import sleep
import logging
def main():
"""Primary function to execute meekbot"""
#TODO: Adjust once a web framework is setup to run the bot script
streamName = input("Enter the stream name you wish to join: ")
#set loggi... |
import angr
import datetime
import time
class GetSystemTimeAsFileTime(angr.SimProcedure):
timestamp = None
def run(self, outptr):
self.instrument()
self.state.mem[outptr].qword = self.timestamp
def instrument(self):
if angr.options.USE_SYSTEM_TIMES in self.state.options:
... |
import json
import urlparse
from jfr_playoff.logger import PlayoffLogger
from jfr_playoff.remote import RemoteUrl as p_remote
from jfr_playoff.data.tournament import TournamentInfoClient
FLAG_CDN_URL = 'https://cdn.tournamentcalculator.com/flags/'
class TCJsonTournamentInfo(TournamentInfoClient):
@property
... |
"""
sentry.db.models.manager
~~~~~~~~~~~~~~~~~~~~~~~~
:copyright: (c) 2010-2014 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
from __future__ import absolute_import, print_function
import hashlib
import logging
import threading
import weakref
from django.conf imp... |
# -*- coding: utf-8 -*-
from django.core.urlresolvers import reverse
from nani.test_utils.context_managers import LanguageOverride
from nani.test_utils.testcase import NaniTestCase
from nani.test_utils.request_factory import RequestFactory
from testproject.app.models import Normal, Related
from nani.views import Transl... |
import gzip
import os
import shutil
import subprocess
import sys
import time
from importlib import import_module
from shutil import copyfile
from celery.schedules import crontab
from django.conf import settings
from django.core.cache import cache
from django.core.management.commands import diffsettings
import weblate... |
"""Google Cloud Platform library - ml cell magic."""
from __future__ import absolute_import
from __future__ import unicode_literals
import base64
import collections
import copy
import csv
from io import BytesIO
import json
import numpy as np
import os
import pandas as pd
from PIL import Image
import six
import tensor... |
import unittest
from apiary.tools.timestamp import TimeStamp
class TestConstruction(unittest.TestCase):
def testFloatConstruction(self):
ts = TimeStamp(12.3456789)
self.assertEqual(ts.seconds, 12)
self.assertEqual(ts.micros, 345679)
ts = TimeStamp(123.456789)
self.assert... |
# -*- coding: utf-8 -*-
"""
history
~~~~~~~
A tiny example to show how pagination works.
:copyright: (c) 2011-2013 by Selectel, see AUTHORS for details.
:license: LGPL, see LICENSE for more details.
"""
from __future__ import print_function, unicode_literals
import os
import random
import string... |
import xchat
__module_name__ = "inxi"
__module_version__ = "1.0"
__module_description__ = "adds buttons for the most common inxi commands "
# delete buttons, just in case
xchat.command("delbutton CPU")
xchat.command("delbutton SYSTEM")
xchat.command("delbutton GFX")
xchat.command("delbutton AUDIO")
xchat.command("... |
#! /usr/bin/env python
from __future__ import print_function
import openturns as ot
import math as m
ot.PlatformInfo.SetNumericalPrecision(6)
# 1D example
mesh1D = ot.Mesh()
print("Default 1D mesh=", mesh1D)
vertices = ot.NumericalSample(0, 1)
vertices.add([0.5])
vertices.add([1.5])
vertices.add([2.1])
vertices.add(... |
"""Copyright (C) 2013 COLDWELL AG
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 the hope that... |
import errno
import os
import os.path
import sys
from katello.constants import DISABLE_ENABLE_REPOS_VAR, ENABLED_REPOS_CACHE_FILE, ENABLED_REPOS_PLUGIN_CONF, PROFILE_CACHE_FILE
from katello.uep import get_manager, get_uep, lookup_consumer_id
from katello.utils import combined_profiles_enabled, plugin_enabled
from rhs... |
import swift as ft
class TestCase(ft.RestTestCase):
def test(self):
self.maxDiff = None
self.now = 1388534400000
with ft.TempWorkDir() as wd:
ft.create_db()
with ft.Server(self.now) as server:
with ft.Client() as client:
client.s... |
from __future__ import absolute_import
from django.utils import timezone
from mock import Mock, patch
from sentry.testutils import AcceptanceTestCase
class OrganizationRateLimitsTest(AcceptanceTestCase):
def setUp(self):
super(OrganizationRateLimitsTest, self).setUp()
self.user = self.create_use... |
# coding=utf-8
import factory
from factory.django import DjangoModelFactory
from celery_rpc.tests import models
def create_m2m(field_name, field_factory=None):
""" Вспомогательная функция для создания Many-To-Many полей
для PostGeneration декрарации factory_boy.
Сделано на основе документации по factory... |
import sys
from . import Term
from RDFMetadata import model
NS_URI = "http://purl.org/dc/elements/1.1/"
NS_PREFIX = "dc"
contributor = Term(
uri=NS_URI + "contributor",
qname=model.QName(NS_URI, NS_PREFIX, "contributor"),
label="Contributor",
desc="An entity responsible for making contributions to the... |
"""A simple web server for testing purpose.
It serves the testing html pages that are needed by the webdriver unit tests."""
import logging
import os
import socket
import threading
try:
from urllib import request as urllib_request
except ImportError:
import urllib as urllib_request
try:
from http.server i... |
from flask import Blueprint
from flask import request
from flask import jsonify
from urllib import parse
from server.wx import wx_service
from server.wx.sign import Sign
from server.database.model import WxInfo
from server.utility.exception import *
PREFIX = '/wx'
wx_app = Blueprint("wx_app", __name__, url_prefix=PR... |
from optparse import make_option
import jhbuild.moduleset
from jhbuild.commands import Command, register_command
from jhbuild.utils.cmds import get_output
from jhbuild.utils import uprint, N_, _
from jhbuild.errors import CommandError
class cmd_checkbranches(Command):
doc = N_('Check modules in GNOME Git reposito... |
"""
@author: <EMAIL>
@copyright: 2017 Englesh.org. All rights reserved.
@license: https://github.com/Fyzel/weather-data-flaskapi/blob/master/LICENSE
@contact: <EMAIL>
@deffield updated: 2017-06-14
"""
from database import db
from database.models import Humidity, Pressure, Temperature
def create_humi... |
title = 'Pmw.ButtonBox demonstration'
# Import Pmw from this directory tree.
import sys
sys.path[:0] = ['../../..']
import tkinter
import Pmw
class Demo:
def __init__(self, parent):
# Create and pack the ButtonBox.
self.buttonBox = Pmw.ButtonBox(parent,
labelpos = 'nw... |
# coding:utf-8
import numpy as np
from pgmpy.estimators import ParameterEstimator
from pgmpy.factors.discrete import TabularCPD
from pgmpy.models import BayesianModel
class BayesianEstimator(ParameterEstimator):
def __init__(self, model, data, **kwargs):
"""
Class used to compute parameters for ... |
from oslo_log import log
from ovsdbapp import constants as ovsdbapp_const
from neutron_lib.callbacks import events
from neutron_lib.callbacks import registry
from neutron_lib import constants as const
from neutron_lib.plugins import constants as plugin_constants
from neutron_lib.plugins import directory
from neutron... |
from docutils import nodes
from sphinx.domains.python import PyXRefRole
URL_DIRECTIVES = {'url'}
PY_DIRECTIVES = {'class', 'function'}
def setup(app):
"""Install the plugin.
:param app: Sphinx application context.
"""
app.add_role('map', mapping_role)
app.add_config_value('xref_mapping_dict', N... |
# TRANS: Multihead refers to support for multiple computer displays
# TRANS: In this case, it only concerns the special configuration
# TRANS: with multiple X "screens"
__kupfer_name__ = _("Multihead Support")
__kupfer_sources__ = ()
__description__ = ("Will run the keyboard shortcut relay service on additional"
... |
from ert_gui.ide.keywords.definitions import PercentArgument
from ecl.test import ExtendedTestCase
class PercentArgumentTest(ExtendedTestCase):
def test_default_percent_argument(self):
percent = PercentArgument()
validation_status = percent.validate("45%")
self.assertTrue(validation_sta... |
#!/usr/bin/env python
"""
Solve day 8 of Advent of Code.
http://adventofcode.com/2016/day/8
"""
import copy
NUM_ROWS = 6
NUM_COLS = 50
class Screen:
def __init__(self, rows, cols):
self.data = []
for i in range(rows):
self.data.append([False] * cols)
def do_command(self, comm... |
import tempfile
from testing.test_interpreter import BaseTestInterpreter
class TestDir(BaseTestInterpreter):
def test_dir_create(self):
output = self.run("""
$d = dir('/tmp/');
echo $d->path;
""")
assert self.space.str_w(output.pop(0)) == '/tmp/'
def test_dir... |
import pymongo
from pymongo import MongoClient
import json
try:
MONGODB_URI = "mongodb://mysquaremeal:<EMAIL>:57653/mysquaremeal_user_profile_database"
mlab_client = MongoClient(MONGODB_URI, connectTimeoutMS=30000)
db = mlab_client.mysquaremeal_user_profile_database
except ConnectionError:
raise
class... |
"""
Find an equilibrium of an array A of integers.
An equilibrium is an index i such that:
sum(A[:i]) == sum(A[i+1:])
Notes:
* Knowing this can be solved in O(N) helps in coming up
with a creative solution by giving you the confidence to
know that a linear-time solution is possible. How can
one get this ... |
def extractNovelsnowCom(item):
'''
Parser for 'novelsnow.com'
'''
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not (chp or vol) or "preview" in item['title'].lower():
return False
tagmap = [
('My Sister the Heroine and I the Villainess', 'My Sister the Heroine, and I th... |
from __future__ import unicode_literals
import frappe, erpnext
from frappe import _
from frappe.utils import formatdate, format_datetime, getdate, get_datetime, nowdate, flt, cstr, add_days, today
from frappe.model.document import Document
from frappe.desk.form import assign_to
from erpnext.hr.doctype.employee.employee... |
import math
try:
import asyncio
except ImportError:
## Trollius >= 0.3 was renamed
import trollius as asyncio
from autobahn import wamp
from autobahn.wamp.exception import ApplicationError
from autobahn.asyncio.wamp import ApplicationSession
@wamp.error("com.myapp.error1")
class AppError1(Exception):
"... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['stableinterface'],
'supported_by': 'community'}
import os
import smtplib
import ssl
import traceback
from email import encoders
fro... |
#!/usr/bin/env python
from collections import Counter
from sqlalchemy.sql import and_, literal_column, select
from sqlalchemy.types import Float
from pyfiles.common_helpers import do_cluster, group_unsorted
def get_routes(db, threshold, user, start=None, end=None):
ends = db.metadata.tables["leg_ends"]
leg... |
# -*- coding: utf-8 -*-
"""Mix-in classes for project views."""
from __future__ import (
absolute_import, division, print_function, unicode_literals)
import logging
from builtins import object
from datetime import datetime, timedelta
from django.conf import settings
from django.core.urlresolvers import reverse
fr... |
"""
Utility module for modifying os.environ
:author: Toon Willems (Ghent University)
:author: Ward Poelmans (Ghent University)
"""
import copy
import os
from vsc.utils import fancylogger
from vsc.utils.missing import shell_quote
from easybuild.tools.build_log import EasyBuildError, dry_run_msg
from easybuild.tools.co... |
#!/usr/bin/env python
import subprocess, shlex
import argparse
import tempfile
import time
import os, os.path
import sys
import stat
try: input = raw_input; # 2.x and 3.x compatibility hack
except: pass;
HELPTEXT = """
journal.py attempts to be a simple-as-possible-but-not-simpler personal journal program using g... |
import re
from mapproxy.srs import SRS
from mapproxy.config import abspath
from mapproxy.util.geom import (
load_datasource,
load_ogr_datasource,
load_polygons,
require_geom_support,
build_multipolygon,
)
from mapproxy.util.coverage import coverage
bbox_string_re = re.compile(r'[-+]?\d*.?\d+,[-+]... |
from __future__ import absolute_import
# this is needed to get logging info in `py.test` when something fails
import logging
logging.basicConfig()
from builtins import range
import json
import os
import shutil
import tempfile
import unittest
from elasticluster import Cluster
from elasticluster.cluster import Struct,... |
from sys import exit
from random import randint
class Scene(object):
def enter(self):
pass
class Engine(object):
def __init__(self, scene_map):
self.scene_map = scene_map
def play(self):
current_scene = self.scene_map.opening_scene()
while True:
print "\n----------"
next_scene_name = current_scen... |
import pickle
from uwhoisd import rl
from . import utils
class TokenBucket(rl.TokenBucket):
"""
A token bucket with a fake clock.
"""
def __init__(self, rate, limit, clock=None):
self.clock = utils.Clock() if clock is None else clock
super(TokenBucket, self).__init__(rate, limit)
d... |
"""
Excellon Tool Definition File module
====================
**Excellon file classes**
This module provides Excellon file classes and parsing utilities
"""
import re
try:
from cStringIO import StringIO
except(ImportError):
from io import StringIO
from .excellon_statements import ExcellonTool
def loads(data... |
#-------------------------------------------------------------------------
# Copyright (c) Microsoft. All rights reserved.
#
# Licensed 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.apa... |
import numpy as np
from classifip.representations.credalset import CredalSet
from math import fabs
class LinVac(CredalSet):
"""Class of linear vacuous model: a single probability
distribution + epsilon index.
:param proba: a 1xn array containing probability
:type proba: :class:`~numpy.array`
:... |
# -*- coding: utf-8 -*-
import scrapy
from scrapy.loader import ItemLoader
from novel.items import NovelItem
class CommonSpider(scrapy.Spider):
name = "common"
def __init__(self, url, *args, **kwargs):
# Note super() only works for new-style classes.
super(CommonSpider, self).__init__(*args,... |
#!/usr/bin/env python
from hachoir_core.error import HachoirError
from hachoir_core.cmd_line import unicodeFilename
from hachoir_parser import createParser
from hachoir_core.tools import makePrintable
from hachoir_metadata import extractMetadata
from hachoir_core.i18n import initLocale
from sys import argv, stderr, exi... |
#!/usr/bin/python
# THIS TOOL, LIKE, GETS COMMENTS FROM A COMMUNITY OR WHATEVER.
import codecs, glob, os, pickle, pprint, logging, re, sys, time, urllib, urllib2
import xml.dom.minidom, xmlrpclib, socket
from xml.sax import saxutils
from optparse import OptionParser
import hswcsecret, hswcutil
import sqlite3
import ... |
_dbutils = {}
class Generic_dbutils:
"""Default database utilities."""
def __init__(self):
pass
def tname(self, table):
if table != 'biosequence': return table
else: return 'bioentry'
def last_id(self, cursor, table):
# XXX: Unsafe without transactions isolation
... |
# coding: UTF-8
'''''''''''''''''''''''''''''''''''''''''''''''''''''
file name: model.py
create time: 2018年06月11日 星期一 13时53分42秒
author: Jipeng Huang
e-mail: <EMAIL>
github: https://github.com/hjptriplebee
'''''''''''''''''''''''''''''''''''''''''''''''''''''
#evalute model, just for test
import data
fro... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from django.core.urlresolvers import reverse
from django.test import TestCase
from wagtail.tests.utils import WagtailTestUtils
from wagtail.wagtailcore.models import Page
class TestExplorerNavView(TestCase, WagtailTestUtils):
"""
... |
# -*- coding: utf-8 -*-
"""QGIS Unit tests for Postgres QgsAbastractProviderConnection API.
.. note:: This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your opti... |
# -*- coding: utf-8 -*-
'''
Exodus Add-on
Copyright (C) 2016 Exodus
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 opti... |
'''
Encapsulate global (per thread) state.
This is for state that can affect the current parse. It's probably simplest to
explain an example of what it can be used for. Memoization records results
for a particular state to avoid repeating matches needlessly. The state used
to identify when "the same thing is happen... |
# -*- coding: utf-8 -*-
from trytond.pool import PoolMeta
from trytond.model import fields
from trytond.pyson import Eval, Bool, Not
__all__ = ['Product']
__metaclass__ = PoolMeta
class Product:
"Product"
__name__ = 'product.product'
country_of_origin = fields.Many2One(
'country.country', 'Cou... |
import json
from django import forms
from django.core import validators
from django.core.exceptions import ValidationError
from django.utils.encoding import smart_str
from django.contrib import messages
from django.http import HttpResponseRedirect, HttpResponse
from django.utils.translation import ugettext_lazy as _
f... |
from time import time, sleep
from inbox import Inbox
import re
import os
import html
from glob import glob
from bg import background
class emailDict(dict):
def __init__(self, *args, **kwargs):
self.update(*args, **kwargs)
def __getitem__(self, key):
value = dict.__getitem__(self, key)
... |
# -*- coding: UTF-8 -*-
from flask import url_for
class CDN(object):
"""Base class for CDN objects."""
def __init__(self, **kwargs):
for key, val in kwargs.items():
setattr(self, key, val)
def get_resource_url(self):
"""Return resource url for filename."""
raise NotIm... |
import os
import unittest
from unittest import mock
from external.odds.betclic.api import get_odds, get_odds_from_html
from memoize import delete_memoized
BETCLIC_TESTS_FOLDER = os.path.dirname(os.path.abspath(__file__))
class TestBetclicOdds(unittest.TestCase):
def setUp(self):
"""
Clears odds... |
"""
Provides the definition of a Bit Field,
"""
import uuid
def clean_signal(name):
"Removes white space from a string, replacing them with underscores."
return "_".join(name.strip().split())
class BitField(object):
"""
BitField - holds all the data related to a bit field (one or more bits
of a... |
import sqlite3
import json
import time
import logging
import re
import os
from DbCursor import DbCursor
class Db:
def __init__(self, schema, db_path):
self.db_path = db_path
self.db_dir = os.path.dirname(db_path) + "/"
self.schema = schema
self.schema["version"] = self.schema.get... |
from ovh import APIError
def get_current_cred(client):
try:
credential = client.get('/auth/currentCredential')
except APIError:
raise
return credential
# TODO: clear unused code below
def has_valid_cred(client):
try:
cred = get_current_cred(client)
except APIError:
... |
#!/usr/bin/env python
"""SciPy: Scientific Library for Python
SciPy (pronounced "Sigh Pie") is open-source software for mathematics,
science, and engineering. The SciPy library
depends on NumPy, which provides convenient and fast N-dimensional
array manipulation. The SciPy library is built to work with NumPy
arrays, a... |
# -*- coding: utf-8 -*-
"""
Volunteer Management System
@author: Zubair Assad
@author: Pat Tressel
@author: Fran Boon
"""
module = "vol"
if deployment_settings.has_module(module):
# -------------------------------------------------------------------------
# vol_volunteer (Component of pr_pe... |
# -*- coding: iso-8859-1 -*-
"""
MoinMoin - WSGI application
@copyright: 2003-2008 MoinMoin:ThomasWaldmann,
2008-2008 MoinMoin:FlorianKrupicka
@license: GNU GPL, see COPYING for details.
"""
import os
from MoinMoin import log
logging = log.getLogger(__name__)
from MoinMoin.we... |
"""
Support to allow pieces of code to request configuration from the user.
Initiate a request by calling the `request_config` method with a callback.
This will return a request id that has to be used for future calls.
A callback has to be provided to `request_config` which will be called when
the user has submitted c... |
# 2011 Sprout StreetBump Team
import filters
from google.appengine.ext import db
from google.appengine.ext import webapp
from google.appengine.ext.webapp import util
import os
import sys
from google.appengine.ext.webapp import template
import csv
import StringIO
from django.utils import simplejson
import constants a... |
import datetime
import os
import stat
import warnings
from django.contrib.messages import constants as message_constants
from django.core import exceptions, urlresolvers
from kombu.common import Broadcast, Exchange, Queue
from kombu.serialization import registry
import configobj
import djcelery
import jsondate
import... |
'''
lifecycle.Start
~~~~~~~~~~~~~~~
Downloads and starts the Cloudify Host-Pool Service
'''
import pkgutil
import os
from time import sleep
from string import Template
import tempfile
from subprocess import Popen, PIPE, call
import requests
from cloudify import ctx
from cloudify.exceptions import NonRecove... |
import os
from pants.testutil.pants_run_integration_test import PantsRunIntegrationTest
class BuildGraphIntegrationTest(PantsRunIntegrationTest):
@classmethod
def use_pantsd_env_var(cls):
"""Some of the tests here expect to read the standard error after an intentional failure.
However, when ... |
# -*- encoding:utf-8 -*-
from mako import runtime, filters, cache
UNDEFINED = runtime.UNDEFINED
__M_dict_builtin = dict
__M_locals_builtin = locals
_magic_number = 5
_modified_time = 1301718493.657292
_template_filename='/home/boo/devel/require2/tutorial/pylons/form/form/templates/userdata/edit.mako'
_template_uri='/us... |
#!/usr/bin/env python
# Renders views and STL cache for printed parts
import os
import openscad
import shutil
import sys
import c14n_stl
import re
import json
import jsontools
from types import *
from views import polish;
from views import render_view;
def printed():
print("Printed Parts")
print("-----... |
"""Home of the `Sequential` model.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import copy
from tensorflow.python.keras import backend as K
from tensorflow.python.keras import layers as layer_module
from tensorflow.python.keras.engine import base_la... |
#!/usr/bin/python
# Native
import os
import sys
import optparse
import logging
logging.basicConfig(level=logging.DEBUG)
# Append our system path
sys.path.append(os.path.join(os.getcwd(), "../../"))
# LO-PHI Classes
from lophi.sensors.disk.physical import DiskSensorPhysical
# Globals
PHY_HOST = "172.20.1.1"
def m... |
"""
Contains information relevant to Sensor class
"""
import operator
import unidecode
from nordb.core.validationTools import validateFloat
from nordb.core.validationTools import validateInteger
from nordb.core.validationTools import validateString
from nordb.core.validationTools import validateDate
from nordb.core.u... |
import os
import test_sql_template
from mysql.utilities.exception import MUTLibError, UtilDBError
_PARENT_TABLE = "CREATE TABLE diff_table.t2 (a_i int not null " + \
"primary key) engine=Innodb;"
# Note: removing auto_increment does not work correctly.
# do tests for :
# - primary key, no primary ke... |
import unittest
from mock import Mock
from redmate.mapping import Redis2DbMapper
class Redis2DbMapperTest(unittest.TestCase):
def setUp(self):
self.db = Mock(name="db-connection-mock")
self.redis = Mock(name="redis-client-mock")
self.mapper = Redis2DbMapper(self.redis, self.db)
def te... |
#!/usr/bin/env python
"""
Objects shared by all the test cases
"""
import os
import glob
import unittest
import numpy as np
class BaseTestCase(unittest.TestCase):
"""
Superclass for all neukrill-net test cases
"""
@classmethod
def setUpClass(self):
self.test_dir = os.path.join('neu... |
"""Views a trace as an annotated request dependency graph."""
import dependency_graph
import request_dependencies_lens
class RequestNode(dependency_graph.RequestNode):
"""Represents a request in the graph.
is_ad and is_tracking are set according to the ContentClassificationLens
passed to LoadingGraphView.
"... |
import unittest
import numpy as np
import six
import chainer
from chainer import testing
from chainer_tests.dataset_tests.tabular_tests import dummy_dataset
def _filter_params(params):
for param in params:
key_size = 0
key_size += 3 if param['mode_a'] else 1
key_size += 2 if param['mode_... |
from openerp.osv import fields
from openerp.osv import osv
from openerp.tools.translate import _
class account_analytic_line(osv.osv):
_inherit = 'account.analytic.line'
_description = 'Analytic Line'
_columns = {
'product_uom_id': fields.many2one('product.uom', 'Unit of Measure'),
'product... |
import datetime
class _dummy_(object):
def __init__(self, *args, **kw):
pass
class state_machine(_dummy_): pass
class state(_dummy_): pass
class ANY(_dummy_):
def __sub__(self, other):
pass
class SAME(_dummy_): pass
class failure(_dummy_): pass
class Vehicle(object):
@state_machine
... |
from typing import TYPE_CHECKING
import warnings
from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error
from azure.core.paging import ItemPaged
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import HttpR... |
from pprint import pprint
from config_loader import try_load_from_file
from hpOneView.oneview_client import OneViewClient
config = {
"ip": "172.16.102.59",
"credentials": {
"userName": "administrator",
"password": ""
}
}
# To run this sample you must define the uri for an enclosure
enclos... |
# -*- coding: utf-8 -*-
from scrapy.selector import Selector
import scrapy
from scrapy.contrib.loader import ItemLoader
from fun.items import CoserItem
class CoserSpider(scrapy.Spider):
name = "coser"
allowed_domains = ["bcy.net"]
start_urls = (
'http://bcy.net/cn125101',
'http://bcy.net/c... |
import os
import utils.mvc as mvc
import wx
wildcard = "Text Files (*.txt)|*.text|" \
"All files (*.*)|*.*"
def CheckModified(self, save=True):
if self.m_textCtrlText.IsModified():
answer = wx.MessageBox(
'Text has been edited. Do you want to save it?',
'Text Modified',
... |
#!/usr/bin/env python
'''
avl2qml - module for converting ArcView 3.x Legends (.avl) to QGIS styles (.qml)
'''
import argparse
import xml.etree.ElementTree as ET
import os
import re
import pyodb
def avl2qml(data, shapefile=None, field_name=None):
# parse avl
odb = pyodb.ODB(data)
legend = odb.objects[1]... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.contrib.auth.admin import UserAdmin
from django.utils.html import format_html
from django.utils.translation import ugettext_lazy as _
class CustomerAdmin(UserAdmin):
fieldsets = (
(None, {'fields': ('username', 'password')}),
... |
"""Unit test for Zookeeper helper - testing zk connection and leader election.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import os
import unittest
import kazoo
import kazoo.client
import mock
import treadm... |
from opus_core.variables.variable import Variable
from biocomplexity.land_cover.variable_functions import my_attribute_label
from numpy import arcsin, sqrt, float32, not_equal, logical_not, zeros, logical_or, int32
from scipy.ndimage import correlate
from numpy import ma
class pSSS(Variable):
""" Percent co... |
import webapp2
import tusers
from google.appengine.ext import ndb
class InstitutionHandler(webapp2.RequestHandler):
def get(self):
user = tusers.get_current_user()
#Get the requested tournament
tid = self.request.get('t')
t_key = ndb.Key('Tournament', int(tid))
t = t_key.get()
if (user and user.key ... |
import argparse
import time
from flask import Flask
from src.pin import OutputPin
if __name__ == "__main__":
parser = argparse.ArgumentParser(description='Controls an AC System')
parser.add_argument("-p", "--port", type=int, help="the port to run server on", default=5003)
parser.add_argument("-a", "--AC_p... |
# -*- coding: utf-8 -*-
"""
Plot `\\log_2` of square Gram-Schmidt norms during a BKZ run.
EXAMPLE::
>>> from fpylll import IntegerMatrix, BKZ, FPLLL
>>> from fpylll.algorithms.bkz2 import BKZReduction as BKZ2
>>> from fpylll.tools.bkz_plot import KeepGSOBKZFactory
>>> FPLLL.set_random_seed(1337)
>... |
class UDPStream(object):
def __init__(self, socket, in_ioloop=None):
self.socket = socket
self._state = None
self._read_callback = None
self.ioloop = in_ioloop or IOLoop.instance()
def _add_io_state(self, state):
if self._state is None:
self._state =... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.