content string |
|---|
"""Deprecated. See :doc:`/examples/high_availability`."""
import warnings
from pymongo import mongo_client
class MongoReplicaSetClient(mongo_client.MongoClient):
"""Deprecated alias for :class:`~pymongo.mongo_client.MongoClient`.
:class:`~pymongo.mongo_replica_set_client.MongoReplicaSetClient`
will be ... |
# -*- coding:utf-8 -*-
ASCIItranslit = {
0x0022: "''",
0x002A: "_",
0x002F: "_",
0x003A: "_",
0x003C: "_",
0x003D: "_",
0x003E: "_",
0x003F: "_",
0x005C: "_",
0x007C: "_",
0x007F: "",
0x00A0: "_",
0x00A1: "!",
0x00A2: "c",
0x00A3: "lb",
0x00A4: "",
0x00A5: "yen",
0x00A6: "I",
0x00A7: "SS",
0x00A8: ... |
"""
Define common steps for instructor dashboard acceptance tests.
"""
# pylint: disable=missing-docstring
# pylint: disable=redefined-outer-name
from __future__ import absolute_import
from lettuce import world, step
from mock import patch
from nose.tools import assert_in # pylint: disable=no-name-in-module
from c... |
import openerp.netsvc as netsvc
def log(cr,ident,act_id,info=''):
return
# msg = """
#res_type: %r
#res_id: %d
#uid: %d
#act_id: %d
#info: %s
#""" % (ident[1], ident[2], ident[0], act_id, info)
#cr.execute('insert into wkf_logs (res_type, res_id, uid, act_id, time, info) values... |
from neutron.api.v2 import attributes as attrs
from neutron.common import utils
from neutron.db import db_base_plugin_v2
from neutron.db import portsecurity_db_common
from neutron.extensions import portsecurity as psec
class PortSecurityDbMixin(portsecurity_db_common.PortSecurityDbCommon):
# Register dict extend ... |
"""
Django settings for event_subscribe project.
For more information on this file, see
https://docs.djangoproject.com/en/dev/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/dev/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR,... |
from upload_wdg import *
from sobject_group_wdg import *
from calendar_wdg import *
from sobject_calendar_wdg import *
from data_export_wdg import *
from misc_input_wdg import *
from button_wdg import *
from button_new_wdg import *
from gear_menu_wdg import *
from chooser_wdg import *
from smart_select_wdg import *
fro... |
import cherrypy
import os
import sys
# 這個程式要計算正齒輪的齒面寬, 資料庫連結希望使用 pybean 與 SQLite
# 導入 pybean 模組與所要使用的 Store 及 SQLiteWriter 方法
from pybean import Store, SQLiteWriter
import math
# 確定程式檔案所在目錄, 在 Windows 有最後的反斜線
_curdir = os.path.join(os.getcwd(), os.path.dirname(__file__))
# 將所在目錄設為系統搜尋目錄
sys.path.append(_curdir)
if 'OP... |
"""A lexical analyzer class for simple shell-like syntaxes."""
# Module and documentation by Eric S. Raymond, 21 Dec 1998
# Input stacking and error message cleanup added by ESR, March 2000
# push_source() and pop_source() made explicit by ESR, January 2001.
# Posix compliance, split(), string arguments, and
# iterato... |
"""Tool for exporting GLIFs from FontLab"""
import FL
import os
from robofab.interface.all.dialogs import ProgressBar
from robofab.glifLib import GlyphSet
from robofab.tools.glifImport import GlyphPlaceholder
from robofab.pens.flPen import drawFLGlyphOntoPointPen
def exportGlyph(glyphName, flGlyph, glyphSet):
"""Ex... |
# vim: ai ts=4 sts=4 et sw=4 encoding=utf-8
import csv
class CsvReader(object):
"""
Typical usage::
csv_reader = CsvReader(path)
for d in csv_reader.iter_dicts():
Variable.objects.create(**d)
"""
def __init__(self, path):
self.open(path)
def open(self, path):
... |
import os
import sys
sys.path.append(os.environ['PERF_EXEC_PATH'] + \
'/scripts/python/Perf-Trace-Util/lib/Perf/Trace')
from perf_trace_context import *
from Core import *
from Util import *
usage = "perf script -s syscall-counts-by-pid.py [comm|pid]\n";
for_comm = None
for_pid = None
if len(sys.argv) > 2:
sys.e... |
from temboo.core.choreography import Choreography
from temboo.core.choreography import InputSet
from temboo.core.choreography import ResultSet
from temboo.core.choreography import ChoreographyExecution
import json
class RetrieveCellFeed(Choreography):
def __init__(self, temboo_session):
"""
Creat... |
#! /usr/bin/python
import sys,re,string
sys.path.append("/home/pdendek/docsim-check/out/document-similarity-logic-1.6-SNAPSHOT-jar-with-dependencies.jar")
from pl.edu.icm.coansys.commons.java import DiacriticsRemover
def fillDict(inL,langs):
innerD = {}
for x in inL:
t,l = x
langs.add(l)
innerD[l] = t
return... |
import logging
import hashlib
import os
from base64 import urlsafe_b64encode as encode
from base64 import urlsafe_b64decode as decode
from pylons import request, response, session, tmpl_context as c, url
from pylons.controllers.util import abort, redirect
from pylons.decorators.rest import restrict
from ocsmanager.mo... |
import argparse
import mongoengine
import redis
import sys
import rmc.models as m
import rmc.shared.constants as c
import rmc.shared.facebook as facebook
import rmc.shared.util as rmc_util
import rmc.data.crawler as rmc_crawler
import rmc.data.processor as rmc_processor
# TODO(mack): remove duplication of fields thro... |
# -*- coding: utf-8 -*-
#
# OLED-Info Renderer for Dreambox/Enigma-2
# Coded by Vali (c)2011
#
#######################################################################
from enigma import eLabel
from Renderer import Renderer
from os import popen
from time import localtime, strftime
from Components.VariableText imp... |
from sos.plugins import Plugin, RedHatPlugin, DebianPlugin, UbuntuPlugin
class Acpid(Plugin):
"""ACPI daemon information"""
plugin_name = "acpid"
profiles = ('hardware',)
class RedHatAcpid(Acpid, RedHatPlugin):
def setup(self):
self.add_copy_spec([
"/var/log/acpid*",
... |
"""
A simple menu system for pygame. Probably a little too simple, unfortunately."""
from __future__ import division
import pygame
# This silly Exception is used to return from a menu.
class ReturnError(Exception):
pass
class Exit(Exception):
pass
class Menu(object):
"""
Class for bui... |
import os
from nupic.frameworks.opf.expdescriptionhelpers import importBaseDescription
# the sub-experiment configuration
config = \
{
'dataSource': 'file://' + os.path.join(os.path.dirname(__file__),
'../datasets/scalar_SP_0.csv'),
'modelParams': { 'clParams': { 'clVerbo... |
from temboo.core.choreography import Choreography
from temboo.core.choreography import InputSet
from temboo.core.choreography import ResultSet
from temboo.core.choreography import ChoreographyExecution
import json
class GetMonitoredTwitterHandle(Choreography):
def __init__(self, temboo_session):
"""
... |
"""Unit tests for the error_fixer module."""
# Allow non-Google copyright
# pylint: disable=g-bad-file-header
import unittest as googletest
from closure_linter import error_fixer
from closure_linter import testutil
class ErrorFixerTest(googletest.TestCase):
"""Unit tests for error_fixer."""
def setUp(self):
... |
import os
from colorama import Fore
from helpers import run_cmd
outDirDefault = 'test-outs'
testDirDefault = 'test-files'
"""
Run a single test
@param tFile- required; the file to check against (uncompressed data)
@param level- optional (default: all); the compression level [1-9]
@return True if all tests passed; Fa... |
def upgrade(migrate_engine):
pass
def downgrade(migration_engine):
pass |
from __future__ import absolute_import
import sys
from datetime import timedelta
from django.core.cache.backends.base import InvalidCacheBackendError
from celery import result
from celery import states
from celery.utils import gen_unique_id
from celery.datastructures import ExceptionInfo
from djcelery.backends.cac... |
import sys
import os
import pandas as pd
import numpy as np
import argparse
def main():
parser=argparse.ArgumentParser(description='MusiteDeep custom training tool for general PTM prediction.')
parser.add_argument('-input', dest='inputfile', type=str, help='training data in fasta format. Sites f... |
"""The io module provides the Python interfaces to stream handling. The
builtin open function is defined in this module.
At the top of the I/O hierarchy is the abstract base class IOBase. It
defines the basic interface to a stream. Note, however, that there is no
separation between reading and writing to streams; impl... |
import os
import ycm_core
# These are the compilation flags that will be used in case there's no
# compilation database set (by default, one is not set).
# CHANGE THIS LIST OF FLAGS. YES, THIS IS THE DROID YOU HAVE BEEN LOOKING FOR.
flags = [
'-Wall',
'-Werror',
'-pendantic-errors',
'-std=c++0x',
'-fno-strict-aliasing... |
#!/usr/bin/env python
# coding=utf-8
################################################################################
# CosConfig 有关cos的配置
################################################################################
class CosConfig(object):
def __init__(self):
self._end_point = 'http://web.file.myqc... |
#!/usr/bin/env python
##################################################
# Gnuradio Python Flow Graph
# Title: CPM test
# Description: gnuradio flow graph
# Generated: Thu Feb 19 23:16:23 2009
##################################################
from gnuradio import gr
from gnuradio import trellis, digital, filter, bloc... |
import unittest
import mock
from google.cloud.pubsub_v1.types import ReceivedMessage
from google.protobuf.json_format import MessageToDict, ParseDict
from airflow.exceptions import AirflowSensorTimeout
from airflow.providers.google.cloud.sensors.pubsub import PubSubPullSensor
TASK_ID = 'test-task-id'
TEST_PROJECT = ... |
from typing import Optional
from overrides import overrides
import torch
from torch import nn
from allennlp.modules.seq2seq_encoders.seq2seq_encoder import Seq2SeqEncoder
from allennlp.nn.util import add_positional_features
@Seq2SeqEncoder.register("pytorch_transformer")
class PytorchTransformer(Seq2SeqEncoder):
... |
import json
import mock
from django.conf import settings
from openstack_dashboard import api
from openstack_dashboard.api.rest import cinder
from openstack_dashboard.test import helpers as test
class CinderRestTestCase(test.TestCase):
#
# Volumes
#
def test_volumes_get(self):
self._test_vol... |
from androguard.core import *
from androguard.core.androgen import *
from androguard.core.bytecode import *
from androguard.core.bytecodes.dvm import *
from androguard.core.bytecodes.apk import *
from androguard.core.analysis.analysis import *
from androguard.core.analysis.ganalysis import *
from androguard.decompiler.... |
import glob
import optparse
import os
import sys
def main(argv):
parser = optparse.OptionParser(
usage='Usage: %prog [options] filename ...')
parser.add_option('-C', '--srcdir',
help='Change directory.', dest='srcdir', default=None)
parser.add_option('-o', '--output',
... |
from __future__ import absolute_import
from __future__ import print_function
from buildbot.steps.worker import CompositeStepMixin
from buildbot.steps.worker import CopyDirectory
from buildbot.steps.worker import FileExists
from buildbot.steps.worker import MakeDirectory
from buildbot.steps.worker import RemoveDirector... |
from __future__ import with_statement
import base64
import optparse
import os
import pymongo
import simplejson
import sys
import time
import zlib
from paste.deploy import converters
from lolapps.util import processor
from lolapps.util import db
from lolapps.util.adapters import mongo, chunking
from lolapps.common i... |
from django.core.management.base import BaseCommand, CommandError
from xmodule.modulestore.django import modulestore
from xmodule.modulestore.xml_importer import check_module_metadata_editability
from xmodule.course_module import CourseDescriptor
from request_cache.middleware import RequestCache
class Command(BaseCo... |
from itertools import ifilter
UNIDADES = (
'',
'UN ',
'DOS ',
'TRES ',
'CUATRO ',
'CINCO ',
'SEIS ',
'SIETE ',
'OCHO ',
'NUEVE ',
'DIEZ ',
'ONCE ',
'DOCE ',
'TRECE ',
'CATORCE ',
'QUINCE ',
'DIECISEIS ',
'DIECISIETE ',
'DIECIOCHO ',
'DIECI... |
#!/usr/bin/python
# this script unzips the brand catalog content export zip files
# one at a time, and numbers each exported xml file
import zipfile
import shutil
import os
import glob
def bool_str(s):
s = s.lower()
T = ('1', 'true', 'y', 'ye', 'yes', 'yea', 'ya', 'yah', 'yup')
F = ('0', 'false', 'n', 'no', 'not',... |
import re
from streamlink.compat import urljoin
from streamlink.plugin import Plugin
from streamlink.plugin.api import validate
from streamlink.plugin.api.utils import parse_json
from streamlink.stream import AkamaiHDStream, HLSStream
_url_re = re.compile(r"http(s)?://(www\.)?livestream.com/")
_stream_config_schema =... |
"""The script is used to parse an XPK file.
It will do:
1. Check the magic file header;
2. Verify the signature of the XPK file;
3. Extract the content of the XPK file to some folder.
The format of XPK file can be found at
https://github.com/crosswalk-project/crosswalk-website/wiki/Crosswalk-package-management
This ... |
from openerp.osv import fields, osv
import openerp.addons.decimal_precision as dp
class membership_invoice(osv.osv_memory):
"""Membership Invoice"""
_name = "membership.invoice"
_description = "Membership Invoice"
_columns = {
'product_id': fields.many2one('product.product','Membership', requi... |
#!/bin/python
import roomai.kuhn
import roomai.common
import random
class HumanInputPlayer(roomai.common.AbstractPlayer):
"""
"""
def receive_info(self, info):
"""
Args:
info:
"""
available_actions = info
def take_action(self):
"""
Returns:
... |
from os import environ
import asyncio
from autobahn.asyncio.wamp import ApplicationSession, ApplicationRunner
class Component(ApplicationSession):
"""
An application component that subscribes and receives events.
After receiving 5 events, it unsubscribes, sleeps and then
resubscribes for another run.... |
"""
Functions for working with "safe strings": strings that can be displayed safely
without further escaping in HTML. Marking something as a "safe string" means
that the producer of the string has already turned characters that should not
be interpreted by the HTML engine (e.g. '<') into the appropriate entities.
"""
i... |
from __future__ import unicode_literals
import frappe
out = frappe.response
from frappe.utils import cint
import frappe.defaults
def get_sql_tables(q):
if q.find('WHERE') != -1:
tl = q.split('FROM')[1].split('WHERE')[0].split(',')
elif q.find('GROUP BY') != -1:
tl = q.split('FROM')[1].split('GROUP BY')[0].spli... |
from __future__ import absolute_import, unicode_literals
import hashlib
import json
import os
from django.core.files.uploadedfile import UploadedFile
from django.http import HttpResponse, HttpResponseServerError
from .models import FileModel, UPLOAD_TO
from .tests import UNICODE_FILENAME
from .uploadhandler import Q... |
{
'name': 'Dominican Republic - Accounting',
'version': '1.0',
'category': 'Localization/Account Charts',
'description': """
This is the base module to manage the accounting chart for Dominican Republic.
==============================================================================
* Chart of Accounts.... |
"""
Given a 2D binary matrix filled with 0's and 1's, find the largest square containing all 1's and return its area.
Example
For example, given the following matrix:
1 0 1 0 0
1 0 1 1 1
1 1 1 1 1
1 0 0 1 0
Return 4.
"""
__author__ = 'Daniel'
class Solution:
def maxSquare(self, matrix):
"""
Algo... |
from openerp.osv import fields, orm
from openerp.tools.translate import _
from openerp import netsvc
from datetime import datetime, timedelta
from dateutil.relativedelta import relativedelta
import time
class OeMedicalPrescriptionOrder(orm.Model):
_name='oemedical.prescription.order'
_columns={
'pat... |
from django.apps.registry import apps as global_apps
from django.db import migrations, router
from .exceptions import InvalidMigrationPlan
from .loader import MigrationLoader
from .recorder import MigrationRecorder
from .state import ProjectState
class MigrationExecutor:
"""
End-to-end migration execution - ... |
import win32evtlog, traceback
import win32api, win32con
import win32security # To translate NT Sids to account names.
from win32evtlogutil import *
def ReadLog(computer, logType="Application", dumpEachRecord = 0):
# read the entire log back.
h=win32evtlog.OpenEventLog(computer, logType)
numRecords = win32... |
import collections
import datetime
import hmac
import json
import logging
import urllib2
from google.appengine.api import urlfetch
from google.appengine.api import users
from google.appengine.ext import db
import models
import config_NOCOMMIT as config
# Whether to display the new vote counts (cached in Triples).
US... |
import pandas as pd
'''
The following code is to help you play with the concept of Series in Pandas.
You can think of Series as an one-dimensional object that is similar to
an array, list, or column in a database. By default, it will assign an
index label to each item in the Series ranging from 0 to N, where N... |
import os
import hmac
import re
from ansible.module_utils.six.moves.urllib.parse import urlparse
try:
from hashlib import sha1
except ImportError:
import sha as sha1
HASHED_KEY_MAGIC = "|1|"
def is_ssh_url(url):
""" check if url is ssh """
if "@" in url and "://" not in url:
return True
... |
"""DNA - Service example - Main service module.
Main methods to handle the service tasks.
This example service uses DCM APIs (and the corresponding DNA connector) to
collect DCM report data, elaborate it, and push it to a BigQuery dataset.
"""
import base64
import json
import logging
import sys
from dcm_connector im... |
'''Command line handlers that address the responses in the Google Sheet'''
import logging
import os
from cliff.lister import Lister
import seadir.config as config
import seadir.model.responses as responses
class Dump(Lister):
'''Dump the records from the Google Sheet to the screen'''
log = logging.getLogg... |
import unittest
import pickle
from ctypes import *
import _ctypes_test
dll = CDLL(_ctypes_test.__file__)
class X(Structure):
_fields_ = [("a", c_int), ("b", c_double)]
init_called = 0
def __init__(self, *args, **kw):
X.init_called += 1
self.x = 42
class Y(X):
_fields_ = [("str", c_char... |
# coding: utf-8
# pylint: disable=missing-docstring, invalid-name
import flask
import auth
import config
import model
from main import app
dropbox_config = dict(
access_token_method='POST',
access_token_url='https://api.dropbox.com/1/oauth2/token',
authorize_url='https://www.dropbox.com/... |
"""A base class to provide a model and corresponding input data for testing."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
class ModelAndInput(object):
"""Base class to provide model and its corresponding inputs."""
def get_model(self):
"""Ret... |
""" Python 'zlib_codec' Codec - zlib compression encoding
Unlike most of the other codecs which target Unicode, this codec
will return Python string objects for both encode and decode.
Written by Marc-Andre Lemburg (<EMAIL>).
"""
import codecs
import zlib # this codec needs the optional zlib module !
##... |
"""
Machine learning module for Python
==================================
sklearn is a Python module integrating classical machine
learning algorithms in the tightly-knit world of scientific Python
packages (numpy, scipy, matplotlib).
It aims to provide simple and efficient solutions to learning problems
that are acc... |
from io import BytesIO
import logging
import os
import re
import struct
import sys
from .compat import sysconfig, fsencode, detect_encoding, ZipFile
from .resources import finder
from .util import (FileOperator, get_export_entry, convert_path,
get_executable, in_venv)
logger = logging.getLogger(__n... |
# -----------------
# normal arguments (no keywords)
# -----------------
def simple(a):
return a
simple(1)
#! 6 type-error-too-few-arguments
simple()
#! 10 type-error-too-many-arguments
simple(1, 2)
#! 10 type-error-too-many-arguments
simple(1, 2, 3)
# -----------------
# keyword arguments
# -----------------... |
"""Visual Studio project reader/writer."""
import gyp.common
import gyp.easy_xml as easy_xml
class Writer(object):
"""Visual Studio XML tool file writer."""
def __init__(self, tool_file_path, name):
"""Initializes the tool file.
Args:
tool_file_path: Path to the tool file.
name: Name of the... |
"""
database_example_formatted.py
:copyright: (c) 2015 by C. W.
:license: New BSD
"""
from flask import Flask, request, jsonify, redirect, url_for
import flask_excel as excel
from flask_sqlalchemy import SQLAlchemy
from datetime import datetime
# please uncomment the following line if you use pyexcel < 0.2.2
# import ... |
from __future__ import unicode_literals
from django.contrib.auth.models import User
from django.core import management
from django.test import TestCase
from django.utils.six import StringIO
from .models import (
Car, CarDriver, Driver, Group, Membership, Person, UserMembership,
)
class M2MThroughTestCase(TestCa... |
import os
import sys
import copy
import subprocess
WEB2PY_PATH = sys.argv[1]
APP = sys.argv[2]
changed_table = "org_organisation"
new_field = "type_id"
new_table = "org_organisation_type"
old_field = "type"
new_table_field = "name"
os.chdir(WEB2PY_PATH)
sys.path.append(WEB2PY_PATH)
from gluon.custom_import import cu... |
from __future__ import unicode_literals
import frappe
from frappe import _
def execute(filters=None):
columns = get_columns()
proj_details = get_project_details()
pr_item_map = get_purchased_items_cost()
se_item_map = get_issued_items_cost()
dn_item_map = get_delivered_items_cost()
data = []
for project in pr... |
#! /usr/bin/env python
from state_ai import StateAi
import rospy
from math import pi
from std_msgs.msg import Bool
class IGVCBasicNorth(StateAi):
def __init__(self):
super(IGVCBasicNorth, self).__init__("igvc_basic_north")
def on_start(self):
#self.generate_circle(2.0, pi/4, 2 * pi - pi/4, ... |
VERBOSE = True
from globals import ALLVERBOSE
"""
ImapProxyServer Object
Version 0.0.1
Sets up framework for loging into proxy server
spawns new CredentialsChecker
spawns new protocol factory
listens for connections
Version 0.0.0 - New File
"""
from twisted.internet im... |
"""
Send emails to users inviting them to add their course certificates to their
LinkedIn profiles.
"""
from smtplib import SMTPServerDisconnected, SMTPDataError, SMTPConnectError, SMTPException
import json
import logging
import urllib
from boto.exception import AWSConnectionError
from boto.ses.exceptions import (
... |
import pytest
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException, NoSuchElementException, NoAlertPresentException
from .conftest import _make_nbserv... |
import unittest
from task_scheduler import TaskScheduler
from task import Task
import arrow
class TaskSchedulerTestCase(unittest.TestCase):
def setUp(self):
self.task_scheduler = TaskScheduler()
self.tz = 'local'
self.datetime = arrow.Arrow(2015, 5, 9, 11, 11, 11, tzinfo=self.tz)
s... |
import functools
class Filter(object):
pass
class Kernel(Filter):
"""
Create a convolution kernel. The current version only
supports 3x3 and 5x5 integer and floating point kernels.
In the current version, kernels can only be applied to
"L" and "RGB" images.
:param size: Kernel size, g... |
"""
A test harness for the logging module. Tests SMTPHandler.
Copyright (C) 2001-2002 Vinay Sajip. All Rights Reserved.
"""
import logging, logging.handlers
MAILHOST = 'beta'
FROM = '<EMAIL>'
TO = ['arkadi_renko']
SUBJECT = 'Test Logging email from Python logging module (non-buffering)'
def main():
lo... |
from openerp.osv import fields, osv
from openerp.tools.translate import _
class purchase_requisition_partner(osv.osv_memory):
_name = "purchase.requisition.partner"
_description = "Purchase Requisition Partner"
_columns = {
'partner_id': fields.many2one('res.partner', 'Supplier', required=True,doma... |
data = (
'A', # 0x00
'B', # 0x01
'C', # 0x02
'D', # 0x03
'E', # 0x04
'F', # 0x05
'G', # 0x06
'H', # 0x07
'I', # 0x08
'J', # 0x09
'K', # 0x0a
'L', # 0x0b
'M', # 0x0c
'N', # 0x0d
'O', # 0x0e
'P', # 0x0f
'Q', # 0x10
'R', # 0x11
'S', # 0x12
'T', # 0x13
'U', # 0... |
import collections
import logging
import ryu.exception as ryu_exc
from ryu.base import app_manager
from ryu.controller import event
class RemoteDPIDAlreadyExist(ryu_exc.RyuException):
message = ('port (%(dpid)s, %(port)s) has already '
'remote dpid %(remote_dpid)s')
class TunnelKeyAlreadyExist(r... |
import numpy as np
import cv2
from matplotlib import pyplot as plt
# test algorithm to recognize digits using kNN
# source: http://docs.opencv.org/trunk/doc/py_tutorials/py_ml/py_knn/py_knn_opencv/py_knn_opencv.html
img = cv2.imread('../data/digits.png')
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
# Now we split the... |
from openerp.osv import fields,osv
class res_partner(osv.osv):
""" Inherits partner and adds CRM information in the partner form """
_inherit = 'res.partner'
def _opportunity_meeting_phonecall_count(self, cr, uid, ids, field_name, arg, context=None):
res = dict(map(lambda x: (x,{'opportunity_count... |
"""Checks WebKit style for the watchlist file."""
from webkitpy.common.watchlist.watchlistparser import WatchListParser
class WatchListChecker(object):
"""Processes the watch list for checking style."""
def __init__(self, file_path, handle_style_error):
self._handle_style_error = handle_style_erro... |
# coding: utf-8
# PYTHON IMPORTS
import os
import re
# DJANGO IMPORTS
from django.core.management.base import BaseCommand, CommandError
from django.conf import settings
from django.utils.six.moves import input
# FILEBROWSER IMPORTS
from filebrowser.settings import EXTENSION_LIST, EXCLUDE, DIRECTORY, VERSIONS, EXTENS... |
import json
from social.tests.backends.oauth import OAuth2Test
class StocktwitsOAuth2Test(OAuth2Test):
backend_path = 'social.backends.stocktwits.StocktwitsOAuth2'
user_data_url = 'https://api.stocktwits.com/api/2/account/verify.json'
expected_username = 'foobar'
access_token_body = json.dumps({
... |
# https://leetcode.com/problems/number-of-islands/
class Solution(object):
def numIslands(self, grid):
"""
:type grid: List[List[str]]
:rtype: int
"""
if len(grid) == 0: return 0
cols,rows = len(grid), len(grid[0])
def dfs(i, j):
"""
he... |
"""Sphinx extension for building opcode documentation.
"""
# pylint: disable=C0413
# C0413: Wrong import position
import re
from cStringIO import StringIO
import docutils.statemachine
import docutils.nodes
import docutils.utils
import docutils.parsers.rst
import sphinx.errors
import sphinx.util.compat
import sphin... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.network.netv... |
"""Easier access to ID3 tags.
EasyID3 is a wrapper around mutagen.id3.ID3 to make ID3 tags appear
more like Vorbis or APEv2 tags.
"""
import mutagen.id3
from ._compat import iteritems, text_type, PY2
from mutagen import Metadata
from mutagen._util import DictMixin, dict_match
from mutagen.id3 import ID3, error, dele... |
import logging
import os
import subprocess
import tempfile
import zipfile
from lib.subcommand import SubCommand
from lib.symbol import SymbolDataSources
LOGGER = logging.getLogger('dmprof')
class UploadCommand(SubCommand):
def __init__(self):
super(UploadCommand, self).__init__(
'Usage: %prog upload ... |
{
'name': 'Invoicing Journals',
'version': '1.0',
'category': 'Sales Management',
'description': """
The sales journal modules allows you to categorise your sales and deliveries (picking lists) between different journals.
==================================================================================... |
import sys
from collections import deque
from neo.lib import logging
from neo.lib.app import BaseApplication
from neo.lib.protocol import uuid_str, \
CellStates, ClusterStates, NodeTypes, Packets
from neo.lib.node import NodeManager
from neo.lib.connection import ListeningConnection
from neo.lib.exception import S... |
#!/usr/bin/env python
import sys
import math
from gnuradio import gr, gru, audio, eng_notation, blks2, optfir
from gnuradio import usrp
from gnuradio.eng_option import eng_option
from optparse import OptionParser
try:
import cqpsk
except:
from tetra_demod import cqpsk
# applies frequency translation, resampl... |
import argparse
import os
import sys
from common_includes import *
class Preparation(Step):
MESSAGE = "Preparation."
def RunStep(self):
# Update v8 remote tracking branches.
self.GitFetchOrigin()
class DetectLastPush(Step):
MESSAGE = "Detect commit ID of last push to trunk."
def RunStep(self):
... |
"""drop_user_and_chart
Revision ID: cf5dc11e79ad
Revises: 41f5f12752f8
Create Date: 2019-01-24 15:30:35.834740
"""
import sqlalchemy as sa
from alembic import op
from sqlalchemy.dialects import mysql
from sqlalchemy.engine.reflection import Inspector
# revision identifiers, used by Alembic.
revision = 'cf5dc11e79ad'... |
import gdb
double_type = gdb.lookup_type('double')
string_type = gdb.lookup_type('char').pointer()
def fixed_value(f):
"""Extracts the floating point value of a 'fixed' instance."""
if f.type.unqualified().strip_typedefs().code == double_type.code:
return float(f.cast(double_type))
else:
... |
"""
Face of a triangle mesh.
"""
from __future__ import absolute_import
#Init has to be imported first because it has code to workaround the python bug where relative imports don't work if the module is imported as a main module.
import __init__
from fabmetheus_utilities.geometry.geometry_tools import dictionary
fro... |
# chat_server.py
import sys, socket, select
HOST = ''
SOCKET_LIST = []
RECV_BUFFER = 4096
PORT = 443
def chat_server():
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server_socket.bind((HOST, PORT))
server_soc... |
#!/usr/bin/env python
# Test whether a client sends a correct PUBLISH to a topic with QoS 2 and responds to a disconnect.
import inspect
import os
import socket
import sys
# From http://stackoverflow.com/questions/279237/python-import-a-module-from-a-folder
cmd_subfolder = os.path.realpath(os.path.abspath(os.path.jo... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import os
extensions = [
'sphinx.ext.autodoc',
'sphinx.ext.autosummary',
'sphinx.ext.coverage',
'sphinx.ext.doctest',
'sphinx.ext.extlinks',
'sphinx.ext.ifconfig',
'sphinx.ext.napoleon',
'sphinx.ext.todo',
'sphinx.ext.... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.