content stringlengths 4 20k |
|---|
"""Various utility classes and functions."""
import codecs
from datetime import timedelta, tzinfo
import os
import re
try:
set
except NameError:
from sets import Set as set
import textwrap
import time
from itertools import izip, imap
missing = object()
__all__ = ['distinct', 'pathmatch', 'relpath', 'wraptext'... |
"""Tests for confusion_matrix_ops."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import errors_impl
... |
from gvsig import *
import os
import rlib
reload(rlib)
def console(msg,otype=0):
print msg,
def main(*args):
R = rlib.getREngine(console)
layer = os.path.join(str(script.getResource("data")), "contorno.shp")
R.setwd(R.getLayerPath(script.getResource("data")))
R.source( R.getLayerPath(script.getResource("da... |
import logging, time
from autotest.client.shared import error
def run_linux_s3(test, params, env):
"""
Suspend a guest Linux OS to memory.
@param test: kvm test object.
@param params: Dictionary with test parameters.
@param env: Dictionary with the test environment.
"""
vm = env.get_vm(pa... |
#!/usr/bin/env python
# encoding: utf-8
# Thomas Nagy, 2006 (ita)
"TeX/LaTeX/PDFLaTeX support"
import os, re
import Utils, TaskGen, Task, Runner, Build
from TaskGen import feature, before
from Logs import error, warn, debug
re_tex = re.compile(r'\\(?P<type>include|input|import|bringin|lstinputlisting){(?P<file>[^{}]... |
"""Doctest for method/function calls.
We're going the use these types for extra testing
>>> from collections import UserList
>>> from collections import UserDict
We're defining four helper functions
>>> def e(a,b):
... print(a, b)
>>> def f(*a, **k):
... print(a, support.sortdict(k)... |
import os
import random
from gallium import *
from base import *
def lods(*dims):
size = max(dims)
lods = 0
while size:
lods += 1
size >>= 1
return lods
class TextureTest(TestCase):
tags = (
'target',
'format',
'width',
'height',
'dep... |
import os
import json
import threading
import time
from django.http import JsonResponse
from datetime import datetime,timedelta
import OmniDB_app.include.OmniDatabase as OmniDatabase
global_object = {}
to_be_removed = []
def cleanup_thread():
while True:
v_remove_index = len(to_be_removed)-1
try:... |
import unittest, time, sys, random, math, getpass
sys.path.extend(['.','..','../..','py'])
import h2o, h2o_cmd, h2o_import as h2i, h2o_util, h2o_print as h2p
import h2o_summ, h2o_browse as h2b, h2o_util
print "Like test_summary_uniform, but with integers only"
DO_MEDIAN = False
MAX_QBINS = 1
MAX_QBINS = 1000000
DO_RE... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import numpy
def event_detection(feature_data, model_container, hop_length_seconds=0.01, smoothing_window_length_seconds=1.0,
decision_threshold=0.0, minimum_event_length=0.1, minimum_event_gap=0.1):
"""Sound event detection
Parameters
--... |
from __future__ import absolute_import
from __future__ import unicode_literals
from docker import errors
from docker.utils import version_lt
from pytest import skip
from .. import unittest
from compose.cli.docker_client import docker_client
from compose.config.config import ServiceLoader
from compose.const import LAB... |
"""
Groups together code used for creating a NuPIC model and dealing with IO.
"""
import importlib
import csv
import os
from nupic.data.inference_shifter import InferenceShifter
from nupic.frameworks.opf.model_factory import ModelFactory
import nupic_anomaly_output
from settings import METRICS, PATIENT_IDS,... |
"""
VerticalBlock - an XBlock which renders its children in a column.
"""
import logging
from copy import copy
from lxml import etree
from xblock.core import XBlock
from xblock.fragment import Fragment
from xmodule.mako_module import MakoTemplateBlockBase
from xmodule.progress import Progress
from xmodule.seq_module im... |
"""Tests for HTMLExporter"""
# Copyright (c) IPython Development Team.
# Distributed under the terms of the Modified BSD License.
from .base import ExportersTestsBase
from ..html import HTMLExporter
from IPython.nbformat import v4
import re
class TestHTMLExporter(ExportersTestsBase):
"""Tests for HTMLExporter""... |
data = (
'Lun ', # 0x00
'Kua ', # 0x01
'Ling ', # 0x02
'Bei ', # 0x03
'Lu ', # 0x04
'Li ', # 0x05
'Qiang ', # 0x06
'Pou ', # 0x07
'Juan ', # 0x08
'Min ', # 0x09
'Zui ', # 0x0a
'Peng ', # 0x0b
'An ', # 0x0c
'Pi ', # 0x0d
'Xian ', # 0x0e
'Ya ', # 0x0f
'Zhui ', # 0x10
'Le... |
from __future__ import absolute_import, division, print_function
from .common import Benchmark
import numpy as np
class Bincount(Benchmark):
def setup(self):
self.d = np.arange(80000, dtype=np.intp)
self.e = self.d.astype(np.float64)
def time_bincount(self):
np.bincount(self.d)
... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
from tensorflow.contrib.solvers.python.ops import lanczos
from tensorflow.contrib.solvers.python.ops import util
from tensorflow.python.framework import constant_op
from tensorflow.python.op... |
from openpyxl.descriptors.serialisable import Serialisable
from openpyxl.descriptors import (
Alias,
Typed,
Sequence
)
from openpyxl.descriptors.sequence import NestedSequence
from openpyxl.descriptors.excel import ExtensionList
from openpyxl.utils.indexed_list import IndexedList
from openpyxl.xml.constants... |
from .error import *
from .tokens import *
from .events import *
from .nodes import *
from .loader import *
from .dumper import *
__version__ = '3.10'
try:
from .cyaml import *
__with_libyaml__ = True
except ImportError:
__with_libyaml__ = False
import io
def scan(stream, Loader=Loader):
"""
Sc... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
'''
Generate Gcode for Lissajous Curve
Future ref will generate Gcode for other curves
Test range : [1,1 + np.pi,0.1]
Test delta : 0
'''
import numpy as np
import argparse
try:
import matplotlib.pyplot as plt
except ImportError:
pass
def lissajous(a,b,rng,delta=None):... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
try:
from collections import Counter
HAS_COLLECTIONS_COUNTER = True
except ImportEr... |
import subprocess
import sys
import os
import setup_util
def start(args, logfile, errfile):
setup_util.replace_text("activeweb/src/main/webapp/WEB-INF/resin-web.xml", "localhost", args.database_host)
setup_util.replace_text("activeweb/src/main/java/app/config/DbConfig.java", "localhost", args.database_host)
try... |
import argparse
import sys
from osgeo import ogr
from osgeo import osr
import json
import shapely.geometry
import codecs
class Map:
def __init__(self, name, language):
self.paths = {}
self.name = name
self.language = language
self.width = 0
self.heoght = 0
self.bbox = []
def addPath(self, ... |
import numpy as np
import sqlite3
from sqlite3 import IntegrityError
class FingerprintDB():
"""A class for accessing a temporary SQLite database. This
function works as a context manager and should be used as follows:
with FingerprintDB() as fpdb:
(Perform operation here)
This syntax will au... |
from uber.common import *
# TODO: DOM: this whole thing needs a major overhaul, it's a nightmare
# this spits out data in the wrong format needed for the javascript,
# and the javascript does a ton of unneeded processing to work around it.
# imports the actual hardcoded graph data for previous magfest years
# (yes, i... |
from __future__ import division, absolute_import, print_function
import os
from .. import _DATA_STORE_AVAILABLE, IOHUB_DIRECTORY
from . import ioHubConnection
from ..util import yload, yLoader, readConfig
def launchHubServer(**kwargs):
"""
Starts the ioHub Server subprocess, and return a
:class:`psycho... |
"""Helper functions for creating partitioned variables.
This is a convenient abstraction to partition a large variable across
multiple smaller variables that can be assigned to different devices.
The full variable can be reconstructed by concatenating the smaller variables.
Using partitioned variables instead of a si... |
import unittest2 as unittest
from webkitpy.common.system.outputcapture import OutputCapture
from webkitpy.tool.mocktool import MockOptions, MockTool
from webkitpy.tool.steps.updatechangelogswithreviewer import UpdateChangeLogsWithReviewer
class UpdateChangeLogsWithReviewerTest(unittest.TestCase):
def test_guess_r... |
"""
Support for Rain Bird Irrigation system LNK WiFi Module.
For more details about this component, please refer to the documentation at
https://home-assistant.io/components/rainbird/
"""
import logging
import voluptuous as vol
import homeassistant.helpers.config_validation as cv
from homeassistant.const import (CON... |
import re
import string
import itertools
NORMALISATIONS = reversed(sorted([
('road', 'rd'),
('avenue', 'ave'),
('street', 'st'),
('place', 'pl'),
('estate', 'est'),
('pk', 'park'),
('sq', 'square'),
('stn', 'station'),
('cres', 'crescent'),
('cen', 'centre'),
('sth', 'south'... |
from gi.repository import Gtk
#-------------------------------------------------------------------------
#
# NoteModel
#
#-------------------------------------------------------------------------
class NoteModel(Gtk.ListStore):
def __init__(self, note_list, db):
Gtk.ListStore.__init__(self, str, str, bool... |
import asm3.configuration
import asm3.i18n
import asm3.lostfound
from .base import FTPPublisher
from asm3.sitedefs import HELPINGLOSTPETS_FTP_HOST
import os
import sys
class HelpingLostPetsPublisher(FTPPublisher):
"""
Handles publishing to helpinglostpets.com
"""
def __init__(self, dbo, publishCriter... |
class Operation(object):
"""Defines a series of operations which shall be executed in order.
the operations expected are procedures, return values are discarded
"""
def __init__(self, procedure, args=(), kwargs={}, nextop=None):
self._procedure = procedure
self.args = args[:]
... |
from setuptools import setup, find_packages
import codecs
README = codecs.open("README.rst", encoding="utf-8").read()
setup(
name="splinter",
version="0.9.0",
url="https://github.com/cobrateam/splinter",
description="browser abstraction for web acceptance testing",
long_description=README,
au... |
"""Pull in statistics for sites."""
# pylint: disable=C0301
from apiary.tasks import BaseApiaryTask
import logging
import requests
import datetime
import re
LOGGER = logging.getLogger()
class GetStatisticsTask(BaseApiaryTask):
"""Collect statistics on usage from site."""
def run(self, site_id, site, method... |
from nose2 import events, loader, session
from nose2.tests._common import TestCase
class TestPluggableTestLoader(TestCase):
def setUp(self):
self.session = session.Session()
self.loader = loader.PluggableTestLoader(self.session)
def test_load_from_module_calls_hook(self):
self.sessio... |
"""
Views for managing keypairs.
"""
from django.core.urlresolvers import reverse
from django.core.urlresolvers import reverse_lazy
from django import http
from django.template.defaultfilters import slugify # noqa
from django.utils.translation import ugettext_lazy as _
from django.views.generic import View # noqa
fr... |
from distutils.command.build_ext import build_ext as _du_build_ext
try:
# Attempt to use Pyrex for building extensions, if available
from Pyrex.Distutils.build_ext import build_ext as _build_ext
except ImportError:
_build_ext = _du_build_ext
import os, sys
from distutils.file_util import copy_file
from set... |
from openerp.osv import osv
"""Inherit res.currency to handle accounting date values when converting currencies"""
class res_currency_account(osv.osv):
_inherit = "res.currency"
def _get_conversion_rate(self, cr, uid, from_currency, to_currency, context=None):
if context is None:
context ... |
#!/usr/bin/env python
'''
nsot
====
Ansible Dynamic Inventory to pull hosts from NSoT, a flexible CMDB by Dropbox
Features
--------
* Define host groups in form of NSoT device attribute criteria
* All parameters defined by the spec as of 2015-09-05 are supported.
+ ``--list``: Returns JSON hash of host groups -... |
"""
Simplistic HTTP proxy support.
This comes in two main variants - the Proxy and the ReverseProxy.
When a Proxy is in use, a browser trying to connect to a server (say,
www.yahoo.com) will be intercepted by the Proxy, and the proxy will covertly
connect to the server, and return the result.
When a ReverseProxy is ... |
# -*- coding: utf-8 -*-
"""
pygments.styles.friendly
~~~~~~~~~~~~~~~~~~~~~~~~
A modern style based on the VIM pyte theme.
:copyright: Copyright 2006-2017 by the Pygments team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
from pygments.style import Style
from pygments.token import Keyw... |
import unittest
from functools import wraps
from django.conf import settings
from django.db import DEFAULT_DB_ALIAS, connection
def skipUnlessGISLookup(*gis_lookups):
"""
Skip a test unless a database supports all of gis_lookups.
"""
def decorator(test_func):
@wraps(test_func)
def ski... |
"""Fake LDAP server for test harness.
This class does very little error checking, and knows nothing about ldap
class definitions. It implements the minimum emulation of the python ldap
library to work with compute.
"""
import fnmatch
from oslo_serialization import jsonutils
import six
from six.moves import range
... |
"""Tests for api.ec2.admin"""
import datetime
from nova import context
from nova import db
from nova import exception
from nova import flags
from nova import test
from nova import utils
from nova.api.ec2 import admin
from nova.api.ec2 import ec2utils
from nova.cloudpipe import pipelib
from nova.compute import vm_stat... |
"""
=============================================================================
Various Agglomerative Clustering on a 2D embedding of digits
=============================================================================
An illustration of various linkage option for agglomerative clustering on
a 2D embedding of the di... |
import logging
import os
import threading
import time
from fs.osfs import OSFS
from smartfile.errors import RequestError, ResponseError
import common
from definitions import FileDefinition, LocalDefinitionHelper
from errors import FileNotAvailableError, FileDeletedError, MaxTriesError
from errors import UploadError
f... |
import logging
from oslo.utils import timeutils
import six.moves.urllib.parse as urlparse
import swiftclient
from django.conf import settings
from django.utils.translation import ugettext_lazy as _
from horizon import exceptions
from horizon.utils.memoized import memoized # noqa
from openstack_dashboard.api import... |
import hashlib
import itertools
import logging
import os
import re
from openerp import tools
from openerp.tools.translate import _
from openerp.exceptions import AccessError
from openerp.osv import fields,osv
from openerp import SUPERUSER_ID
from openerp.osv.orm import except_orm
from openerp.tools.translate import _
... |
ANSIBLE_METADATA = {'status': ['preview'],
'supported_by': 'core',
'version': '1.0'}
EXAMPLES = r"""
# Before 2.3, option 'dest', 'destfile' or 'name' was used instead of 'path'
- lineinfile:
path: /etc/selinux/config
regexp: '^SELINUX='
line: 'SELINUX=enforcing'
- ... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
ANSIBLE_METADATA = {
'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'certified'
}
from ansible.module_utils.network.nso.nso import connect, verify_version, nso_argument_spec
from ansible.module_utils... |
"""
Tables Extension for Python-Markdown
====================================
Added parsing of tables to Python-Markdown.
See <https://pythonhosted.org/Markdown/extensions/tables.html>
for documentation.
Original code Copyright 2009 [Waylan Limberg](http://achinghead.com)
All changes Copyright 2008-2014 The Python ... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
import pytest
from ansible.module_utils.facts.system.cmdline import CmdLineFactCollector
test_data = [
(
"crashkernel=auto rd.lvm.lv=fedora_test-elementary-os/root rd.lvm.lv=fedora_test-elementary-os/swap rhgb quiet",
... |
# -*- Mode: python; py-indent-offset: 4; indent-tabs-mode: nil; coding: utf-8; -*-
# Based on http://doughellmann.com/2010/05/09/defining-custom-roles-in-sphinx.html
"""Integration of Sphinx with Redmine.
"""
from docutils import nodes, utils
from docutils.parsers.rst.roles import set_classes
def redmine_role(name, ... |
#!/usr/bin/env python
# This example demonstrates how to use a constraint polygon in
# Delaunay triangulation.
import vtk
from vtk.util.colors import peacock
# Generate the input points and constrained edges/polygons.
points = vtk.vtkPoints()
points.InsertPoint(0, 1, 4, 0)
points.InsertPoint(1, 3, 4, 0)
points.Inser... |
from binascii import hexlify, unhexlify
from hashlib import md5, sha1
from ..exceptions import SSLError
try: # Test for SSL features
SSLContext = None
HAS_SNI = False
import ssl
from ssl import wrap_socket, CERT_NONE, PROTOCOL_SSLv23
from ssl import SSLContext # Modern SSL?
from ssl import... |
"""Modules for attending over memory."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import collections
# Dependency imports
import numpy as np
from sonnet.python.modules import base
from sonnet.python.modules import basic
import tensorflow as tf
# ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Run an EPD test suite with an UCI engine."""
from __future__ import print_function
import chess
import chess.uci
import chess.variant
import time
import argparse
import itertools
import logging
import sys
def test_epd(engine, epd, VariantBoard, movetime):
positi... |
from rest_framework import serializers
from django.contrib import auth
from courses.models import *
class OfferingSerializer(serializers.HyperlinkedModelSerializer):
course_set = serializers.HyperlinkedRelatedField(many=True, read_only=True, view_name='courses:api:course-payment-detail')
period = serializer... |
import sys
from argparse import ArgumentParser
from typing import Any, Dict, List
from django.conf import settings
from django.core.management.base import CommandError
from zerver.lib.management import ZulipBaseCommand
from zerver.lib.soft_deactivation import (
do_auto_soft_deactivate_users,
do_soft_activate_... |
#coding:utf8
from baseclass.DeepRecommender import DeepRecommender
import numpy as np
from random import choice,random,randint,shuffle
from tool import config
import tensorflow as tf
#According to the paper, we only
class DMF(DeepRecommender):
def __init__(self,conf,trainingSet=None,testSet=None,fold='[1]'):
... |
import unittest
from coala_utils.ContextManagers import retrieve_stdout
from coalib.results.Result import Result
from coalib.results.result_actions.PrintMoreInfoAction import (
PrintMoreInfoAction)
from coalib.settings.Section import Section
class PrintMoreInfoActionTest(unittest.TestCase):
def setUp(self):... |
# coding=utf-8
from emft.config import Config
from emft.core.logging import make_logger
from emft.gui.base import Checkbox, GroupBox, HLayout, HSpacer, Label, PushButton, Radio, VLayout
from emft.gui.main_ui_tab_widget import MainUiTabChild
from emft.plugins.reorder.adapter.tab_reorder_adapter import TAB_NAME, TabReor... |
from io import StringIO
from antlr4.PredictionContext import PredictionContext, merge
from antlr4.Utils import str_list
from antlr4.atn.ATN import ATN
from antlr4.atn.ATNConfig import ATNConfig
from antlr4.atn.SemanticContext import SemanticContext
from antlr4.error.Errors import UnsupportedOperationException, IllegalS... |
__author__ = 'corona'
import sqlite3
try:
import cPickle as pickle
except ImportError:
import pickle
def inject_cookies_into_chrome(session, chrome_cookie_file):
conn = sqlite3.connect(chrome_cookie_file)
cookies = {}
cookies_list = []
#fh = xbmcvfs.File(session_file, 'rb')
# fh = open(s... |
import os
# Django settings for geonition project.
# If you set this to False, Django will make some optimizations so as not
# to load the internationalization machinery.
USE_I18N = True
# If you set this to False, Django will not format dates, numbers and
# calendars according to the current locale.
USE_L10N = True... |
from lib.common import helpers
class Module:
def __init__(self, mainMenu, params=[]):
self.info = {
'Name': 'Invoke-DisableMachineAcctChange',
'Author': ['@harmj0y'],
'Description': ('Disables the machine account for the target system '
'f... |
"""Implementation of JSONDecoder
"""
import re
from json import scanner
try:
from _json import scanstring as c_scanstring
except ImportError:
c_scanstring = None
__all__ = ['JSONDecoder']
FLAGS = re.VERBOSE | re.MULTILINE | re.DOTALL
NaN = float('nan')
PosInf = float('inf')
NegInf = float('-inf')
def line... |
# -*- coding: utf-8 -*-
"""
jinja2.testsuite.inheritance
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Tests the template inheritance feature.
:copyright: (c) 2010 by the Jinja Team.
:license: BSD, see LICENSE for more details.
"""
import unittest
from jinja2.testsuite import JinjaTestCase
from jinja2 import Env... |
import sys, autotest_data, autotest_runner
def usage():
print"Usage: autotest.py [test app|test iso image]",
print "[target] [whitelist|-blacklist]"
if len(sys.argv) < 3:
usage()
sys.exit(1)
target = sys.argv[2]
test_whitelist=None
test_blacklist=None
# get blacklist/whitelist
if len(sys.argv) > 3:
testlist... |
# Tests of the full ZIP64 functionality of zipfile
# The support.requires call is the only reason for keeping this separate
# from test_zipfile
from test import support
# XXX(nnorwitz): disable this test by looking for extra largfile resource
# which doesn't exist. This test takes over 30 minutes to run in general
# ... |
from nutils import *
from nutils.testing import *
@parametrize
class check(TestCase):
def setUp(self):
super().setUp()
if not self.curved:
self.domain, self.geom = mesh.rectilinear([[1,1.5,2],[-1,0],[0,2,4]][:self.ndims])
self.curv = 0
else:
assert self.ndims == 2
nodes = numpy.l... |
from sendgmail import sendgmail
from time import sleep
import os.path
def main():
shutdown = 0
error_dir_txt = "../static/log/impossible_error.txt"
setting_dir_txt = "../setting.txt"
file_pointer = ""
file_pointer2 = ""
last_line_count = 0
small_bug = 1
middle_bug = 5
big_bug = 10
#check file exist
if not... |
"""
Call Stack Manager deals with tracking call stacks of functions/methods/classes(Django Model Classes)
Call Stack Manager logs unique call stacks. The call stacks then can be retrieved via Splunk, or log reads.
classes:
CallStackManager - stores all stacks in global dictionary and logs
CallStackMixin - used for Mo... |
from ipalib import api
from ipalib import Bool, Int, Str, IA5Str, StrEnum, DNParam
from ipalib.plugable import Registry
from ipalib.plugins.baseldap import *
from ipalib.plugins.selinuxusermap import validate_selinuxuser
from ipalib import _
from ipalib.errors import ValidationError
# 389-ds attributes that should be ... |
#!/usr/bin/python
from __future__ import (absolute_import, division, print_function)
# Copyright 2019 Fortinet, Inc.
#
# 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 Lic... |
class ModuleDocFragment(object):
DOCUMENTATION = r'''
options:
api_version:
description:
- Use to specify the API version. Use to create, delete, or discover an object without providing a full
resource definition. Use in conjunction with I(kind), I(name), and I(namespace) to identify a
specif... |
from __future__ import unicode_literals
from StringIO import StringIO
import os
import unittest
from mach.main import Mach
from mach.base import CommandContext
here = os.path.abspath(os.path.dirname(__file__))
class TestBase(unittest.TestCase):
provider_dir = os.path.join(here, 'providers')
def _run_mach(s... |
microcode = '''
# MOVNTQ
def macroop MASKMOVQ_MMX_MMX {
ldfp ufp1, ds, [1, t0, rdi], dataSize=8
maskmov ufp1, mmx, mmxm, size=1
stfp ufp1, ds, [1, t0, rdi], dataSize=8
};
''' |
ANSIBLE_METADATA = {'status': ['preview'],
'supported_by': 'community',
'version': '1.0'}
try:
from libcloud.compute.types import Provider
from libcloud.compute.providers import get_driver
from libcloud.common.google import GoogleBaseError, QuotaExceededError, \
... |
"""
Tests for BlockCountsTransformer.
"""
# pylint: disable=protected-access
from openedx.core.lib.block_structure.factory import BlockStructureFactory
from xmodule.modulestore.tests.django_utils import ModuleStoreTestCase
from xmodule.modulestore.tests.factories import SampleCourseFactory
from ..block_counts import ... |
from src.base.solution import Solution
from src.tests.part1.q347_test_top_k_frequent_elements import TopKFreqElemTestCases
"""
https://leetcode.com/problems/top-k-frequent-elements/#/description
Given a non-empty array of integers, return the k most frequent elements.
For example,
Given [1,1,1,2,2,3] and k = 2, ret... |
# Test case for the os.poll() function
import os
import subprocess
import random
import select
try:
import threading
except ImportError:
threading = None
import time
import unittest
from test.support import TESTFN, run_unittest, reap_threads, cpython_only
try:
select.poll
except AttributeError:
raise ... |
"""A module for the run command."""
import cr
class RunCommand(cr.Command):
"""The implementation of the run command.
This first uses Builder to bring the target up to date.
It then uses Installer to install the target (if needed), and
finally it uses Runner to run the target.
You can use skip version to ... |
"""Unit tests for the :data:`iris.analysis.MAX` aggregator."""
from __future__ import (absolute_import, division, print_function)
from six.moves import (filter, input, map, range, zip) # noqa
# Import iris.tests first so that some things can be initialised before
# importing anything else.
import iris.tests as tests... |
import os
import sys
import imp
from zipimport import zipimporter
from django.utils import unittest
from django.utils.importlib import import_module
from django.utils.module_loading import module_has_submodule
class DefaultLoader(unittest.TestCase):
def setUp(self):
sys.meta_path.insert(0, ProxyFinder())... |
class ModuleDocFragment(object):
# Standard Pure Storage documentation fragment
DOCUMENTATION = '''
options:
- See separate platform section for more details
requirements:
- See separate platform section for more details
notes:
- Ansible modules are available for the following Pure Storage products: Flas... |
import platform
from spack.architecture import Platform, Target
from spack.operating_systems.mac_os import MacOs
class Darwin(Platform):
priority = 89
front_end = 'x86_64'
back_end = 'x86_64'
default = 'x86_64'
def __init__(self):
super(Darwin, self).__init__('darwin')
... |
ANSIBLE_METADATA = {'status': ['preview'],
'supported_by': 'community',
'version': '1.0'}
# ===========================================
# Stackdriver module specific support methods.
#
try:
import json
except ImportError:
try:
import simplejson as json
excep... |
from django.core.exceptions import ImproperlyConfigured
from django.core.management.base import BaseCommand, CommandError
from django.core import serializers
from django.db import connections, router, DEFAULT_DB_ALIAS
from django.utils.datastructures import SortedDict
from optparse import make_option
class Command(Ba... |
"Thread-safe in-memory cache backend."
from __future__ import with_statement
import time
try:
import cPickle as pickle
except ImportError:
import pickle
from django.core.cache.backends.base import BaseCache
from django.utils.synch import RWLock
# Global in-memory store of cache data. Keyed by name, to provi... |
from django.conf import settings
from django.contrib.sites.models import Site, RequestSite, get_current_site
from django.core.exceptions import ObjectDoesNotExist
from django.http import HttpRequest
from django.test import TestCase
class SitesFrameworkTests(TestCase):
def setUp(self):
Site(id=settings.SI... |
def write_fstab(lines, dest):
fs_w = open(dest, 'w')
for l in lines:
fs_w.write(l)
fs_w.flush()
fs_w.close()
def _escape_fstab(v):
""" escape space (040), ampersand (046) and backslash (134) which are invalid in fstab fields """
if isinstance(v, int):
return v
else:
... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
from units.compat.mock import patch
from ansible.modules.network.onyx import onyx_vlan
from units.modules.utils import set_module_args
from .onyx_module import TestOnyxModule, load_fixture
class TestOnyxVlanModule(TestOnyxModule)... |
import os
import re
import urllib2
import json
from scriptCommon import catchPath
from scriptCommon import runAndCapture
issueNumberRe = re.compile( r'(.*?)#([0-9]*)([^0-9]?.*)' )
rootPath = os.path.join( catchPath, 'include/' )
versionPath = os.path.join( rootPath, "internal/catch_version.hpp" )
hashes = runAndCa... |
import unittest
import tempfile
import os
import logging
from lxml import etree
from redi import redi
class TestSortElementTree(unittest.TestCase):
def setUp(self):
redi.configure_logging('.')
#redi.logger.setLevel(logging.DEBUG)
# un-sorted XML file
self.unsorted = """<?xml vers... |
#Tic Tac Toe
import random
def drawBoard(board):
#this function prints out the board it was passed
#"board" is a list of 10 strings representing the board (ignore index 0)
print(' | |')
print(' ' + board[7] + ' | ' + board[8] + ' | ' + board[9])
print(' | |')
print('-----------')
... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import os
import sys
import six
import webtest
from webtest.debugapp import debug_app
from webtest.compat import PY3
from webtest.compat import to_bytes
from webtest.compat import print_stderr
from webtest.app import AppError
from tests.compat import unitt... |
__author__ = 'Frank Sehnke, <EMAIL>'
from pybrain.rl.environments import EpisodicTask
from pybrain.rl.environments.ode.sensors import SpecificBodyPositionSensor
from scipy import tanh, zeros, array, random, sqrt, asarray
#Basic class for all ccrl tasks
class CCRLTask(EpisodicTask):
def __init__(self, env):
... |
from types import SimpleNamespace
from typing import Type, Generic, Any, TypeVar, Callable, Tuple, _GenericAlias, get_type_hints
import inspect
from amino.util.string import snake_case
from amino import ADT, Map, List, Lists, do, Do, Either, Try, Just, Nothing, Maybe
from amino.algebra import Algebra
from amino.loggin... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.