content string |
|---|
# -*- coding: utf-8 -*-
"""
***************************************************************************
validitycheck.py
---------------------
Date : January 2019
Copyright : (C) 2019 by Nyall Dawson
Email : nyall dot dawson at gmail dot com
***************... |
import argparse
import os
import libcst as cst
import pathlib
import sys
from typing import (Any, Callable, Dict, List, Sequence, Tuple)
def partition(
predicate: Callable[[Any], bool],
iterator: Sequence[Any]
) -> Tuple[List[Any], List[Any]]:
"""A stable, out-of-place partition."""
results = ([], [])... |
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'network'}
import re
from ansible.module_utils.network.nxos.nxos import get_config, load_config, run_commands
from ansible.module_utils.network.nxos.nxos import nxos_argument_spec, check_args... |
from django.contrib.sessions.backends.base import SessionBase, CreateError
from django.core.cache import cache
KEY_PREFIX = "django.contrib.sessions.cache"
class SessionStore(SessionBase):
"""
A cache-based session store.
"""
def __init__(self, session_key=None):
self._cache = cache
s... |
import numpy as np
import pandas as pd
from xray.core import ops, utils
from xray.core.pycompat import OrderedDict
from . import TestCase
class TestSafeCastToIndex(TestCase):
def test(self):
dates = pd.date_range('2000-01-01', periods=10)
x = np.arange(5)
td = x * np.timedelta64(1, 'D')
... |
import copy
from nova.api.validation import parameter_types
create = {
'type': 'object',
'properties': {
'volume': {
'type': 'object',
'properties': {
'volume_type': {'type': 'string'},
'metadata': {'type': 'object'},
'snapshot_id... |
import unittest
import frappe
from frappe.utils import today
from erpnext.hr.doctype.employee.employee import make_salary_structure
from erpnext.hr.doctype.salary_structure.salary_structure import make_salary_slip
class TestSalarySlip(unittest.TestCase):
def setUp(self):
frappe.db.sql("""delete from `tabLeave Appli... |
#!/usr/bin/python
import h5py
import sys
import numpy as np
import os
import re
import random
# find the path to my own python function:
cur_dir=os.getcwd()
sep='test_cases'
test_DIR=cur_dir.split(sep,1)[0]
scriptDIR=test_DIR+'compare_function'
sys.path.append(scriptDIR)
# import my own function for color and comparat... |
# this is a virtual module that is entirely implemented server side |
"""
Testing signals emitted on changing m2m relations.
"""
from django.db import models
from django.test import TestCase
from .models import Car, Part, Person, SportsCar
class ManyToManySignalsTest(TestCase):
def m2m_changed_signal_receiver(self, signal, sender, **kwargs):
message = {
'insta... |
# coding: utf-8
# BlackSmith mark.2
# exp_name = "muc" # /code.py v.x9
# Id: 05~5c
# Code © (2009-2012) by WitcherGeralt [<EMAIL>]
class expansion_temp(expansion):
def __init__(self, name):
expansion.__init__(self, name)
def command_subject(self, stype, source, body, disp):
if Chats.has_key(source[1]):
... |
#-*-coding:utf-8-*-
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
from numpy import *
def loadDataSet():
dataMat = []; labelMat = []
fr = open('testSet.txt')
for line in fr.readlines():
lineArr = line.strip().split()
dataMat.append([1.0,float(lineArr[0]),float(lineArr[1])])
... |
# -*- coding: utf-8 -*-
"""
werkzeug.contrib.fixers
~~~~~~~~~~~~~~~~~~~~~~~
.. versionadded:: 0.5
This module includes various helpers that fix bugs in web servers. They may
be necessary for some versions of a buggy web server but not others. We try
to stay updated with the status of the bug... |
from abc import ABCMeta, abstractmethod
from difflib import SequenceMatcher
import inspect
import os
import re
import sys
import style
import sort_includes
from region import *
from file_types import lang_type
def safefix(fix_func):
""" Decorator for the fix functions of the Verifier class.
This function... |
"""Class representing message/* MIME documents."""
__all__ = ['MIMEMessage']
from email import message
from email.mime.nonmultipart import MIMENonMultipart
class MIMEMessage(MIMENonMultipart):
"""Class representing message/* MIME documents."""
def __init__(self, _msg, _subtype='rfc822'):
"""Creat... |
from hamcrest import ( assert_that,
contains_exactly,
contains_inanyorder,
has_entries,
has_entry )
from pprint import pformat
import json
from ycmd.tests.go import PathToTestFile, SharedYcmd
from ycmd.tests.test_utils import (... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {
'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'
}
DOCUMENTATION = r'''
---
module: meraki_organization
short_description: Manage organizations in the Meraki cloud
versio... |
"""Miscellaneous functions for dealing with sequences."""
import re, time
from Bio import SeqIO
from Bio.Seq import Seq
from Bio import Alphabet
from Bio.Alphabet import IUPAC
from Bio.Data import IUPACData, CodonTable
######################################
# DNA
######################
# {{{
def GC(seq):
"""C... |
# -*- coding: utf-8 -*-
import ipaddress
__all__ = [
'config_to_map',
'get_region'
]
def config_to_map(topology_config):
"""
args:
topology_config: dict
{
'region1': [
'10.1.1.0/24',
'10.1.10.0/24',
'172.1... |
from openerp.osv import fields, osv
import os
from openerp.tools.translate import _
import logging
_logger = logging.getLogger(__name__)
class wizard_multi_charts_accounts(osv.osv_memory):
"""
Change wizard that a new account chart for a company.
* Add option to install languages during the setup
... |
from typing import Tuple
import h2.config
import h2.connection
import h2.events
from mitmproxy.http import HTTPFlow
from mitmproxy.proxy.context import Context
from mitmproxy.proxy.layers.http import HTTPMode
from mitmproxy.proxy.commands import CloseConnection, OpenConnection, SendData
from mitmproxy.connection impo... |
"""These functions are executed via gyp-sun-tool when using the Makefile
generator."""
import fcntl
import os
import struct
import subprocess
import sys
def main(args):
executor = SunTool()
executor.Dispatch(args)
class SunTool(object):
"""This class performs all the SunOS tooling steps. The methods can eith... |
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['stableinterface'],
'supported_by': 'core'}
from ansible.module_utils.basic import AnsibleModule
def main():
module = AnsibleModule(
argument_spec=dict(
data=dict(required=False, default=None),
... |
import json,glob,os
import dicom
outdir='/scratch/01329/poldrack/selftracking/ds031/sub00001/ses105/fieldmap'
washubase='/scratch/01329/poldrack/selftracking/washu'
basedirs=['vc39556','vc39556_2']
fmseries=[[5,10,21],[5,17]]
ctr=1
for i in range(2):
basedir=os.path.join(washubase,basedirs[i])
for j in range(... |
"""
Tests for rose.
"""
import numpy as np
import pytest
from pygmt import Figure
from pygmt.datasets import load_fractures_compilation
@pytest.fixture(scope="module", name="data")
def fixture_data():
"""
Load the sample numpy array data.
"""
return np.array(
[[40, 60], [60, 300], [20, 180], [... |
"""Signature constants for SavedModel save and restore operations.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.python.util.all_util import remove_undocumented
# Key in the signature def map for `default` serving signatures. The def... |
"""
Python implementation of the fast ICA algorithms.
Reference: Tables 8.3 and 8.4 page 196 in the book:
Independent Component Analysis, by Hyvarinen et al.
"""
# Authors: Pierre Lafaye de Micheaux, Stefan van der Walt, Gael Varoquaux,
# Bertrand Thirion, Alexandre Gramfort, Denis A. Engemann
# License: BS... |
ANSIBLE_METADATA = {'metadata_version': '1.0',
'status': ['preview'],
'supported_by': 'community'}
# TODO: Disabled RETURN as it is breaking the build for docs. Needs to be fixed.
import time
#TODO: get this info from API
STATES = ['present', 'absent']
DATACENTERS = ['ams01', ... |
"""mlir_gen: Generate mlir code from python code."""
# pylint: disable=invalid-name
# pylint: disable=missing-function-docstring
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import gast as ast
from tensorflow.python.autograph.pyct import anno
from tenso... |
"""
Utility functions for PyMS wide use
"""
#############################################################################
# #
# PyMS software for processing of metabolomic mass-spectrometry data #
# Copyright (C) 2005-2012 V... |
import datetime
from django.db import models
from django.db.models.fields.related import \
ReverseSingleRelatedObjectDescriptor
from django.utils.encoding import python_2_unicode_compatible
from django.utils.translation import get_language
@python_2_unicode_compatible
class Country(models.Model):
# Table Col... |
"""
French-language mappings for language-dependent features of
reStructuredText.
"""
__docformat__ = 'reStructuredText'
directives = {
u'attention': 'attention',
u'pr\u00E9caution': 'caution',
u'danger': 'danger',
u'erreur': 'error',
u'conseil': 'hint',
u'important': 'important',... |
import platform
import os
from six import BytesIO
def rel_path_to_url(rel_path, url_base="/"):
assert not os.path.isabs(rel_path)
if url_base[0] != "/":
url_base = "/" + url_base
if url_base[-1] != "/":
url_base += "/"
return url_base + rel_path.replace(os.sep, "/")
def from_os_path(... |
import os
import sys
from distutils.core import setup
from distutils.sysconfig import get_python_lib
# Warn if we are installing over top of an existing installation. This can
# cause issues where files that were deleted from a more recent Django are
# still present in site-packages. See #18115.
overlay_warning = Fal... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Simple built-in backend.
"""
__author__ = "Lluís Vilanova <<EMAIL>>"
__copyright__ = "Copyright 2012, Lluís Vilanova <<EMAIL>>"
__license__ = "GPL version 2 or (at your option) any later version"
__maintainer__ = "Stefan Hajnoczi"
__email__ = "<EMAIL>"
... |
#!/usr/bin/env python
# W.J. van der Laan, 2011
# Make spinning .mng animation from a .png
# Requires imagemagick 6.7+
from __future__ import division
from os import path
from PIL import Image
from subprocess import Popen
SRC='img/reload_scaled.png'
DST='../../src/qt/res/movies/update_spinner.mng'
TMPDIR='/tmp'
TMPNAM... |
import web
import logging
#import model
#import markdown
import pymongo
from pymongo.code import Code
import re
from pymongo.objectid import ObjectId
import json
from datetime import datetime
from sets import Set
from collections import defaultdict
logging.basicConfig(level=logging.INFO)
conn = pymongo.Connection()
db... |
# mad.py
# Alf Clement 27-Mar-2014
#
zero=0
three=3
print("1")
print("2")
print(three)
print("{}".format(4))
five=25//5
print(int(five))
j=0
for i in range(4):
j += i
print(j)
print(3+4)
try:
a=4//zero
except:
print(8)
print("xxxxxxxxx".count("x"))
def ten():
return 10
print(ten())
a=[]
for i in range(13):
a.appen... |
"""Crypto utilities."""
import contextlib
import logging
import socket
import sys
from six.moves import range # pylint: disable=import-error,redefined-builtin
import OpenSSL
from acme import errors
logger = logging.getLogger(__name__)
# DVSNI certificate serving and probing is not affected by SSL
# vulnerabiliti... |
import gc
import weakref
import mock
from oslo.config import cfg
from neutron.db import agentschedulers_db
from neutron import manager
from neutron.tests import base
from neutron.tests import fake_notifier
class PluginSetupHelper(object):
"""Mixin for use with testtools.TestCase."""
def cleanup_core_plugin... |
from collections import defaultdict
from openerp.tools import mute_logger
from openerp.tests import common
UID = common.ADMIN_USER_ID
class TestORM(common.TransactionCase):
""" test special behaviors of ORM CRUD functions
TODO: use real Exceptions types instead of Exception """
def setUp(self):... |
import unittest, random, sys, time
sys.path.extend(['.','..','../..','py'])
import h2o, h2o_browse as h2b, h2o_exec as h2e, h2o_import as h2i, h2o_cmd
initList = [
('r', 'r=i.hex'),
]
exprList = [
"a=c(1,2,3); a = r[r[,1]>2,]",
"a=c(1,2,3); a = r[r[,1]>10,]",
]
class Basic(unittest.TestCa... |
"""A utility script to help building Syzygy-instrumented Chrome binaries."""
import glob
import logging
import optparse
import os
import shutil
import subprocess
import sys
# The default directory containing the Syzygy toolchain.
_DEFAULT_SYZYGY_DIR = os.path.abspath(os.path.join(
os.path.dirname(__file__), '../... |
import dataclasses
from typing import ClassVar
@dataclasses.dataclass
class A1:
bar1: int
<error descr="Fields with a default value must come after any fields without a default.">baz1</error>: int = 1
foo1: int
<error descr="Fields with a default value must come after any fields without a default.">ba... |
from django.core.urlresolvers import reverse
from django.utils.translation import ugettext_lazy as _
from django.views import generic
from horizon import exceptions
from horizon import messages
from horizon import tables
from horizon.utils import memoized
from horizon import workflows
from openstack_dashboard import ... |
from zipline.assets import Equity
from zipline.finance.slippage import SlippageModel
from zipline.utils.sentinel import sentinel
class TestingSlippage(SlippageModel):
"""
Slippage model that fills a constant number of shares per tick, for
testing purposes.
Parameters
----------
filled_per_tic... |
from __future__ import with_statement
import os
import sys
import tempfile
import shutil
import subprocess
import rpm
from mic import msger
from mic.utils import errors, proxy, misc
from mic.utils.rpmmisc import readRpmHeader, RPMInstallCallback
from mic.chroot import cleanup_mounts, setup_chrootenv, cleanup_chrootenv
... |
"""This module is for parsing manual pages and extracting necessary information
for creating a metaGUI.
Needed capabilities:
* Retrieve text of a given manpage
* Read manpage for a given program and create a list of command-line options,
with expected parameters and accompanying paragraph(s) of documentation.
"""... |
from openerp.report import report_sxw
from openerp.osv import osv
from openerp.addons.hr_payroll import report
class payslip_details_report_in(report.report_payslip_details.payslip_details_report):
def __init__(self, cr, uid, name, context):
super(payslip_details_report_in, self).__init__(cr, uid, name, c... |
# Django documentation build configuration file, created by
# sphinx-quickstart on Thu Mar 27 09:06:53 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 picklable (module imports are okay... |
__author__ = 'PARKJINSANG'
#
def read_file(path):
"""
Read text from file path
:param path: string of path of file to read
:return: contents inside the file
"""
file = open(path, "r", encoding='ISO-8859-1')
contents = ""
while True:
line = file.readline()
if not line:
... |
import capstone as _capstone
from .arch import Arch
# FIXME: Tell fish to fix whatever he was storing in info['current_function']
# TODO: Only persist t9 in PIC programs
class ArchMIPS32(Arch):
def __init__(self, endness="Iend_LE"):
super(ArchMIPS32, self).__init__(endness)
if endness == 'Iend_BE... |
from openerp import fields, models
from openerp import tools
class crm_activity_report(models.Model):
""" CRM Lead Analysis """
_name = "crm.activity.report"
_auto = False
_description = "CRM Activity Analysis"
_rec_name = 'id'
date = fields.Datetime('Date', readonly=True)
author_id = fie... |
"""
Represents a launch specification for Spot instances.
"""
from boto.ec2.ec2object import EC2Object
from boto.resultset import ResultSet
from boto.ec2.blockdevicemapping import BlockDeviceMapping
from boto.ec2.group import Group
from boto.ec2.instance import SubParse
class GroupList(list):
def startElement(s... |
def slogdet(a):
"""
Compute the sign and (natural) logarithm of the determinant of an array.
If an array has a very small or very large determinant, than a call to
`det` may overflow or underflow. This routine is more robust against such
issues, because it computes the logarithm of the determinant ... |
# weather.py
# Rewritten by ScottSteiner to use Weather Underground instead of Yahoo
from util import hook, database, http, web
base_url = "http://api.wunderground.com/api/{}/{}/q/{}.json"
def format_coordinates(latitude, longitude):
"Formats coordinates into one string"
latitude = round(float(latitude), 2)
longi... |
"""
Internet Group Management Protocol(IGMP) packet parser/serializer
RFC 1112
IGMP v1 format
0 1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
|Version| Type | ... |
from rawweb import *
def main(raw_stream,ssl):
'''
This Burpy module is specially written to find CSRF vulnerability in Facebook Application.
It has already found few minor CSRF vulnerability in FB application. Few them was qualifed for Bug Bounty.
It simply checks whether CSRF token validation is present in Server... |
import hashlib
import hmac
import json
import uuid
import urlparse
from django import http
from django.conf import settings
from django.contrib import auth
from django.contrib.auth.signals import user_logged_in
from django.db import IntegrityError
from django.utils.datastructures import MultiValueDictKeyError
import ... |
from .currency_getter_interface import Currency_getter_interface
from datetime import datetime
from openerp.tools import DEFAULT_SERVER_DATE_FORMAT
import logging
_logger = logging.getLogger(__name__)
class PL_NBP_getter(Currency_getter_interface):
"""Implementation of Currency_getter_factory interface
for ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
VMware Inventory Script
=======================
Retrieve information about virtual machines from a vCenter server or
standalone ESX host. When `group_by=false` (in the INI file), host systems
are also returned in addition to VMs.
This script will attempt to read conf... |
import os
import re
import types
import ConfigParser
import shlex
class RegistrationBase(object):
def __init__(self, module, username=None, password=None):
self.module = module
self.username = username
self.password = password
def configure(self):
raise NotImplementedError("Mu... |
# -*- coding: utf-8 -*-
import sys
from datetime import timedelta, datetime
import pytest
import ttcal
from django.core.exceptions import ValidationError
from django.db import connection
from django.forms import Form
from ttcal import Duration
from dkmodelfields import DurationField
from dkmodelfields import adminform... |
ANSIBLE_METADATA = {'status': ['stableinterface'],
'supported_by': 'core',
'version': '1.0'}
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.service import sysv_exists, sysv_is_enabled, fail_if_missing
from ansible.module_utils._text import to_nati... |
# -*- coding: utf-8 -*-
"""
jinja2.testsuite.utils
~~~~~~~~~~~~~~~~~~~~~~
Tests utilities jinja uses.
:copyright: (c) 2010 by the Jinja Team.
:license: BSD, see LICENSE for more details.
"""
import gc
import unittest
import pickle
from jinja2.testsuite import JinjaTestCase
from jinja2.utils imp... |
"""SCons.Tool.Packaging.targz
The targz SRC packager.
"""
#
# Copyright (c) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009 The SCons Foundation
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in t... |
from OpenGL.GL import *
from itertools import product
from math import ceil, log
from PIL import Image, ImageDraw, ImageFont
from .core import Context, Texture, VertexBuffer, Scene
from .matrix import Matrix
from .programs import TextProgram
from .util import interleave
def float_to_byte_color(color):
return tuple... |
from __future__ import unicode_literals
import re
from .common import InfoExtractor
from ..compat import (
compat_urllib_parse,
compat_str,
)
from ..utils import (
ExtractorError,
find_xpath_attr,
fix_xml_ampersands,
HEADRequest,
sanitized_Request,
unescapeHTML,
url_basename,
R... |
import datetime
from django.conf import settings
from django.core.mail import send_mail
from django.db import models
from django.db.models.signals import post_save
from django.dispatch import receiver
from django.template.loader import render_to_string
from django.utils.hashcompat import sha_constructor
from django.c... |
"""
Polish-language mappings for language-dependent features of
reStructuredText.
"""
__docformat__ = 'reStructuredText'
directives = {
# language-dependent: fixed
'uwaga': 'attention',
'ostro\u017cnie': 'caution',
'code (translation required)': 'code',
'niebezpiecze\u0144stwo': 'danger... |
from m5.util.code_formatter import code_formatter
def printDotty(sm, code):
code('digraph ${{sm.getIdent()}} {')
code.indent()
for t in sm.transitions:
# Don't print ignored transitions
if t.getActionShorthands() in ("--", "z"):
continue
code('${{t.getStateShorthand()}}... |
import numpy.testing
import chainerx
# NumPy-like assertion functions that accept both NumPy and ChainerX arrays
def _as_numpy(x):
if isinstance(x, chainerx.ndarray):
return chainerx.to_numpy(x)
assert isinstance(x, numpy.ndarray) or numpy.isscalar(x)
return x
def _check_dtype_and_strides(x, y... |
#! /usr/bin/env python
# pdeps
#
# Find dependencies between a bunch of Python modules.
#
# Usage:
# pdeps file1.py file2.py ...
#
# Output:
# Four tables separated by lines like '--- Closure ---':
# 1) Direct dependencies, listing which module imports which other modules
# 2) The inverse of (1)
# 3) Indirect de... |
import unittest
import os
import sys
import commands
import comm
class TestWebAppInstall(unittest.TestCase):
def test_install(self):
comm.setUp()
app_name = "helloworld"
pkg_name = "com.example." + app_name.lower()
comm.app_install(app_name, pkg_name, self)
if __name__ == '__main... |
from openerp.tests.common import TransactionCase
class test_department(TransactionCase):
def setUp(self):
super(test_department, self).setUp()
# Clean up registries
self.registry('ir.model').clear_caches()
self.registry('ir.model.data').clear_caches()
# Get registries
... |
import pandas as pd
from sklearn.ensemble import RandomForestClassifier
from sklearn.ensemble import GradientBoostingClassifier
from sklearn.ensemble import BaggingClassifier
from sklearn.ensemble import AdaBoostClassifier
from sklearn.ensemble import ExtraTreesClassifier
from sklearn.neural_network import MLPClassifie... |
"Test posix functions"
from test import test_support
# Skip these tests if there is no posix module.
posix = test_support.import_module('posix')
import errno
import sys
import time
import os
import pwd
import shutil
import stat
import sys
import tempfile
import unittest
import warnings
_DUMMY_SYMLINK = os.path.join... |
"""KFP pipeline orchestrating BigQuery and Cloud AI Platform services."""
import os
from helper_components import evaluate_model
from helper_components import retrieve_best_run
from jinja2 import Template
import kfp
from kfp.components import func_to_container_op
from kfp.dsl.types import Dict
from kfp.dsl.types impo... |
"""
EasyBuild support for building and installing Xmipp, implemented as an easyblock
@author: Jens Timmerman (Ghent University)
"""
import glob
import os
import easybuild.tools.toolchain as toolchain
from easybuild.framework.easyblock import EasyBlock
from easybuild.tools.build_log import EasyBuildError
from easybuil... |
ANSIBLE_METADATA = {'metadata_version': '1.0',
'status': ['preview'],
'supported_by': 'community'}
from ansible.module_utils.basic import AnsibleModule
try:
from ansible.module_utils.avi import (
avi_common_argument_spec, HAS_AVI, avi_ansible_api)
except ImportError:... |
from sympy.core.compatibility import range
from sympy.core.basic import Basic
from sympy.vector.vector import Vector
from sympy.vector.coordsysrect import CoordSysCartesian
from sympy.vector.functions import _path
from sympy import Symbol
from sympy.core.cache import cacheit
class Point(Basic):
"""
Represents... |
"""This file contains code for use with "Think Bayes",
by Allen B. Downey, available from greenteapress.com
Copyright 2012 Allen B. Downey
License: GNU GPLv3 http://www.gnu.org/licenses/gpl.html
"""
from __future__ import print_function, division
import math
import columns
import thinkbayes2
import thinkbayes2
impo... |
'''
Given a collection of intervals, merge all overlapping intervals.
For example,
Given [1,3],[2,6],[8,10],[15,18],
return [1,6],[8,10],[15,18].
'''
# Definition for an interval.
class Interval(object):
def __init__(self, s=0, e=0):
self.start = s
self.end = e
# To print the result
def _... |
"""Simple sequential environment with known Q-function for testing purposes.
The user dynamics in this environment follow a 6 state x 4 action MDP with
the following specification:
0 # action
0 (1 0.1) (2 0.1) (3 0.8)
1 (2 0.1) (3 0.1) (4 0.8)
2 (3 0.1) (4 0.1) (5 0.8)
3 (4 0.1) (5 0.1) (0 0.8)
4 (5 1.0)
5 (0 1.0)
... |
"""
The main hook file that is called by Juju.
"""
import json
import httplib
import os
import time
import socket
import subprocess
import sys
import urlparse
from charmhelpers.core import hookenv, host
from kubernetes_installer import KubernetesInstaller
from path import path
from lib.registrator import Registrator
... |
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from spark.gui.resource import iconPath
__all__ = ["FileList", "FileInfoWidget"]
class CustomList(QWidget):
def __init__(self, parent=None):
super(CustomList, self).__init__(parent)
self.setFocusPolicy(Qt.StrongFocus)
self.oddColor = QPa... |
#!/usr/bin/python
#-*- coding: utf-8 -*-
import random
from IPy import IP as ip
class DHCP:
def __hash__(self):
return hash(random.random())
def __eq__(self, other):
return hash(self) == hash(other)
def __str__(self):
return "<DHCP>"
class _IP:
def __init__(self, address, netmask, gateway):
self.add... |
import cv2
import numpy as np
from matplotlib import pyplot as plt
from skimage import morphology
from drawlinefeature import DrawLineFeature,drawconvex#zc
from lineseg import lineseg
from drawedgelist import drawedgelist
from Lseg_to_Lfeat_v2 import Lseg_to_Lfeat_v2 #zc
from LabelLineCurveFeature_v2 import... |
from __future__ import unicode_literals
from datetime import datetime
import re
import threading
# from django.conf import settings
from django.contrib import comments
from django.contrib.comments.signals import comment_was_posted
from django.contrib.contenttypes.models import ContentType
from django.contrib.sites.mo... |
# -*- coding: utf-8 -*-
import base64
import logging
import sys
import threading
import openerp
import openerp.report
from openerp import tools
import security
_logger = logging.getLogger(__name__)
# TODO: set a maximum report number per user to avoid DOS attacks
#
# Report state:
# False -> True
self_reports... |
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as expected
from pages.base import BaseRegion
class SendToDevice(BaseRegion):
_root_locator = (By.CSS_SELECTOR, '.send-to-device')
_email_locator = (By.CSS_SELECTOR, '.send-to-device-input')
_submit_bu... |
import unittest
from libcloud.utils.py3 import httplib
import sys
from libcloud.compute.types import InvalidCredsError
from libcloud.compute.drivers.ibm_sce import IBMNodeDriver as IBM
from libcloud.compute.base import Node, NodeImage, NodeSize, NodeLocation
from libcloud.test import MockHttp
from libcloud.test.compu... |
ANSIBLE_METADATA = {'metadata_version': '1.0',
'status': ['preview'],
'supported_by': 'community'}
import re
from ansible.module_utils.nxos import get_config, load_config, run_commands
from ansible.module_utils.nxos import nxos_argument_spec, check_args
from ansible.module_util... |
from functools import wraps
from django.utils.decorators import available_attrs, method_decorator
from django.views.decorators.cache import never_cache
from django.views.decorators.http import last_modified as cache_last_modified
from django.utils.translation import ugettext_lazy as _
from django.core.exceptions impor... |
import os, unittest
import sqlite3 as sqlite
def get_db_path():
return "sqlite_testdb"
class TransactionTests(unittest.TestCase):
def setUp(self):
try:
os.remove(get_db_path())
except OSError:
pass
self.con1 = sqlite.connect(get_db_path(), timeout=0.1)
... |
"""
Do not use unberbars for cpp filename.
Only alphabets, numbers can be used for a cpp filename.
== Vilolation ==
/testdir/test_1.cpp <== Violation. - is used.
/testdir1/_test1.cpp <== Violation. _ is used
== Good ==
testdir/test.cpp
testdir1/test_1.c <== Don't care. it's c file.
"""
from nsiqcp... |
ANSIBLE_METADATA = {'metadata_version': '1.0',
'status': ['preview'],
'supported_by': 'community'}
try:
import shade
HAS_SHADE = True
except ImportError:
HAS_SHADE = False
from distutils.version import StrictVersion
def _needs_update(module, aggregate):
new_m... |
from __future__ import division, print_function, unicode_literals
# This code is so you can run the samples without installing the package
import sys
import os
sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..'))
#
# total time duration * action multiplier
testinfo = "s, t 2.0, s, t 4.0, s, t 6.1, s, q"
... |
import boto
from boto.compat import json
from boto.cloudsearch.optionstatus import OptionStatus
from boto.cloudsearch.optionstatus import IndexFieldStatus
from boto.cloudsearch.optionstatus import ServicePoliciesStatus
from boto.cloudsearch.optionstatus import RankExpressionStatus
from boto.cloudsearch.document import ... |
try:
import urlparse
except ImportError:
import urllib.parse as urlparse
import newrelic.packages.six as six
from newrelic.agent import (current_transaction,
wrap_function_wrapper, ExternalTrace)
def _nr_wrapper_factory(bind_params_fn, library):
# Wrapper functions will be similar for monkeypatching ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.