code
stringlengths
1
199k
import sys import os import time ROOT_PATH = "/home/b/VisualSearch1" COLLECTION_TO_SIZE = { 'tentagv10dev':1382290, 'tentagv10val':100000, 'tentagv10test':477486 } # Not used one: {'tentagv10train':1482290, 'tentagv10':1959776 } COLLECTION_TO_NumberOfConcept = {'web13devel':95,'web13test':116,'tentagv10dev':10,'tentag...
import sys import itertools from .control import TaskControl from .filewatch import FileModifyWatcher from .cmd_base import DoitCmdBase from .cmd_run import opt_verbosity, Run def _auto_watch(task_list, filter_tasks): """return list of tasks and files that need to be watched by auto cmd""" this_list = [t.clone(...
import gensim import numpy as np import string from keras import backend from keras.layers import Conv1D, Dense, Input, Lambda, LSTM from keras.layers.merge import concatenate from keras.layers.embeddings import Embedding from keras.models import Model word2vec = gensim.models.Word2Vec.load("word2vec.gensim") embedding...
import os import sys sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), "python-bitcoinrpc")) from decimal import Decimal, ROUND_DOWN import json import random import shutil import subprocess import time import re from bitcoinrpc.authproxy import AuthServiceProxy, JSONRPCException from util import...
""" This module performs simulated annealing to find a state of a system that minimizes its energy. An example program demonstrates simulated annealing with a traveling salesman problem to find the shortest route to visit the twenty largest cities in the United States. Notes: Matt Perry 6/24/12 Changed to s...
""" Configuration module for RO manager tests """ __author__ = "Graham Klyne (GK@ACM.ORG)" __copyright__ = "Copyright 2011-2013, University of Oxford" __license__ = "MIT (http://opensource.org/licenses/MIT)" from rocommand import ro_settings class ro_test_config: CONFIGDIR = "config" ROBASEDIR ...
from persimmon.view.blocks.block import Block from persimmon.view.pins import OutputPin from kivy.properties import ObjectProperty, StringProperty from kivy.lang import Builder Builder.load_file('persimmon/view/blocks/dictblock.kv') class DictBlock(Block): dict_out = ObjectProperty() string_in = StringProperty(...
import logging, glob, re, click from sqlalchemy import create_engine, Column, Integer, String from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker from sqlalchemy import distinct from openpyxl import load_workbook from xlrd import * Column = Column Integer = Integer String = S...
from nlpia.data.loaders import get_data from nltk.tokenize import casual_tokenize import pandas as pd import numpy as np import os from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.decomposition import PCA from nlpia.constants import DATA_PATH NUM_TOPICS = 3 NUM_WORDS = 6 NUM_DOCS = NUM_PRETTY = ...
import sys,os keywords = ['PLPS_path', 'PDB2PQR_path', 'APBS_path', 'XLOGP3_path', 'ligand_file', 'BABEL_path',\ 'n_conf', 'OMEGA_path'] def read_input(input_file): file = open(input_file, 'r') lig_file = [] for line in file: key = line.split()[0] if(key == keywords[0]): ...
from collections import OrderedDict class Container(OrderedDict): """ Generic data holder. Used for functional relations, meaning that for each key there is one value. The Container may be used for both building and parsing. """ def __init__(self, *args, **kwds): self.xml_attrib = kwds.p...
from core.himesis import Himesis, HimesisPreConditionPatternLHS import cPickle as pickle from uuid import UUID class HPar2ProcsPart2_CompleteLHS(HimesisPreConditionPatternLHS): def __init__(self): """ Creates the himesis graph representing the AToM3 model HPar2ProcsPart2_CompleteLHS. """ ...
import discord import asyncio import urllib.request #importing modules used import json import re import random fp_osuapikey = open("apikey.txt", "r") osuapikey = fp_osuapikey.read() #reading personal osu apikey from apikey.txt fp_osuapikey.close() @asyncio.coroutine def runComm(msg, client): if msg.content.sta...
import seek DOMAIN = "seek-165508.appspot.com" start = seek.StartModule('<p> You\'ll be tasked with finding an item and taking a picture of it four times. Are you ready? </p>', 'image0') items = [seek.FindObjectModule('image' + str(i), 'image' + str((i+1)%4), ['drink','computer keyboard','computer','outerwear'][i]) for...
""" Django settings for dqc_django project. Generated by 'django-admin startproject' using Django 1.9.4. For more information on this file, see https://docs.djangoproject.com/en/1.9/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.9/ref/settings/ """ import os BAS...
from .runner import Runner
"""项目文档创建,编译等,使用sphinx.""" import os import http.server import socketserver import subprocess from typing import Dict, Any, Optional import chardet from pmfp.utils import find_project_name_path from pmfp.const import PROJECT_HOME def _update_doc(config: Dict[str, Any]) -> Optional[bool]: """更新文档. Args: ...
from django.db import models class Speaker(models.Model): """ Representing the speaker of a word """ first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) def __unicode__(self): return self.first_name + ' ' + self.last_name def __str__(self): ...
import os import matplotlib.pyplot as plt import matplotlib.ticker as plticker import numpy as np def plot_uniform(x_minimum, x_maximum, tick_interval): x = range(x_minimum, x_maximum + 1) # TODO: Using x_maximum and x_minimum, calculate the height of the # rectangle that represents the uniform probability ...
from __future__ import unicode_literals import django.contrib.auth.models from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('auth', '0008_alter_user_username_max_length'), ('students', '0002_grade'), ] operation...
from gw2api.objects.base_object import BaseAPIObject class BaseAPIv2Object(BaseAPIObject): """Extends the base API handler to automatically handle pagination and id parameters""" def get(self, **kwargs): return super().get(id=kwargs.get('id'), ids=kwargs.get('ids'), ...
''' >>> StoryWithBlueColorsToErrors.run() False >>> blue_colored(""" Then it will be blue ... ERROR ... """) in output.getvalue() True >>> blue_colored(""" ... Errors: ... """) in output.getvalue() True >>> error_msg = """ File "%s", line ..., in do_error ... ...
from django.conf.urls import url from posts.api import * urlpatterns = [ url(r'^$', PostListAPIView.as_view(), name="api"), url(r'^post/(?P<slug>\w+)/$', PostCommentListCreateAPIView.as_view(), name="api"), ]
import requests print(requests)
import time import pymongo from django.conf import settings from apps.rss_feeds.models import MStory, Feed db = settings.MONGODB batch = 0 start = 0 for f in xrange(start, Feed.objects.latest('pk').pk): if f < batch*100000: continue start = time.time() try: cp1 = time.time() - start # if fee...
def goat_latin(ip): ans = [] vowels = ['e', 'i', 'a', 'o', 'u'] for id, i in enumerate(ip.split(' ')): word = "" if i[0].lower() in vowels: word += i else: word += i[1:]+i[0] word += "ma" word += 'a'*(id+1) ans.append(word) return '...
__all__ = [ 'Command', 'LateTask', 'PageCompiler', 'Task', 'TemplateSystem' ] from yapsy.IPlugin import IPlugin from doit.cmd_base import Command as DoitCommand class BasePlugin(IPlugin): """Base plugin class.""" def set_site(self, site): """Sets site, which is a Nikola instance.""" ...
import argparse import datetime DEFAULT_SINCE = ( datetime.datetime.utcnow() - datetime.timedelta(days=30) ).isoformat() + 'Z' def kvpair(string): return string.strip().split('=', 1) def stringified_dict(indict): return dict( ((str(key), str(value)) for key, value in indict.items()) ) class Help...
"""Subcommands with main program arguments In this test case, we test a parser that has its own arguments as well as multiple subcommands, for which individual help sections should be generated. """ import argparse import sys foo_help = "Run the ``foo`` subprogram" foo_desc = """This is a long description of what a ``f...
from queue import Empty as EmptyQueueException #@UnresolvedImport from afqueue.common.exception_formatter import ExceptionFormatter #@UnresolvedImport from afqueue.common.socket_wrapper import SocketWrapper #@UnresolvedImport from afqueue.messages import system_messages #@UnresolvedImport import afqueue.messages.messag...
__all__ = ["DNSQuery", "IPFilter", "CertVerify", "ICMPEcho", "HttpDelay"] from .crawler import DNSQuery from .evaluate import CertVerify, ICMPEcho, HttpDelay from .filter import IPFilter
import requests import os import csv from ..models import Airport from .. import BasicAPI ENDPOINT_URL = "https://sourceforge.net/p/openflights/code/HEAD/tree/openflights/data/airports.dat?format=raw" APP_DIR = os.path.normpath(os.path.join(os.path.dirname(os.path.realpath(__file__)), '..', '..')) class OpenFlights(Bas...
import stripe stripe.api_key = "sk_test_rgfft426e22w2mw2m2" stripe.Customer.create( source= "tok_1OgIlDSDDSFFaaKPesPD", plan=103, email="payinguser@example.com" )
"""History Model""" from __future__ import (absolute_import, print_function, division, unicode_literals) from ..models.base import Model from ..models.trial import Trial from .graphs.history_graph import HistoryGraph class History(Model): """This model represents the workflow evolution histo...
try: paraview.simple except: from paraview.simple import * paraview.simple._DisableFirstRenderCameraReset() lid_1_vtk = LegacyVTKReader( FileNames=['lid_1.vtk'] ) RenderView1 = GetRenderView() CellDatatoPointData1 = CellDatatoPointData() SetActiveSource(lid_1_vtk) DataRepresentation1 = Show() DataRepresentation1.Repres...
'''MIT License Copyright (c) 2017 Kumar Rishabh 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, di...
from pymoku import Moku, ValueOutOfRangeException from pymoku.instruments import * import time, logging import matplotlib import matplotlib.pyplot as plt logging.basicConfig(format='%(asctime)s:%(name)s:%(levelname)s::%(message)s') logging.getLogger('pymoku').setLevel(logging.DEBUG) m = Moku.get_by_name("example") i = ...
from __future__ import unicode_literals from .abc import ( ABCIE, ABCIViewIE, ) from .abcnews import ( AbcNewsIE, AbcNewsVideoIE, ) from .abcotvs import ( ABCOTVSIE, ABCOTVSClipsIE, ) from .academicearth import AcademicEarthCourseIE from .acast import ( ACastIE, ACastChannelIE, ) from .a...
""" Copyright (c) 2017-2022, Jairus Martin. Distributed under the terms of the MIT License. The full license is in the file LICENSE, distributed with this software. Created on Sept 5, 2017 @author: jrm """ from atom.api import List from .android_content import Context, SystemService from .app import AndroidApplication ...
"""Main module for the application.""" import os import logging import base64 import binascii from flask import Flask, g from flask_bcrypt import Bcrypt from flask_login import current_user, LoginManager from flask_wtf.csrf import CSRFProtect from flask_sqlalchemy import SQLAlchemy from sqlalchemy.exc import Operationa...
from __future__ import unicode_literals, division, absolute_import from builtins import * # noqa pylint: disable=unused-import, redefined-builtin import logging from flexget import plugin from flexget.event import event from flexget.plugin import PluginWarning from requests.exceptions import RequestException from flex...
from database import db class Issues(db.Model): id = db.Column('issue_id', db.Integer, primary_key=True) issue = db.Column(db.String(20)) evektor = db.Column(db.Boolean(), default=False) description = db.Column(db.Text) details = db.Column(db.Text) author = db.Column(db.String(20)) date_issu...
__test__ = False simple = ( 'file1.txt', 'file2.py', 'file3.js', ('empty_dir',), ('dir', ('file4.txt',)) ) pyproj = ( ('.hg', ('hgfile',)), ('.hiddendir', ('file',)), ('_ignoredir', ('file',)), ('_buildout', ('parts.cfg',)), ('cpnts', (('base', ('__init__.py', ...
"""Device, context and memory management on CuPy. Chainer uses CuPy (with very thin wrapper) to exploit the speed of GPU computation. Following modules and classes are imported to :mod:`cuda` module for convenience (refer to this table when reading chainer's source codes). ============================ =================...
import numpy as np from numpy import nan as NA import pandas as pd data = pd.DataFrame({'k1': ['one', 'two'] * 3 + ['two'], 'k2': [1, 1, 2, 3, 3, 4, 4]}) data data.duplicated() data.drop_duplicates() data['v1'] = range(7) data.drop_duplicates(['k1']) data.drop_duplicates(['k1', 'k2']) data.drop_duplicates(['k1', 'k2'],...
from django.views.decorators.csrf import csrf_exempt from django.contrib.auth import authenticate, login from django.contrib.auth.decorators import login_required, permission_required from django.shortcuts import render_to_response, get_object_or_404 from django.http import HttpResponse, HttpResponseRedirect from djang...
from core.himesis import Himesis class HeannotationlefteAnnotationsSolveRefEAnnotationEAnnotationEAnnotationEAnnotation(Himesis): def __init__(self): """ Creates the himesis graph representing the AToM3 model HeannotationlefteAnnotationsSolveRefEAnnotationEAnnotationEAnnotationEAnnotation. "...
import os import subprocess import sys def run_cmd(cmd, stdin_data=None): p = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True) stdout = "" stderr = "" ...
import cgt from cgt import nn from cgt.distributions import categorical import numpy as np from example_utils import fmt_row, fetch_dataset import time, sys def init_weights(*shape): wval = np.random.randn(*shape) * 0.01 ww = cgt.shared(wval, fixed_shape_mask='all') return ww def rmsprop_updates(cost, param...
__author__ = "Cyril Jaquier" __version__ = "$Revision: 703 $" __date__ = "$Date: 2008-07-17 23:28:51 +0200 (Thu, 17 Jul 2008) $" __copyright__ = "Copyright (c) 2004 Cyril Jaquier" __license__ = "GPL" version = "0.8.3"
try: import unittest2 as unittest except ImportError: import unittest import logging import time import os from wia import Wia from wia.error import WiaError, WiaValidationError, WiaUnauthorisedError, WiaForbiddenError, WiaNotFoundError class LocationsTest(unittest.TestCase): def test_locations_publish_rest...
import unittest from backlight import Brightness, BrightnessDevice, BrightnessDevicePercentage class TestBrightness(unittest.TestCase): brightness = Brightness() delta = 10 def setUp(self): self.v = self.brightness.get() def tearDown(self): self.brightness.set(self.v) def test_set(se...
from django.conf import settings from django.contrib import messages from django.core import mail from django.http import HttpResponseRedirect, Http404 from django.shortcuts import render from django.template.loader import render_to_string from eventex.subscriptions.forms import SubscriptionForm from eventex.subscripti...
""" plug.py ~~~~~~~ Module for communicating with smart plugs """ from abc import abstractmethod import broadlink from pyvesync import VeSync from home.iot.power import Power PORT = 80 class Plug(Power): widget = { 'buttons': ( { 'text': 'On', 'method': 'on' ...
from hwt.interfaces.std import VectSignal from hwt.interfaces.utils import addClkRstn from hwt.simulator.simTestCase import SimTestCase from hwt.synthesizer.unit import Unit from hwt.synthesizer.vectorUtils import fitTo from pyMathBitPrecise.bit_utils import mask from hwtSimApi.constants import CLK_PERIOD class WidthCa...
""" Utility functions related to the djstripe app. """ import datetime from typing import Optional import stripe from django.conf import settings from django.db.models.query import QuerySet from django.utils import timezone def get_supported_currency_choices(api_key): """ Pull a stripe account's supported curre...
from AccessControl import ClassSecurityInfo from Products.ATExtensions.ateapi import RecordsField from bika.lims.browser.widgets import RecordsWidget from Products.Archetypes.public import * from Products.Archetypes.references import HoldingReference from Products.CMFCore.permissions import View, ModifyPortalContent fr...
from .instances_resource import ( InstancesResource ) __all__ = [ "InstancesResource" ]
from bson.objectid import ObjectId class DiffStorage: def __init__(self, coll, diff_fields, sort_field): self.coll = coll self.diff_fields = diff_fields self.sort = [(sort_field, -1)] def get_by_id(self, oid): return self.coll.find_one({'_id': ObjectId(oid)}) def get(self, **...
from django.conf import settings from .models import Application, Flavor def meta_software(request): try: application = Application.objects.get(id=settings.APPLICATION_ID) flavor = Flavor.objects.get(id=settings.FLAVOR_ID, application=application) except (Application.DoesNotExist, Flavor.DoesNot...
import os module_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)))
import os import sys PROJECT_PATH = os.path.abspath(os.path.dirname(__file__)) sys.path.append(os.path.join(PROJECT_PATH, '..')) from todoSettings import Settings settings = Settings([ os.path.join(PROJECT_PATH, '..', 'config', 'settings.config'), os.path.join(PROJECT_PATH, '..', 'config', 'userpass.config'), ...
__author__ = 'tiso' import sys import random from prime_num import generate_prime, miller_rabin_test, Zpow, AlgEvklid from socket import * def primitve_root_mod_n(num): ''' only for prime numbers :return: primitive root ''' phi = num - 1 n = phi fact = [] i = 2 while (i*i <= n): ...
"""Run a bcbio-nextgen analysis inside of an isolated docker container. """ from __future__ import print_function import os import pwd import uuid import sys import yaml from bcbio import log from bcbiovm.docker import manage, mounts, remap from bcbiovm.ship import reconstitute def do_analysis(args, dockerconf): ""...
import cStringIO as StringIO import cv2 import picamera import numpy as np import time import datetime import os import sys import subprocess PIC_DIR = "/home/pi/fotos/" log_filename = "/home/pi/motion_log" def shoot_pics(number, resolution, delay_sec): resolution_init = camera.resolution camera.resolution = resoluti...
def main(): a = float(raw_input()) b = float(raw_input()) average = (a * 3.5 + b * 7.5) / 11 print 'MEDIA = {:.5f}'.format(average) if __name__ == '__main__': main()
__author__ = 'matt' import json import unittest from apiUtils import APIUtils import spotipy import spotipy.util as util scope = 'playlist-modify-public' class APIUtilsUnittests(unittest.TestCase): def test_spotify_api_info(self): apiUtils = APIUtils() apiInfo = json.load(open('src/data/API_info')) ...
from acceptanceutils import surjection import string import random one = ([1], 1) two = ([1, 2], 2) three = ([1, 2, 3], 3) three_none = (three[0], None) three_item_group = (one, two, three, three_none) ten_item_group = ([0]*10, 1) so = surjection.surjective_options class TestSurjectiveOptions(object): three_lis = l...
import logging logging.getLogger("requests").setLevel(logging.WARNING) logger = logging.getLogger() def initialize(level: str=None) -> logging.Logger: global logger if level: level = logging.getLevelName(level.upper()) else: level = logging.DEBUG kwargs = {"level": level, "format": "[%(l...
from masher.generators import CompositeGenerator from masher.generators import ListGenerator from masher.generators import ConstantGenerator from masher.generators import PhraseGenerator from masher.generators import RandomChanceGenerator from masher.exceptions import WordMasherParseException class ConstantRule: de...
import urllib.request import time from xml.etree.ElementTree import parse candidates = ['4389', '4379'] daves_latitude = 41.980262 def distance(lat1, lat2): return 69*abs(lat1-lat2) def monitor(): u = urllib.request.urlopen('http://ctabustracker.com/bustime/map/getBusesForRoute.jsp?route=22') doc = parse(u)...
def user_to_dict(user): ud = user.userdata[-1] return dict(date=ud.date, teamvalue=ud.teamvalue, money=ud.money, maxbid=ud.maxbid, totalpoints=ud.points, num_players=user.owns.count()) def get_week_month_prices(prices): prices_length = prices.count() if prices_length >= 30: month...
from tests.integration.components.mutually_exclusive.schema_urls import MUTUALLY_EXCLUSIVE_DURATION from tests.integration.integration_test_case import IntegrationTestCase class TestDurationSingleCheckboxOverride(IntegrationTestCase): """ Tests to ensure that the server-side validation for mutually exclusive du...
from ..cw_model import CWModel class ProjectTeamMember(CWModel): def __init__(self, json_dict=None): self.id = None # (Integer) self.projectId = None # (Integer) self.hours = None # (Number) self.member = None # *(MemberReference) self.projectRole = None # *(ProjectRoleR...
from lintreview.review import Problems from lintreview.review import Comment from lintreview.tools.checkstyle import Checkstyle from lintreview.utils import in_path from unittest import TestCase from unittest import skipIf from nose.tools import eq_, assert_in checkstyle_missing = not(in_path('checkstyle')) class TestC...
import sys lines = open(sys.argv[1], 'r') for line in lines: line = line.replace('\n', '').replace('\r', '') if len(line) > 0: number = int(line) roman = '' if number >= 1000: roman = roman + 'M' * (number / 1000) number = number - (1000 * (number / 1000)) ...
from django.conf.urls import url from . import views urlpatterns = [ url(r'^companies/all/$', views.AllCompaniesView.as_view()), url(r'^companies/(?P<pk>\d+)/$', views.SingleCompanyView.as_view()), url(r'^companies/(?P<name>[\w\s-]+)/$', views.SingleByNameCompanyView.as_view()), url(r'^products/(?P<pk>\...
from .. import Provider as PhoneNumberProvider class Provider(PhoneNumberProvider): formats = ( '+36 ## ###-####', '(06)##/###-####', '(##)/###-####', '##/###-####', '##/### ####', '06-#/### ####', '06-##/### ####', )
from django import template from easy_thumbnails.files import get_thumbnailer register = template.Library() @register.simple_tag(takes_context=True) def get_fb_image(context): fb_image = None # header image? request = context['request'] current_page = getattr(request, 'current_page', None) if curren...
from __future__ import print_function from __future__ import absolute_import from builtins import zip from builtins import str from builtins import range from lxml import etree import sys import os.path from . import data_prep_utils import re import csv from argparse import ArgumentParser from collections import Ordere...
import pytest provider = "victorops" class TestVicrotops: """ Victorops rest alert tests Online test rely on setting the env variable VICTOROPS_REST_URL """ @pytest.mark.skip("Skipping until obtaining a permanent key") @pytest.mark.online def test_all_options(self, provider): data = ...
''' Widget class ============ The :class:`Widget` class is the base class required for creating Widgets. This widget class was designed with a couple of principles in mind: * *Event Driven* Widget interaction is built on top of events that occur. If a property changes, the widget can respond to the change in the 'o...
class Gamestate: """def __init__(self, pilots = [], aces = [], campaign, series, mission, kill_points = 0, victory_points = 0, promotion_points = 0, promotion_point_limit = None, prev_date = None, prev_kills = 0, wingman_prev_kills = 0, medal_awarding = None, ejection_count = 0): self.pilots = pilots self.aces = a...
class Solution(): def climbStairs(self, n): """ :type n: int :rtype: int """ dp = [1 for i in range(n+1)] for i in range(2, n+1): dp[i] = dp[i-1] + dp[i-2] return dp[n] class Solution1: """ @param n: An integer @return: An integer "...
import datetime from django import template register = template.Library() @register.simple_tag(name="assigned_css_class") def simple_assigned_css_class(assigned_to, user, status): if (assigned_to): if assigned_to == user and status == 'IP': css_class = 'in-progress' elif assigned_to == u...
from django.db import models from six import python_2_unicode_compatible @python_2_unicode_compatible class TModel(models.Model): name = models.CharField(max_length=200) test = models.OneToOneField( 'self', models.CASCADE, null=True, blank=True, related_name='related_test...
""" Created on Wed May 25 15:37:43 2016 @author: mtkessel """ import queue as Q import serial import threading import time import weakref class LLAP(serial.Serial): """Lightweight Local Automation Protocol (LLAP) defines a small device protocol that balances simplicity and human readability. The class...
"""distutils.command.bdist_rpm Implements the Distutils 'bdist_rpm' command (create RPM source and binary distributions).""" __revision__ = "$Id: bdist_rpm.py 70096 2009-03-02 05:41:25Z tarek.ziade $" import sys, os from distutils.core import Command from distutils.debug import DEBUG from distutils.util import get_plat...
import sys, os extensions = [] templates_path = ['_templates'] source_suffix = '.rst' master_doc = 'index' project = u'django-pipeline' copyright = u'2011-2012, Timothée Peignier' version = '1.2.2.1' release = '1.2.2.1' exclude_patterns = ['_build'] pygments_style = 'sphinx' html_theme = 'default' htmlhelp_basename = '...
def foo(ip,port,sockobj, ch,mainch): data = sockobj.recv(4096) if data != "Hello": print 'Error: data did not match "Hello"' exitall() sockobj.send("bye") stopcomm(mainch) stopcomm(ch) if callfunc == 'initialize': ip = getmyip() waitforconn(ip,<connport>,foo) sleep(.1) sockobj = openconn(ip,<c...
class User(): def __init__(self, first_name, last_name, birthday, sex): self.first_name = first_name self.last_name = last_name self.birthday = birthday self.sex = sex def describe_user(self): print('first name: ' + self.first_name + '\nlast name: ' + self.l...
class Point: def __init__(self, x, y): ''' 棋盤座標和像素座標轉換 ''' self.x = x self.y = y self.pixel_x = 30 + 30 * self.x self.pixel_y = 30 + 30 * self.y
import _plotly_utils.basevalidators class SizeValidator(_plotly_utils.basevalidators.NumberValidator): def __init__( self, plotly_name="size", parent_name="icicle.pathbar.textfont", **kwargs ): super(SizeValidator, self).__init__( plotly_name=plotly_name, parent_name=pare...
import os import glob with_setuptools = False if 'USE_SETUPTOOLS' in os.environ or 'pip' in __file__ or 'easy_install' in __file__: try: from setuptools.command.install import install from setuptools import setup from setuptools import Extension from setuptools.command.build_ext import build_ext w...
import functools from typing import Any, Callable, Dict, Generic, List, Optional, TypeVar import warnings from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error from azure.core.pipeline import PipelineResponse from azure.core.pipeline.transp...
import unittest from mbleven import compare class TestFastComp(unittest.TestCase): def test_equal(self): self.assertEqual(compare('abc', 'abc'), 0) def test_insert(self): self.assertEqual(compare('abc', 'xabc'), 1) self.assertEqual(compare('abc', 'axbc'), 1) self.assertEqual(comp...
from nose.tools import * import osha def setup(): print "SETUP!" def teardown(): print "TEAR DOWN!" def test_basic(): print "I RAN!"
import ckanclient ckan = ckanclient.CkanClient('http://catalog.data.gov/api/3') search_params = { 'fq': 'res_format:WMS', 'rows': 10 } d = ckan.action('package_search', **search_params) print d['count'] for rec in d['results']: print rec['title'] search_params = { 'q': 'mvco', 'fq': 'res_format:WMS'...
import functools from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar, Union import warnings from azure.core.async_paging import AsyncItemPaged, AsyncList from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error fr...
class Config(object): """ Base configuration class. Contains one method that defines the database URI. This class is to be subclassed and its attributes defined therein. """ def __init__(self): self.database_uri() def database_uri(self): if self.DIALECT == 'sqlite': ...