content stringlengths 4 20k |
|---|
import BoostBuild
import string
t = BoostBuild.Tester(pass_toolset=1)
t.write("jamroot.jam", """\
import feature ;
feature.feature test_feature : : free ;
import toolset ;
toolset.flags creator STRING : <test_feature> ;
actions creator
{
echo $(STRING) > $(<)
}
make foo.bar : : creator : <test_feature>12345678... |
import time
from XmTestLib import *
import xen.util.blkif
__all__ = [ "block_attach", "block_detach" ]
def get_state(domain, devname):
(path, number) = xen.util.blkif.blkdev_name_to_number(devname)
s, o = traceCommand("xm block-list %s | awk '/^%d/ {print $4}'" %
(domain.getName(),... |
from __future__ import unicode_literals
import posixpath
from django.conf import settings
from django.test import override_settings
from .cases import StaticFilesTestCase, TestDefaults
@override_settings(ROOT_URLCONF='staticfiles_tests.urls.default')
class TestServeStatic(StaticFilesTestCase):
"""
Test sta... |
"""IPv4 helper functions."""
import socket
import sys
if sys.hexversion < 0x02030000 or sys.platform == 'win32':
#
# Some versions of Python 2.2 have an inet_aton which rejects
# the valid IP address '255.255.255.255'. It appears this
# problem is still present on the Win32 platform even in 2.3.
... |
# Corresponds to a small subset of scipy.special.specfun
# that has features that were ported manually from fwrap
# to f2py.
# It was assumed that SciPy 0.7.0 shipped with Ubuntu Lucid
# (using f2py) returned the correct values.
#
import numpy as np
from numpy import array, isnan, r_, arange, finfo, pi, sin, cos, ta... |
""" discover and run doctests in modules and test files."""
from __future__ import absolute_import, division, print_function
import traceback
import pytest
from _pytest._code.code import ExceptionInfo, ReprFileLocation, TerminalRepr
from _pytest.fixtures import FixtureRequest
DOCTEST_REPORT_CHOICE_NONE = 'none'
DOC... |
# ~*~ coding: utf-8 ~*~
import os
import shutil
from collections import namedtuple
from ansible import context
from ansible.playbook import Playbook
from ansible.module_utils.common.collections import ImmutableDict
from ansible.executor.task_queue_manager import TaskQueueManager
from ansible.vars.manager import Vari... |
from openerp.osv import osv,fields
from openerp.tools.translate import _
class repair_cancel(osv.osv_memory):
_name = 'mrp.repair.cancel'
_description = 'Cancel Repair'
def cancel_repair(self, cr, uid, ids, context=None):
""" Cancels the repair
@param self: The object pointer.
@par... |
"""Tests for the stream implementations."""
import logging
import math
import unittest
from apache_beam.coders import slow_stream
class StreamTest(unittest.TestCase):
# pylint: disable=invalid-name
InputStream = slow_stream.InputStream
OutputStream = slow_stream.OutputStream
ByteCountingOutputStream = slow... |
from django.forms import CheckboxSelectMultiple
from .base import WidgetTest
class CheckboxSelectMultipleTest(WidgetTest):
widget = CheckboxSelectMultiple()
def test_render_value(self):
self.check_html(self.widget, 'beatles', ['J'], choices=self.beatles, html=(
"""<ul>
<li><l... |
# -*- coding: utf-8 -*-
""" Sahana Eden Staff Module Automated Tests
@copyright: 2011-2012 (c) Sahana Software Foundation
@license: MIT
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 the... |
# -*- coding: utf-8 -*-
import time
from datetime import datetime
from openerp.osv import fields, osv, orm
from openerp.tools.translate import _
from openerp import tools
import openerp.addons.decimal_precision as dp
class account_move_line(osv.osv):
_inherit = "account.move.line"
def _net(self, cr, uid, i... |
import sys
# ------------------------------------------------------------------------
#
# #TODO #FIXME Airflow 2.0
#
# Old import machinary below.
#
# This is deprecated but should be kept until Airflow 2.0
# for compatibility.
#
# ------------------------------------------------------------------------
_operators = ... |
from __future__ import unicode_literals
import frappe
from frappe.utils import cstr, cint, getdate
from frappe import msgprint, _
from calendar import monthrange
def execute(filters=None):
if not filters: filters = {}
conditions, filters = get_conditions(filters)
columns = get_columns(filters)
att_map = get_atten... |
from __future__ import unicode_literals
import webnotes
from webnotes.utils import flt, fmt_money, getdate
from webnotes.model.code import get_obj
from webnotes import msgprint, _
sql = webnotes.conn.sql
class DocType:
def __init__(self,d,dl):
self.doc, self.doclist = d, dl
def validate(self): # not called on ... |
#converts bitcoincharts csv download into the
#1min format used by the genetic trade framework
from time import *
import urllib2
import sys
__app_version__ = "0.01a"
print "-"*80
print """
Bitcoin Data Feed Synchronizer v%s
\tConverts the data into a weighted price 1min data feed format
To automaticaly download and... |
import operator
import pytest
from pyconll.util import find_ngrams, find_nonprojective_deps
from pyconll import load_from_file
from tests.util import fixture_location
def test_ngram_standard():
"""
Test if the find_ngram method works for standard situations.
"""
c = load_from_file(fixture_location('... |
import gear
import json
import logging
import select
import socket
import threading
import zmq
class MyGearmanServer(gear.Server):
def handleStatus(self, request):
request.connection.conn.send(("build:fake_job\t%s\t0\t0\n" %
self._count).encode('utf8'))
request... |
import cv2
import numpy as np
import matplotlib.pyplot as plt
from scipy import ndimage as sc
# Загрузка
filename = '../img/satelite.tif'
img = sc.imread(filename)
# img = img[0:8000, 0:8000]
# # Коррекция гистограммы
for i in range(1, 30):
alpha = 1 * i
a = cv2.convertScaleAbs(img, alpha=alp... |
from .composition_parts import Identifier
from .composition_parts import WithIdentifier
class IRMap(object):
"""
Manages an identifier-IR map, where IR is IdIRMap.IR. This class is
designed to work together with IdlCompiler closely. See also
IdlCompiler, especially how IdlCompiler uses compilation p... |
import pylith.mpi.mpi as mpimodule
# Communicator class
class Communicator(object):
"""Python MPI communicator object.
"""
# PUBLIC METHODS /////////////////////////////////////////////////////
def __init__(self, handle):
"""Constructor.
"""
# Transfer responsibility of memo... |
"""This module implements the Scraper component which parses responses and
extracts information from them"""
from collections import deque
from twisted.python.failure import Failure
from twisted.internet import defer
from scrapy.utils.defer import defer_result, defer_succeed, parallel, iter_errback
from scrapy.utils... |
import distutils.command.build_scripts
import distutils.util
import glob
import os
import mysql.utilities
def find_packages(*args, **kwrds):
"""Find all packages and sub-packages and return a list of them.
The function accept any number of directory names that will be
searched to find packages. Packages... |
import unittest
from tkinter import Variable, StringVar, IntVar, DoubleVar, BooleanVar, Tcl
class Var(Variable):
_default = "default"
side_effect = False
def set(self, value):
self.side_effect = True
super().set(value)
class TestBase(unittest.TestCase):
def setUp(self):
s... |
#github data scrapper
"""
variables of interest:
indp. variables
- language, given as a binary variable. Need 4 positions for 5 langagues
- #number of days created ago, 1 position
- has wiki? Boolean, 1 position
- followers, 1 position
- following, 1 position
- constant
dep. variab... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import argparse, math, random
from pyutil.mathutil import div_ceil
from pkg_resources import resource_stream
def recursive_subset_sum(entropy_needed, wordlists):
# Pick a minimalish set of numbers which sum to at least
# entropy_needed.
# Okay now what's th... |
import os
DEBUG = True
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'.
'NAME': 'db.sqlite3', # Or path to database file if using sqlite3.
'USER': '', # Not used with s... |
from sqlalchemy import MetaData, Table, func, select
from sqlalchemy.sql import and_
from nova import exception
from nova.i18n import _
def upgrade(migrate_engine):
meta = MetaData(migrate_engine)
instances = Table('instances', meta, autoload=True)
sysmeta = Table('instance_system_metadata', meta, autolo... |
import hashlib
import sys
class message(object):
def __init__(self):
self.registration = ['complianceitems']
self.priority = 20
def validate(self,item):
"""
Validate that a compliance item has all the necessary keys
"""
for key in ['target', 'policy', 'chec... |
import re
import datetime
import json
from django.utils import timezone
class DefaultMangler(json.JSONDecoder):
def __init__(self, *args, **kwargs):
self.basepk = kwargs.get('basepk', -1)
self.owner = kwargs.get('owner', 'admin')
self.datastore = kwargs.get('datastore', '')
self.... |
from Screens.Screen import Screen
from Plugins.Plugin import PluginDescriptor
from Components.SystemInfo import SystemInfo
from Components.ConfigList import ConfigListScreen
from Components.config import getConfigListEntry, config, ConfigBoolean, ConfigNothing, ConfigSlider
from Components.Label import Label
from Compo... |
import os
from pyglet.window import key
DEBUG = os.path.exists('../debug')
WINDOW_WIDTH = 640
WINDOW_HEIGHT = 480
FIELD_FONT_SIZE = 12
OBJECT_FONT_SIZE = 10
STATS_PANEL_X = 460
STATS_PANEL_Y = 70
STATUS_PANEL_HEIGHT = 65.0
ST_BOUND_X = 480
ST_BOUND_Y = 470
WALL_WIDTH = 10
NORMAL_DIFICULTY = True
GAME_NAME = 'GAME 3'
O... |
"""
General tests for twisted.enterprise.
"""
from twisted.trial import unittest
from twisted.enterprise import util
class QuotingTestCase(unittest.TestCase):
def testQuoting(self):
for value, typ, expected in [
(12, "integer", "12"),
("foo'd", "text", "'foo''d'"),
("... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {
'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'
}
DOCUMENTATION = r'''
---
module: vmware_host_ntp_facts
short_description: Gathers facts about NTP configuration on an E... |
__author__ = 'aje'
#
# Copyright (c) 2008 - 2013 10gen, Inc. <http://10gen.com>
#
# 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.apache.org/licenses/LICENSE-2.0
#
# Unless r... |
from weakref import ref
from blinker._saferef import BoundMethodWeakref
try:
callable
except NameError:
def callable(object):
return hasattr(object, '__call__')
try:
from collections import defaultdict
except:
class defaultdict(dict):
def __init__(self, default_factory=None, *a, **... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import os
import json
import sys
from nose.plugins.skip import SkipTest
if sys.version_info < (2, 7):
raise SkipTest("F5 Ansible modules require Python >= 2.7")
from ansible.compat.tests import unittest
from ansible.compat.te... |
import sys
import re
import numpy as np
from collections import defaultdict
from matplotlib import pyplot as plt
import seaborn as sns
sns.set_style("white")
colors = sns.set_palette('Set1', 8)
colors = sns.color_palette('Set1', 3)
f, axes = plt.subplots(1, figsize=(4, 2))
axes = (axes,)
# run as python chunk-gap-p... |
"""
Support for FLAME as toolchain linear algebra library.
@author: Stijn De Weirdt (Ghent University)
@author: Kenneth Hoste (Ghent University)
"""
from easybuild.toolchains.linalg.lapack import Lapack
class Flame(Lapack):
"""Less trivial module, provides FLAME support."""
LAPACK_MODULE_NAME = ['FLAME'] + ... |
import requests
import collections
import sys
import time
import json
Entry = collections.namedtuple("Entry", "name position rows")
ROW_TYPES = {}
def row_type_for_columns(name, column_names):
column_names = tuple(column_names)
row_type = ROW_TYPES.get((name, column_names))
if row_type is None:
... |
import os
import unittest
from MooseDocs.testing import MarkdownTestCase
class TestMooseObjectSyntax(MarkdownTestCase):
"""
Test commands in MooseObjectSyntax extension.
"""
def testDescription(self):
md = '!description /Adaptivity/Markers/BoxMarker'
self.assertConvert('test_description... |
import mail_compose_message
import mail_mass_mailing_create_segment |
# coding: utf-8
from __future__ import unicode_literals
import re
from .common import InfoExtractor
from ..utils import (
extract_attributes,
int_or_none,
)
class PokemonIE(InfoExtractor):
_VALID_URL = r'https?://(?:www\.)?pokemon\.com/[a-z]{2}(?:.*?play=(?P<id>[a-z0-9]{32})|/[^/]+/\d+_\d+-(?P<display_i... |
""" log machine-parseable test session result information in a plain
text file.
"""
import py
import os
def pytest_addoption(parser):
group = parser.getgroup("terminal reporting", "resultlog plugin options")
group.addoption('--resultlog', '--result-log', action="store",
metavar="path", default=None,
... |
"""
This script uses the Vision API's label detection capabilities to find a label
based on an image's content.
To run the example, install the necessary libraries by running:
pip install -r requirements.txt
Run the script on an image to get a label, E.g.:
./label.py <path-to-image>
"""
# [START import_lib... |
import random, subprocess, difflib
while True:
# Random decisions
num = random.randint(2, 250)
density = random.random() * random.random()
decisions = [random.randint(1, num*20) for x in range(num*3)]
branches = [0]*num
defaults = [0]*num
for i in range(num):
b = set([])
bs = random.randint(1, ma... |
"""Config file parsing
All of the scripts in this project use the optparse package to handle
command line options.
This module provides a very simple mechanism for taking config files
as input instead of specifying options on the command line. This is
convenient, for example, for running experiments repeatedly whe... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.python.framework import test_util
from tensorflow.python.ops import array_ops
from tensorflow.python.platform import googletest
from tensorflow.python.summary import text_summary
class TextPlu... |
'''
Created on 27 Apr 2014
@author: Neil Nutt, neilnutt[at]googlemail[dot]com
Tab used to store/collect catchment descriptors
Statistical Flood Estimation Tool
Copyright (C) 2014 Neil Nutt, neilnutt[at]googlemail[dot]com
https://github.com/OpenHydrology/StatisticalFloodEstimationTool
This program i... |
import logging
import sys
import time
import unittest
from doekbase.data_api.util import MonitorMemory, get_logger, basic_config
_log = get_logger(__name__)
alerted = {}
MB = 1024 * 1024
def icanhaz_alert(mm, avail, thresh, name):
assert avail < thresh
alerted[name] = avail
_log.debug('\nalerted: {:d} M... |
from time import time
from urllib2 import HTTPError
import threading
import os
from pycoin.encoding import double_sha256
from coloredcoinlib.store import DataStore, DataStoreConnection, PersistentDictStore, unwrap1
from ngcccbase.services.blockchain import BlockchainInfoInterface
from txcons import RawTxSpec
from blo... |
from __future__ import print_function
import socket
import telnetlib
import sys
from ftplib import FTP
import ftplib
# Check if IP is valid
def is_ip(address):
try:
socket.inet_aton(address)
ip = True
except socket.error:
ip = False
return ip
# Helper function
def split_into_path_... |
import abc
class AddonNodeLogger(object):
"""Helper class for adding correctly-formatted addon logs to nodes.
:param Node node: The node to add logs to
:param Auth auth: Authorization of the person who did the action.
"""
__metaclass__ = abc.ABCMeta
@abc.abstractproperty
def addon_short_n... |
import json
import logging
logger = logging.getLogger(__name__)
class Config(object):
"""A configuration for a Commander Keen bot
This will read and parse a configuration file containing parameters for
a Commander Keen Slack bot.
Configurations are made of a set of JSON-encoded variables. Commande... |
import sys, unittest
import ConfigParser
from ZSI.wstools.Utility import DOM
from ZSI.wstools.WSDLTools import WSDLReader
from ZSI.wstools.TimeoutSocket import TimeoutError
class WSDLToolsTestCase(unittest.TestCase):
def __init__(self, methodName='runTest'):
unittest.TestCase.__init__(self, methodName)
... |
# -*- coding: utf-8 -*-
"""
jinja2.debug
~~~~~~~~~~~~
Implements the debug interface for Jinja. This module does some pretty
ugly stuff with the Python traceback system in order to achieve tracebacks
with correct line numbers, locals and contents.
:copyright: (c) 2010 by the Jinja Team.
:... |
"""
The I{schema} module provides a intelligent representation of
an XSD schema. The I{raw} model is the XML tree and the I{model}
is the denormalized, objectified and intelligent view of the schema.
Most of the I{value-add} provided by the model is centered around
tranparent referenced type resolution and targeted de... |
from __future__ import unicode_literals
import base64
import logging
import string
from datetime import datetime, timedelta
from django.conf import settings
from django.contrib.sessions.exceptions import SuspiciousSession
from django.core.exceptions import SuspiciousOperation
from django.utils import timezone
from dj... |
import os
import subprocess
import sys
import time
class BuildError(Exception):
def __init__(self, value):
self.value = value
def __repr__(self):
return repr(self.value)
def runInDir(command, dir=None, verbose=True):
if dir:
olddir = os.getcwd()
os.chdir(dir)
commandS... |
from nose.plugins.attrib import attr
from marvin.integration.lib.base import *
from marvin.integration.lib.utils import *
from marvin.integration.lib.common import *
#Import Local Modules
from marvin.cloudstackTestCase import cloudstackTestCase
from marvin.cloudstackAPI import *
class Services:
"""Test Services f... |
import logging
from django.utils.translation import ugettext_lazy as _
from horizon import forms
from horizon import workflows
from openstack_dashboard.api import network
LOG = logging.getLogger(__name__)
class Parameter(object):
def __init__(self, config):
self.name = config['name']
self.desc... |
import logging
import re
from autotest.client.shared import error
from virttest import utils_test
def test_list_with_mount(vm, params):
"""
1) Fall into guestfish session w/o inspector
2) Do some necessary check
3) Try to mount root filesystem to /
"""
params['libvirt_domain'] = vm.name
pa... |
import tempfile
import time
from selenium.webdriver.common.action_chains import ActionChains
class SourceNavigationStepsMixin:
def _is_on_source_homepage(self):
return self.wait_for(
lambda: self.driver.find_element_by_id("source-index")
)
def _is_logged_in(self):
return ... |
import copy
import json
import logging
import os
import socket
import ssl
from keystoneclient import adapter
import six
import six.moves.urllib.parse as urlparse
from ironicclient import exc
LOG = logging.getLogger(__name__)
USER_AGENT = 'python-ironicclient'
CHUNKSIZE = 1024 * 64 # 64kB
API_VERSION = '/v1'
def... |
from geonode.maps.models import Map, MapLayer
from django.conf import settings
maplayers = [
{
"fixed": False,
"group": "background",
"layer_params": "",
"map": 1,
"name": "geonode:CA",
"ows_url": "http://localhost:8080/geoserver/wms",
"source_params": "",
... |
import rope.base.builtins
import rope.base.pynames
import rope.base.pyobjects
from rope.base import ast, astutils, exceptions, pyobjects, arguments, worder
BadIdentifierError = exceptions.BadIdentifierError
def eval_location(pymodule, offset):
"""Find the pyname at the offset"""
return eval_location2(pymodul... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from ..organizations.base import BaseOrganizationModel
from ..types import *
class BaseDomainNameModel(BaseOrganizationModel):
"""
This is a base Elasticsearch model for representing data that is tied to a given domain
name.
"""
# Cl... |
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['stableinterface'],
'supported_by': 'community'}
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.cloudstack import (
AnsibleCloudStack,
cs_argument_spec,
cs_required_together,
)... |
import os
import sys
from optparse import OptionParser, NO_DEFAULT
import imp
import django
from django.core.management.base import BaseCommand, CommandError, handle_default_options
from django.utils.importlib import import_module
# For backwards compatibility: get_version() used to be in this module.
get_version = d... |
# coding:utf-8
#二分KMeans方法
#依赖于KMeans里面的一些方法
import numpy as np
from KMeans import *
from pylab import *
#进行多次(n次),寻找到近似最小SSE
def choose_min_SSE(n,data_1):
min_sse = np.inf
i = 0
while i<n :
data_2=choose_initil_point(2, data_1)
[outcomes,poly_point]=k_means(data_1, data_2)
sse = 0
... |
from __future__ import with_statement
import os.path
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
extra = {'scripts': ["bin/pyflakes"]}
else:
extra = {
'test_suite': 'pyflakes.test',
'entry_points': {
'console_scripts': ['pyflakes =... |
from sympy import sqrt, root, S, Symbol, sqrtdenest, Integral, cos
from sympy.simplify.sqrtdenest import _subsets as subsets
r2, r3, r5, r6, r7, r10, r15, r29 = [sqrt(x) for x in [2, 3, 5, 6, 7, 10,
15, 29]]
def test_sqrtdenest():
d = {sqrt(5 + 2 * r6): r2 + r3,
... |
from Screens.Wizard import WizardSummary
from Screens.WizardLanguage import WizardLanguage
from Screens.Rc import Rc
from VideoHardware import video_hw
from Components.Pixmap import Pixmap, MovingPixmap, MultiPixmap
from Components.config import config, ConfigBoolean, configfile
from Tools.Directories import resolveF... |
from __future__ import print_function
from __future__ import unicode_literals
import os.path
import sys
sys.path.insert(1, os.path.abspath(os.path.join(os.path.dirname(__file__), '../lib')))
sys.path.insert(1, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
import unittest
from tests import SiCKRAGE... |
from oslo_config import cfg
auth_opts = [
cfg.StrOpt("auth_strategy",
default="keystone",
choices=("keystone", "noauth2"),
help="""
This determines the strategy to use for authentication: keystone or noauth2.
'noauth2' is designed for testing only, as it does no actual credentia... |
class Code(object):
"""A convenience object for constructing code.
Logically each object should be a block of code. All methods except |Render|
and |IsEmpty| return self.
"""
def __init__(self, indent_size=2, comment_length=80):
self._code = []
self._indent_level = 0
self._indent_size = indent_si... |
# -*- coding: utf-8 -*-
"""
oauthlib.utils
~~~~~~~~~~~~~~
This module contains utility methods used by various parts of the OAuth
spec.
"""
import string
import time
import urllib2
from random import getrandbits, choice
from oauthlib.common import quote, unquote
UNICODE_ASCII_CHARACTER_SET = (string.ascii_letters.... |
"""Export the Python grammar and symbols."""
# Python imports
import os
# Local imports
from .pgen2 import token
from .pgen2 import driver
from . import pytree
# The grammar file
_GRAMMAR_FILE = os.path.join(os.path.dirname(__file__), "Grammar.txt")
_PATTERN_GRAMMAR_FILE = os.path.join(os.path.dirname(__file__),
... |
import mimetypes
import six.moves.urllib
from blinkpy.common.net.network_transaction import NetworkTransaction
def get_mime_type(filename):
return mimetypes.guess_type(filename)[0] or 'application/octet-stream'
# FIXME: Rather than taking tuples, this function should take more structured data.
def _encode_mult... |
from django.contrib.auth import models as auth
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
# No related name is needed here, since symmetrical relations are not
# explicitly reversible.
@python_2_unicode_compatible
class SelfRefer(models.Model):
name = models.CharFiel... |
"""Tests for tensorflow.contrib.layers.python.layers.encoders."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.contrib.layers.python.layers import encoders
from tensorflow.contrib.layers.python.ops import sparse_ops
from tensorflow.python... |
import base
import email_exact
import email_domain
import openerp_standard |
from __future__ import unicode_literals
from django.db import models
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin
class UserManager(BaseUserManager):
def _create_user(self, username, email, password, is_staff, is_superuser, **extra_fields):
email = self.norma... |
## \file
## \ingroup tutorial_tdataframe
## \notebook -nodraw
## This tutorial illustrates the basic features of the TDataFrame class,
## a utility which allows to interact with data stored in TTrees following
## a functional-chain like approach.
##
## \macro_code
##
## \date May 2017
## \author Danilo Piparo
import R... |
"""
The process of translating JS will go like that: # TOP = 'imports and scope set'
1. Remove all the comments
2. Replace number, string and regexp literals with markers
4. Remove global Functions and move their translation to the TOP. Also add register code there.
5. Replace inline functions with lvals
6. Rem... |
import sys, string, os
from Tkinter import *
import steps
Plugins = sys.argv[1]
print Plugins
pluginList = Plugins.split(':')
maxStep = 2
curStep = 1
stepList = []
# functions
# show step on the num index
def showStep(num):
global stepList
stepNum = len(stepList)
if num >= stepNum or num <= 0 :
... |
"""
Disjoint set data structure
"""
class DisjointSet:
""" Disjoint set data structure for incremental connectivity queries.
.. versionadded:: 1.6.0
Attributes
----------
n_subsets : int
The number of subsets.
Methods
-------
add
merge
connected
subset
subset... |
import webnotes
def execute():
# delete wrong gle entries created due to a bug in make_gl_entries of Account Controller
# when using payment reconciliation
res = webnotes.conn.sql_list("""select distinct gl1.voucher_no
from `tabGL Entry` gl1, `tabGL Entry` gl2
where
date(gl1.modified) >= "2013-03-11"
and da... |
"""Sort performance test.
See main() for command line syntax.
See tabulate() for output format.
"""
import sys
import time
import random
import marshal
import tempfile
import os
td = tempfile.gettempdir()
def randfloats(n):
"""Return a list of n random floats in [0, 1)."""
# Generating floats is expensive,... |
"""Various functions related to corelation (template matching)."""
from gamera.plugin import PluginFunction, PluginModule
from gamera.args import ImageType, Args, Float, Point
from gamera.enums import GREYSCALE, ONEBIT
class corelation_weighted(PluginFunction):
"""
Returns a floating-point value for how well... |
import logging
import numpy as np
from neon import NervanaObject, logger as neon_logger
logging.basicConfig(level=20)
logger = logging.getLogger()
def test_dropout(backend_default):
ng = NervanaObject.be
ng.bsz = ng.batch_size = 15
d_array2 = ng.array(np.random.randn(24).reshape((6, 4)), dtype=np.float... |
""" Functions kept for backward compatibility.
They are simple wrappers around a global RegistryManager methods.
"""
import logging
import openerp.conf.deprecation
from openerp.modules.registry import RegistryManager
_logger = logging.getLogger(__name__)
def get_db_and_pool(db_name, force_demo=False, status=No... |
"""
==============
phantom_import
==============
Sphinx extension to make directives from ``sphinx.ext.autodoc`` and similar
extensions to use docstrings loaded from an XML file.
This extension loads an XML file in the Pydocweb format [1] and
creates a dummy module that contains the specified docstrings. This
can be ... |
from decimal import Decimal
_ = lambda x:x
#from i18n import _
from electrum import WalletStorage, Wallet
from electrum.util import format_satoshis, set_verbosity
from electrum.bitcoin import is_valid, COIN, TYPE_ADDRESS
from electrum.network import filter_protocol
import sys, getpass, datetime
# minimal fdisk like gu... |
# -*- coding: utf-8 -*-
#大体chain of responseibilityと同じだが、
#chain of responseibilityはhandlerと実処理が一緒なのに対して
#commandはhandlerと実処理が別になっている
class File(object):
def __init__(self, name):
self.name = name
def getName(self):
return self.name
def decompress(self):
print self.name + u'を展開し... |
# coding: utf-8
import sys
from queue import PriorityQueue
class Node:
def __init__(self, value, left=None, right=None):
self.value = value
self.left = left
self.right = right
self.codes = []
def __lt__(self, other):
return self.value < other.value
def huffman_cod... |
# -*- coding: utf-8 -*-
"""
hyper/http20/bufsocket.py
~~~~~~~~~~~~~~~~~~~~~~~~~
This file implements a buffered socket wrapper.
The purpose of this is to avoid the overhead of unnecessary syscalls while
allowing small reads from the network. This represents a potentially massive
performance optimisation at the cost o... |
"""
Decorator module, see http://pypi.python.org/pypi/decorator
for the documentation.
"""
__version__ = '3.4.0'
__all__ = ["decorator", "FunctionMaker", "contextmanager"]
import sys, re, inspect
if sys.version >= '3':
from inspect import getfullargspec
def get_init(cls):
return cls.__init__
else:
... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'certified'}
DOCUMENTATION = r'''
---
module: bigip_firewall_policy
short_description: Manage AFM securit... |
from django.db.backends.utils import names_digest, split_identifier
from django.db.models.query_utils import Q
from django.db.models.sql import Query
__all__ = ['Index']
class Index:
suffix = 'idx'
# The max length of the name of the index (restricted to 30 for
# cross-database compatibility with Oracle)... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.