code
stringlengths
1
199k
import os import re import sys import imp import platform import subprocess from digits import device_query import config_option import prompt class CaffeOption(config_option.FrameworkOption): @staticmethod def config_file_key(): return 'caffe_root' @classmethod def prompt_title(cls): re...
__all__ = ['ObjectPath', 'ByteArray', 'Signature', 'Byte', 'Boolean', 'Int16', 'UInt16', 'Int32', 'UInt32', 'Int64', 'UInt64', 'Double', 'String', 'Array', 'Struct', 'Dictionary', 'UnixFd'] from _dbus_bindings import ( Array, Boolean, Byte, ByteArray, Dictionary, Double, Int16, Int3...
""" ZPT - Zope Page Template Renderer This module contains a plasTeX renderer that uses Zope Page Templates (actually simpleTAL) as the templating engine. NOTE: This module isn't really needed any more. The PageTempate renderer does everything that this module did and more. This is just here for backwards compatibili...
from __future__ import (absolute_import, division, print_function) __metaclass__ = type from ansible.errors import * from ansible.plugins.lookup import LookupBase from ansible.utils.listify import listify_lookup_plugin_terms class LookupModule(LookupBase): def run(self, terms, variables, **kwargs): terms[0]...
""" Tests for Discussion API serializers """ import itertools from urlparse import urlparse import ddt import httpretty import mock from nose.plugins.attrib import attr from django.test.client import RequestFactory from discussion_api.serializers import CommentSerializer, ThreadSerializer, get_context from discussion_a...
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 exprList = [] print "Check case of all NA in col for quantile. Also a single value" print "FIX! probably should return NA if all NA" print "What is the right answer for ...
"""Enables IterativeImputer The API and results of this estimator might change without any deprecation cycle. Importing this file dynamically sets :class:`~sklearn.impute.IterativeImputer` as an attribute of the impute module:: >>> # explicitly require this experimental feature >>> from sklearn.experimental imp...
""" Copyright 2009 Glencoe Software, Inc. All rights reserved. Use is subject to license terms supplied in LICENSE.txt """ import unittest class TestExample(unittest.TestCase): def testExample(self): pass if __name__ == '__main__': unittest.main()
"""The Query class and support. Defines the :class:`.Query` class, the central construct used by the ORM to construct database queries. The :class:`.Query` class should not be confused with the :class:`.Select` class, which defines database SELECT operations at the SQL (non-ORM) level. ``Query`` differs from ``Select`...
from __future__ import unicode_literals from frappe import _ def get_data(): return { 'fieldname': 'purchase_receipt_no', 'non_standard_fieldnames': { 'Purchase Invoice': 'purchase_receipt', 'Asset': 'purchase_receipt', 'Landed Cost Voucher': 'receipt_document', 'Auto Repeat': 'reference_document', ...
DOCUMENTATION = """ --- module: ios_command version_added: "2.1" author: "Peter sprygada (@privateip)" short_description: Run arbitrary commands on ios devices. description: - Sends arbitrary commands to an ios node and returns the results read from the device. The M(ios_command) module includes an argument t...
"""Manages performance counters of an application and/or its modules.""" __author__ = 'Pavel Simakov (psimakov@google.com)' def incr_counter_global_value(unused_name, unused_delta): """Hook method for global aggregation.""" pass def get_counter_global_value(unused_name): """Hook method for global aggregatio...
""" Test script for the 'cmd' module Original by Michael Schneider """ import cmd import sys from test import test_support import re import unittest import StringIO class samplecmdclass(cmd.Cmd): """ Instance the sampleclass: >>> mycmd = samplecmdclass() Test for the function parseline(): >>> mycmd....
from __future__ import (absolute_import, division, print_function) __metaclass__ = type from six import iteritems, string_types import os from ansible.errors import AnsibleError, AnsibleParserError from ansible.playbook.attribute import Attribute, FieldAttribute from ansible.playbook.role.definition import RoleDefiniti...
""" Test strerror """ import socket import os from twisted.trial.unittest import TestCase from twisted.internet.tcp import ECONNABORTED from twisted.python.win32 import _ErrorFormatter, formatError from twisted.python.runtime import platform class _MyWindowsException(OSError): """ An exception type like L{ctype...
""" Functions that can are used to modify XBlock fragments for use in the LMS and Studio """ import datetime import json import logging import static_replace import uuid import markupsafe from lxml import html, etree from django.conf import settings from django.utils.timezone import UTC from django.utils.html import es...
import testtools import webob.exc from nova.api.openstack.compute.contrib import hosts as os_hosts_v2 from nova.api.openstack.compute.plugins.v3 import hosts as os_hosts_v3 from nova.compute import power_state from nova.compute import vm_states from nova import context as context_maker from nova import db from nova imp...
from django.contrib.auth.mixins import PermissionRequiredMixin from django.core.urlresolvers import reverse_lazy from django.views.generic import ListView, UpdateView from admin.subjects.forms import SubjectForm from osf.models.subject import Subject from osf.models.provider import PreprintProvider class SubjectListVie...
""" Eigenvalue spectrum of graphs. """ import networkx as nx __author__ = "\n".join(['Aric Hagberg <aric.hagberg@gmail.com>', 'Pieter Swart (swart@lanl.gov)', 'Dan Schult(dschult@colgate.edu)']) __all__ = ['laplacian_spectrum', 'adjacency_spectrum'] def laplacian_spectrum...
import sys f = open(sys.argv[1], 'w') f.write('int main() {\n') f.write(' return 0;\n') f.write('}\n') f.close()
''' "luacompile" plugin for cocos command line tool ''' __docformat__ = 'restructuredtext' import sys import subprocess import os import json import inspect import cocos import struct _DELTA = 0x9E3779B9 def _long2str(v, w): n = (len(v) - 1) << 2 if w: m = v[-1] if (m < n - 3) or (m > n): return...
""" *************************************************************************** r_li_padsd_ascii.py ------------------- Date : February 2016 Copyright : (C) 2016 by Médéric Ribreux Email : medspx at medspx dot fr *********************************************...
import canvas import fill_style import line_style import pychart_util import chart_object import legend import font import color from pychart_types import * class T(chart_object.T): """Plots sector diagram which can be superimposed on one another. Sector diagrams are also known as wind roses""" keys = { ...
""" SWF (Macromedia/Adobe Flash) file parser. Documentation: - Alexis' SWF Reference: http://www.m2osw.com/swf_alexref.html - http://www.half-serious.com/swf/format/ - http://www.anotherbigidea.com/javaswf/ - http://www.gnu.org/software/gnash/ Author: Victor Stinner Creation date: 29 october 2006 """ from hachoi...
import sys, os import six sys.path.insert(0, os.path.abspath('..')) needs_sphinx = '1.2' extensions = [ "sphinx.ext.autodoc", "sphinx.ext.extlinks", ] templates_path = ['_templates'] source_suffix = '.rst' master_doc = 'index' project = u'behave' authors = u'Benno Rice, Richard Jones and Jens Engel' copyright =...
""" SleekXMPP: The Sleek XMPP Library Copyright (C) 2013 Nathanael C. Fritz, Lance J.T. Stout This file is part of SleekXMPP. See the file LICENSE for copying permission. """ from sleekxmpp.plugins.google.auth import stanza from sleekxmpp.plugins.google.auth.auth import GoogleAuth
""" Test function :func:`iris.fileformats.grib._load_convert.grid_definition_template_4_and_5`. """ from __future__ import (absolute_import, division, print_function) from six.moves import (filter, input, map, range, zip) # noqa import iris.tests as tests from copy import deepcopy import warnings import numpy as np fr...
"""Refactored "safe reference" from dispatcher.py""" import weakref, traceback, sys if sys.hexversion >= 0x3000000: im_func = '__func__' im_self = '__self__' else: im_func = 'im_func' im_self = 'im_self' def safeRef(target, onDelete = None): """Return a *safe* weak reference to a callable target ...
import unittest from urwid.compat import B import urwid class TextTest(unittest.TestCase): def setUp(self): self.t = urwid.Text("I walk the\ncity in the night") def test1_wrap(self): expected = [B(t) for t in "I walk the","city in ","the night "] got = self.t.render((10,))._text ...
from ....testing import assert_equal from ..svm import SVMTest def test_SVMTest_inputs(): input_map = dict(args=dict(argstr='%s', ), classout=dict(argstr='-classout', ), environ=dict(nohash=True, usedefault=True, ), ignore_exception=dict(nohash=True, usedefault=True, ), in_fi...
from __future__ import division, absolute_import, print_function import pytest from numpy import array from numpy.testing import assert_ from . import util class TestReturnCharacter(util.F2PyTest): def check_function(self, t): tname = t.__doc__.split()[0] if tname in ['t0', 't1', 's0', 's1']: ...
def migrate_up(manager): manager.execute('UPDATE users SET access_level = 0') def migrate_down(manager): pass
from openerp import models, api class account_statement_from_invoice_lines(models.TransientModel): """ Generate Entries by Statement from Invoices """ _inherit = "account.statement.from.invoice.lines" @api.multi def populate_statement(self): statement_id = self.env.context.get('statement...
from django.core.management.base import NoArgsCommand, CommandError from django.core.management.color import no_style from optparse import make_option class Command(NoArgsCommand): option_list = NoArgsCommand.option_list + ( make_option('--verbosity', action='store', dest='verbosity', default='1', ...
from .base import TestBase from ..core import OpCode from ..core import MemoryBuffer class TestCore(TestBase): def test_opcode(self): self.assertTrue(hasattr(OpCode, 'Ret')) self.assertTrue(isinstance(OpCode.Ret, OpCode)) self.assertEqual(OpCode.Ret.value, 1) op = OpCode.from_value(1...
import imports.parent class Child(imports.parent.Parent): pass
from packetbeat import BaseTest """ Tests for the pgsql's send_request and send_response options. """ class Test(BaseTest): def test_default_settings(self): """ Should not include request and response by default. """ self.render_config_template() self.run_packetbeat(p...
from django.core.urlresolvers import reverse from django import http from mox3.mox import IgnoreArg # noqa from mox3.mox import IsA # noqa from openstack_dashboard import api from openstack_dashboard.test import helpers as test IDPS_DETAIL_URL = reverse('horizon:identity:identity_providers:detail', ...
"""Makes sure that files include headers from allowed directories. Checks DEPS files in the source tree for rules, and applies those rules to "#include" commands in source files. Any source file including something not permitted by the DEPS files will fail. The format of the deps file: First you have the normal module-...
import warnings from . import PYQT5 from . import PYQT4 from . import PYSIDE from . import PYSIDE2 if PYQT5: from PyQt5.QtMultimedia import * elif PYSIDE2: from PySide2.QtMultimedia import * elif PYQT4: from PyQt4.QtMultimedia import * from PyQt4.QtGui import QSound elif PYSIDE: from PySide.QtMultim...
import base64 def main(req, res): return 404, [('Content-Type', 'image/png')], base64.decodestring("iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsQAAA7EAZUrDhsAAAAhSURBVDhPY3wro/KfgQLABKXJBqMGjBoAAqMGDLwBDAwAEsoCTFWunmQAAAAASUVORK5CYII=")
from __future__ import division __author__ = "Jai Ram Rideout" __copyright__ = "Copyright 2012, The QIIME project" __credits__ = ["Jai Ram Rideout", "Michael Dwan", "Logan Knecht", "Damien Coy", "Levi McCracken"] __license__ = "GPL" __version__ = "1.9.1-dev" __maintainer__ = "Jai Ram Rideout" __email__ =...
from __future__ import (absolute_import, division, print_function) __metaclass__ = type import sys import copy from ansible import constants as C from ansible.module_utils.iosxr import iosxr_provider_spec from ansible.plugins.action.normal import ActionModule as _ActionModule from ansible.module_utils.network_common im...
ANSIBLE_METADATA = {'status': ['preview'], 'supported_by': 'community', 'metadata_version': '1.1'} DOCUMENTATION = ''' --- module: elb_target short_description: Manage a target in a target group description: - Used to register or deregister a target in a target group version_...
""" Data migration creation command """ import sys import os import re from optparse import make_option try: set except NameError: from sets import Set as set from django.core.management.base import BaseCommand from django.core.management.color import no_style from django.db import models from django.conf impor...
from collections import namedtuple from functools import update_wrapper from threading import Lock _CacheInfo = namedtuple("CacheInfo", ["hits", "misses", "maxsize", "currsize"]) def lru_cache(maxsize=100, typed=False, on_eviction=lambda x:x): """Least-recently-used cache decorator. If *maxsize* is set to None, the...
from __future__ import absolute_import __all__ = ["PerMessageBzip2Mixin", "PerMessageBzip2Offer", "PerMessageBzip2OfferAccept", "PerMessageBzip2Response", "PerMessageBzip2ResponseAccept", "PerMessageBzip2"] import bz2 from autobahn.websocket.compress_base import Pe...
import datetime from key import Key from boto.utils import Password from boto.sdb.db.query import Query import re import boto import boto.s3.key from boto.sdb.db.blob import Blob class Property(object): data_type = str type_name = '' name = '' verbose_name = '' def __init__(self, verbose_name=None, ...
import unittest import logging import six import struct import inspect from nose.tools import ok_, eq_, nottest from ryu.ofproto import ether from ryu.lib.packet import packet from ryu.lib.packet import ethernet from ryu.lib.packet import lldp from ryu.lib import addrconv LOG = logging.getLogger(__name__) class TestLLD...
from gnuradio import gr, gr_unittest class test_stream_mux (gr_unittest.TestCase): def setUp (self): self.tb = gr.top_block () def tearDown (self): self.tb = None def help_stream_2ff(self, N, stream_sizes): v0 = gr.vector_source_f(N*[1,], False) v1 = gr.vector_source_f(N*[2,]...
import fnmatch import os import subprocess import itertools eightySharps = "################################################################################" def generateLicenseSection(filename): yield "############################ Copyrights and license ############################" yield "# ...
import httplib import logging from flask import request, current_app from pymongo.errors import OperationFailure from framework.transactions import utils, commands, messages LOCK_ERROR_CODE = httplib.BAD_REQUEST NO_AUTO_TRANSACTION_ATTR = '_no_auto_transaction' logger = logging.getLogger(__name__) def no_auto_transacti...
ANSIBLE_METADATA = {'metadata_version': '1.0', 'status': ['preview'], 'supported_by': 'community'} DOCUMENTATION = ''' --- module: nxos_snmp_host extends_documentation_fragment: nxos version_added: "2.2" short_description: Manages SNMP host configuration. description: - Manag...
""" Currency exchange rate support that comes from Yahoo Finance. For more details about this platform, please refer to the documentation at https://home-assistant.io/components/sensor.yahoo_finance/ """ import logging from datetime import timedelta import voluptuous as vol from homeassistant.components.sensor import P...
""" CCX Enrollment operations for use by Coach APIs. Does not include any access control, be sure to check access before calling. """ import logging from lms.djangoapps.ccx.models import CustomCourseForEdX log = logging.getLogger("edx.ccx") def get_ccx_from_ccx_locator(course_id): """ helper function to allow query...
from typing import NewType UserId = NewType("UserId", int)
""" Test functions for stats module WRITTEN BY LOUIS LUANGKESORN <lluang@yahoo.com> FOR THE STATS MODULE BASED ON WILKINSON'S STATISTICS QUIZ http://www.stanford.edu/~clint/bench/wilk.txt Additional tests by a host of SciPy developers. """ from __future__ import division, print_function, absolute_import...
""" Default settings for zebra """ import datetime import os from django.conf import settings as _settings if hasattr(_settings, 'STRIPE_PUBLISHABLE'): STRIPE_PUBLISHABLE = getattr(_settings, 'STRIPE_PUBLISHABLE') else: try: STRIPE_PUBLISHABLE = os.environ['STRIPE_PUBLISHABLE'] except KeyError: ...
""" Acceptance tests for the Import and Export pages """ from abc import abstractmethod from bok_choy.promise import EmptyPromise from datetime import datetime from .base_studio_test import StudioLibraryTest, StudioCourseTest from ...fixtures.course import XBlockFixtureDesc from ...pages.studio.import_export import Exp...
""" Slyd test settings Imports slyd settings and adds necessary overrides for test setup """ from slyd.settings import * LOG_LEVEL = 'DEBUG' HTTPCACHE_ENABLED = False RESOURCE_DIR = join(dirname(__file__), 'resources') DATA_DIR = join(RESOURCE_DIR, 'data') SPEC_DATA_DIR = join(DATA_DIR, 'projects')
import datetime import ftplib import os from helpers import unittest try: from cStringIO import StringIO except ImportError: from io import StringIO from luigi.contrib.ftp import RemoteFileSystem, RemoteTarget FILE1 = """this is file1""" FILE2 = """this is file2""" FILE3 = """this is file3""" HOST = "some_host"...
import os import subprocess from django.test import TestCase from django_dynamic_fixture import get from django_dynamic_fixture import fixture import mock from readthedocs.projects.models import Project from readthedocs.doc_builder.environments import LocalEnvironment from readthedocs.doc_builder.loader import get_buil...
RELEASE_LEVELS = [ALPHA, BETA, RELEASE_CANDIDATE, FINAL] = ['alpha', 'beta', 'candidate', 'final'] RELEASE_LEVELS_DISPLAY = {ALPHA: ALPHA, BETA: BETA, RELEASE_CANDIDATE: 'rc', FINAL: ''} version_info = (8, 0, 0, FINAL, 0) version = '.'.join(m...
ANSIBLE_METADATA = {'metadata_version': '1.0', 'status': ['stableinterface'], 'supported_by': 'curated'} DOCUMENTATION = """ --- module: sqs_queue short_description: Creates or deletes AWS SQS queues. description: - Create or delete AWS SQS queues. - Update attributes on exis...
from tempest.api.compute import base from tempest import test class ServerPasswordTestJSON(base.BaseV2ComputeTest): @classmethod def setup_clients(cls): super(ServerPasswordTestJSON, cls).setup_clients() cls.client = cls.servers_client @classmethod def resource_setup(cls): super(...
from django.conf.urls import patterns, url from . import views urlpatterns = patterns( '', url('^login/cancelled/$', views.login_cancelled, name='socialaccount_login_cancelled'), url('^login/error/$', views.login_error, name='socialaccount_login_error'), url('^signup/$', views.signup, name='soci...
from odoo import api, fields, models, _ from odoo.addons import decimal_precision as dp class MrpSubProduct(models.Model): _name = 'mrp.subproduct' _description = 'Byproduct' product_id = fields.Many2one('product.product', 'Product', required=True) product_qty = fields.Float( 'Product Qty', ...
from __future__ import with_statement import base64 import os import binascii from xml.etree.ElementTree import Element, SubElement from libcloud.utils.py3 import PY3 from libcloud.utils.py3 import httplib from libcloud.utils.py3 import urlquote from libcloud.utils.py3 import tostring from libcloud.utils.py3 import b f...
from .samples import ExpDecayingSample from .moving_average import ExpWeightedMovingAvg from .snapshot import Snapshot
""" ================================= Compare BIRCH and MiniBatchKMeans ================================= This example compares the timing of Birch (with and without the global clustering step) and MiniBatchKMeans on a synthetic dataset having 100,000 samples and 2 features generated using make_blobs. If ``n_clusters``...
from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'community'} DOCUMENTATION = ''' --- module: ec2_win_password short_description: gets the default administra...
"""Basic tests for the cherrypy.Request object.""" import os localDir = os.path.dirname(__file__) import sys import types from cherrypy._cpcompat import IncompleteRead, ntob, ntou, unicodestr import cherrypy from cherrypy import _cptools, tools from cherrypy.lib import httputil defined_http_methods = ("OPTIONS", "GET",...
from PIL import Image from PIL import ImageFont from PIL import ImageDraw """ make an image's white part to be transparent for merging with another image """ def white_to_transparent(img): img = img.convert('RGBA') datas = img.getdata() newData=[] for item in datas: if item[0] == 255 and item[1] == 255 and item[2...
from lxml import objectify import urlparse import openerp from openerp.addons.payment.models.payment_acquirer import ValidationError from openerp.addons.payment.tests.common import PaymentAcquirerCommon from openerp.addons.payment_buckaroo.controllers.main import BuckarooController from openerp.tools import mute_logger...
from Tkinter import * class notebook(object): def __init__(self, master, side=LEFT): self.active_fr = None self.count = 0 self.choice = IntVar(0) if side in (TOP, BOTTOM): self.side = LEFT else: self.side = TOP self.rb_fr = Frame(master, borderwidth=2, relief=GROOVE) self.rb_fr.pack(side=side, fill=BO...
import glob from optparse import make_option # noqa import os from django.core.management.base import CommandError # noqa from django.core.management.templates import TemplateCommand # noqa from django.utils.importlib import import_module # noqa import horizon class Command(TemplateCommand): args = "[name] [das...
from kivy.adapters.dictadapter import DictAdapter from kivy.uix.listview import ListItemButton, ListItemLabel, \ CompositeListItem, ListView from kivy.uix.gridlayout import GridLayout from fixtures import integers_dict class MainView(GridLayout): '''Uses :class:`CompositeListItem` for list item views compri...
DOCUMENTATION = ''' --- module: urpmi short_description: Urpmi manager description: - Manages packages with I(urpmi) (such as for Mageia or Mandriva) version_added: "1.3.4" options: pkg: description: - name of package to install, upgrade or remove. required: true default: null state: descrip...
import six import unittest import warnings from scrapy.settings import Settings, SettingsAttribute, CrawlerSettings from tests import mock from . import default_settings class SettingsAttributeTest(unittest.TestCase): def setUp(self): self.attribute = SettingsAttribute('value', 10) def test_set_greater_...
from openerp.osv import fields, osv class product_category(osv.osv): _inherit = "product.category" _columns = { 'property_account_income_categ': fields.property( type='many2one', relation='account.account', string="Income Account", help="This account will ...
from sympy import TableForm, S from sympy.printing.latex import latex from sympy.abc import x from sympy.functions.elementary.miscellaneous import sqrt from sympy.functions.elementary.trigonometric import sin from sympy.utilities.pytest import raises from textwrap import dedent def test_TableForm(): s = str(TableFo...
""" mbed SDK Copyright (c) 2011-2013 ARM Limited 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 required by applicable law or agreed to in writi...
"""This module defines the data structures used to represent a grammar. These are a bit arcane because they are derived from the data structures used by Python's 'pgen' parser generator. There's also a table here mapping operators to their names in the token module; the Python tokenize module reports all operators as t...
import os import sys from setuptools import setup VERSION = '0.1.0' if sys.argv[-1] in ['test', 'publish']: import doctest if doctest.testfile('README.md', verbose=True).failed: sys.exit() if sys.argv[-1] == 'publish': os.system('python setup.py sdist upload') sys.exit() setup( n...
class FooService(object): def __init__(self, dep1): self.dep1 = dep1 def action(self): return self.dep1.action() class BarService(object): def __init__(self, dep1, dep2): self.dep1 = dep1 self.dep2 = dep2 def action1(self): return self.dep1.action() def action...
from django.template import TemplateSyntaxError from django.template.loader import get_template from django.test import RequestFactory, SimpleTestCase, TestCase from django.core.urlresolvers import reverse from django.utils.safestring import mark_safe class HtmlTagNodeTest(SimpleTestCase): SAMPLE_CONTENT = 'Lorem i...
import json from yagocd.resources import Base, BaseManager from yagocd.resources.job import JobInstance from yagocd.util import since @since('15.2.0') class AgentManager(BaseManager): """ The agents API allows users with administrator role to manage agents. `Official documentation. <https://api.go.cd/curren...
__version__ = '3.5.2.post1' if __name__ != '__main__': try: __import__('pkg_resources').declare_namespace(__name__) except ImportError: __path__ = __import__('pkgutil').extend_path(__path__, __name__)
import copy import unittest from ecmcli.commands import base, remote class ConfigData(unittest.TestCase): def test_todict_noconv(self): for x in ({}, 0, None, 1, "", True, False, 0.0, -1, -1.1, 1.1, {1: 1}): self.assertEqual(base.todict(x), copy.deepcopy(x)) def test_todict_nesting(self): ...
"""CAS authentication middleware""" from urllib import urlencode from django.conf import settings from django.contrib.auth import REDIRECT_FIELD_NAME from django.contrib.auth import logout as do_logout from django.contrib.auth.views import login, logout from django.core.urlresolvers import reverse from django.http impo...
from jsonrpc import ServiceProxy access = ServiceProxy("http://127.0.0.1:9932") pwd = raw_input("Enter old wallet passphrase: ") pwd2 = raw_input("Enter new wallet passphrase: ") access.walletpassphrasechange(pwd, pwd2)
def count_substring(string, sub_string): return len([i for i in range(len(string)) if string[i:].startswith(sub_string)]) if __name__ == '__main__': string = input().strip() sub_string = input().strip() count = count_substring(string, sub_string) print(count)
from flask import * from app import app @app.route('/') @app.route('/index') def index(): return render_template('index.html', title='Home') @app.route('/blog') def blog(): return render_template('blog.html', title='Blog') @app.route('/culture') def culture(): return render_template('culture.html', title=...
print __name__ # Should be __main__ temp = list def list(): return "this function works" list_object = list() print list_object list = temp list_object = list() print list_object tmp = True True = False whatami = True print whatami True = tmp # need to restore print dict print dict() def night_stalker(scythe_versio...
import os import sys from os.path import join import logging import logging.handlers import warnings from functools import partial from heisen.config import settings from heisen.core.log import filters from heisen.core.log import exceptions from heisen.core.log import external class Logger(object): def __init__(sel...
import logging from spockbot.mcdata import blocks from spockbot.plugins.base import pl_announce, PluginBase from spockbot.plugins.tools.event import EVENT_UNREGISTER from spockbot.vector import Vector3 logger = logging.getLogger('spockbot') @pl_announce('BlockFinder') class BlockFinderPlugin(PluginBase): requires =...
import os import warnings class Profile(object): ''' base Profile class ''' def __init__(self, name, version, title, url, namespace, typename, outputschema, prefixes, model, core_namespaces, added_namespaces,repository): ''' Initialize profile ''' self.name = name self.version = ...
import os import sys import re import shutil import logging import argparse import inspect from enum import Enum from .sys import check_exe, printv logger = logging.getLogger(__name__) def display_open(file): """Print the syntax to open a file based on the platform.""" if sys.platform == 'linux': printv...
'''MIT License Copyright (c) {year} {author} 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 Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distr...
from models.move import Move class MiniMaxAlfaBeta(object): def __init__(self, max_depth): self.chosen_move = None self.max_depth = max_depth def mini_max_alfa_beta(self, board, depth, color, parent_alfa, parent_beta, max_gamer, heuristic_function): """ """ valid_moves = ...