content stringlengths 4 20k |
|---|
from odoo import api, models, fields
class CommunicationDefaults(models.AbstractModel):
_inherit = 'partner.communication.defaults'
print_subject = fields.Boolean(default=True)
print_header = fields.Boolean()
show_signature = fields.Boolean()
add_success_story = fields.Boolean()
class PartnerCo... |
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 FetchToken(Choreography):
def __init__(self, temboo_session):
"""
Create a ne... |
suite = {
"mxversion" : "5.5.6",
"name" : "jvmci",
"url" : "http://openjdk.java.net/projects/graal",
"developer" : {
"name" : "Truffle and Graal developers",
"email" : "<EMAIL>",
"organization" : "Graal",
"organizationUrl" : "http://openjdk.java.net/projects/graal",
},
"repositories" : {
... |
"""Celery tasks for user management"""
import logging
from celery import task
from django.db import IntegrityError
import games.models
from games.notifier import send_daily_mod_mail
from games.util.steam import create_game
from accounts.models import User
from accounts import spam_control
from common.util import slug... |
from __future__ import division as __division__
import numpy as __np__
import matplotlib.pyplot as __plt__
# Function: trace rays
# input a list of ray
# output [ray position and direction] on next surface
def trace(ray_list, surface1, surface2):
ray_num = len(ray_list)
Pos_new_list = []
KLM_new_list = ... |
"""XLIFF classes specifically suited for handling the PO representation in
XLIFF.
This way the API supports plurals as if it was a PO file, for example.
"""
from lxml import etree
import re
from translate.misc.multistring import multistring
from translate.storage import base, lisa, poheader, xliff
from translate.sto... |
from __future__ import print_function
from functools import wraps
class descript(object):
def __init__(self, f, lockattr):
self.f = f
self.lockattr = lockattr
def __get__(self, instance, klass):
if instance is None:
# Class method was requested
return self.m... |
# -*- coding: utf-8 -*-
"""
pygments.lexers.j
~~~~~~~~~~~~~~~~~
Lexer for the J programming language.
:copyright: Copyright 2006-2015 by the Pygments team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
from pygments.lexer import RegexLexer, words, include
from pygments.token import Com... |
from ._submit_job import submit_job
def submit_hadoop_job(project_id, region, cluster_name,
main_jar_file_uri=None, main_class=None, args=[], hadoop_job={}, job={},
wait_interval=30):
"""Submits a Cloud Dataproc job for running Apache Hadoop MapReduce jobs
on Apache Hadoop YARN.
Args:
... |
import boto3
import botocore
import json
def upload_to_bucket(obj, filename):
bucket_name = 'phelps-testbucket'
s3 = boto3.client('s3')
try:
response = s3.get_bucket_location(Bucket=bucket_name)
print 'upload_to_bucket', response
except botocore.exceptions.ClientError:
response ... |
"""
Seismic: 2D finite difference simulation of elastic SH wave propagation in a
medium with a discontinuity (i.e., Moho), generating Love waves.
"""
import numpy as np
from matplotlib import animation
from fatiando import gridder
from fatiando.seismic import wavefd
from fatiando.vis import mpl
# Set the parameters of... |
APP_NAME = "cloudcaptive-userinfuser"
UI_SPATH = "https://"+ APP_NAME + ".appspot.com/api/"
UI_PATH = "http://" + APP_NAME +".appspot.com/api/"
LOCAL_TEST = "http://localhost:8080/api/"
API_VER = "1"
VALID_WIDGETS = ["trophy_case", "milestones", "notifier", "points", "rank", "availablebadges", "leaderboard"]
UPDATE_USE... |
#!/usr/bin/python
#
# Follow naming conventions described at:
# PEP 0008 (https://www.python.org/dev/peps/pep-0008/)
#
import numpy as np
import random
class SubsetGenerator:
""" Return a representative subset of a given matrix.
Generate row based subset from a given data matrix.
The class provides fu... |
"""
Uses gevent to make concurrent requests.
"""
import grequests
import json
import logging
from .client import Client, validate_args, stringify
from .data import AddressCollection
from .exceptions import SmartyStreetsError, ERROR_CODES
try:
# Python 2
ranger = xrange
except NameError:
# Python 3
ra... |
"""An NNVM implementation of graph packing."""
import nnvm
from nnvm.compiler import graph_attr, graph_util
def _pack_batch_channel(data, dshape, bfactor, cfactor):
"""Pack the data channel dimension.
"""
assert dshape[0] % bfactor == 0
assert dshape[1] % cfactor == 0
data = nnvm.sym.reshape(data,... |
import rocs.data.databases.ConceptualGraph as CG
import sys
def SetFromObservedProperty(cg):
for fname, f in cg.edge.items():
if f.type.startswith('Observed') and len(f.nodes) == 1:
((p_argmax,), p_max) = max(f.potential.iteritems(), key=lambda x:x[1])
cg.node[f.nodes[0]].observed_value = p_argmax
... |
import mock
import json
from testrunner import PluginsTestCase as TestCaseBase
from plugins import check_cluster_vol_usage
class TestClusterVolUsage(TestCaseBase):
# Method to test volume perf data when no matching host method
@mock.patch('plugins.livestatus.readLiveStatusAsJSON')
def test_checkVolumePe... |
from openerp.osv import fields, osv
class purchase_requisition(osv.osv):
_inherit = "purchase.requisition"
def _get_analytic_accounts(
self, cursor, user, ids, name, arg, context=None
):
res = {}
for purchase in self.browse(cursor, user, ids, context=context):
res[purc... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import pages.utils
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
... |
# To maximize python3/python2 compatibility
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import division
from __future__ import absolute_import
#
# helper code: we define our match tokens
lastval = ''
def monitor(location,value):
global lastval
#print 'At %s: %s... |
import os
from pymacaron.log import pymlogger
import imp
import pprint
import subprocess
from pymacaron.config import get_config
from pymacaron.auth import generate_token
utils = imp.load_source('utils', os.path.join(os.path.dirname(__file__), 'utils.py'))
log = pymlogger(__name__)
class Tests(utils.PyMacaronTest... |
import unittest
from board_search import board_search
from board import Board
from trie import Trie
class BoardSearchTest(unittest.TestCase):
def setUp(self):
self.trie = Trie()
def test_search_with_no_words(self):
board = Board([['C', 'A', 'R'], ['D', 'O', 'T'], ['X', 'G', 'X']])
self... |
from libdef import *
import time
class Game:
def __init__(self, game):
self.game = game
self.background = Background('./assets/background.png', [0, 0])
def choose_players(self):
self.game.screen.blit(self.background.image, self.background.rect)
DrawText(self.game.screen, "Sele... |
#!/usr/bin/python
import json, re
import random
import sys
try:
from urllib.request import build_opener
except:
from urllib2 import build_opener
# Makes a request to a given URL (first arg) and optional params (second arg)
def make_request(*args):
opener = build_opener()
opener.addheaders = [('User-ag... |
import csv
import logging
from telemetry.internal.platform import power_monitor
class DumpsysPowerMonitor(power_monitor.PowerMonitor):
"""PowerMonitor that relies on the dumpsys batterystats to monitor the power
consumption of a single android application. This measure uses a heuristic
and is the same informat... |
"""
Unit tests for `iris.fileformats.grib._load_convert.fixup_int32_from_uint32`.
"""
from __future__ import (absolute_import, division, print_function)
from six.moves import (filter, input, map, range, zip) # noqa
# Import iris.tests first so that some things can be initialised before
# importing anything else.
im... |
# -*- coding: utf-8 -*-
# Gestion fine de la typographie française, du moins, ce qui peut être
# automatisé, Lointainement inspiré de l’extension SmartyPants.
from __future__ import unicode_literals
import zmarkdown
from ..inlinepatterns import HtmlPattern
class ReplacePattern(HtmlPattern):
def __init__(self, pa... |
import os
os.environ['DJANGO_SETTINGS_MODULE']='settings'
import cgi
import cgitb
cgitb.enable()
import webapp2 as webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext.webapp import template
import django
from django import forms
from leslie import lesliedb
class leslieInputPage(w... |
from abapy.misc import load
from matplotlib import pyplot as plt
import matplotlib.gridspec as gridspec
from matplotlib import mpl
import numpy as np
path_to_odb = '../../../../testing/'
title0 = 'title0'
title1 = 'title1'
title2 = 'title2'
N_levels = 10 # Number os isovalues
levels = np.linspace(0., 0.3, N_levels)
S... |
from plotly.basedatatypes import BaseTraceHierarchyType as _BaseTraceHierarchyType
import copy as _copy
class Line(_BaseTraceHierarchyType):
# class properties
# --------------------
_parent_path_str = "treemap.marker"
_path_str = "treemap.marker.line"
_valid_props = {"color", "colorsrc", "width"... |
"""
Helper functions for loading environment settings.
"""
from __future__ import absolute_import, print_function
import io
import json
import os
import sys
from time import sleep
import memcache
import six
from lazy import lazy
from path import Path as path
from paver.easy import BuildFailure, sh
from six.moves impo... |
"""
Example of simple consumer that waits for a single message, acknowledges it
and exits.
"""
from kombu import Connection, Exchange, Queue, Consumer, eventloop
from pprint import pformat
#: By default messages sent to exchanges are persistent (delivery_mode=2),
#: and queues and exchanges are durable.
exchange = Exc... |
class _LazyAgData(object):
def __init__(self):
self._ag_data_access = None
def __getattr__(self, name):
if not self._ag_data_access:
from amgut.lib.data_access.ag_data_access import AGDataAccess
print 'Connecting to postgres for amgut.connections.ag_data'
s... |
"""Unit tests for run_perf_tests."""
import StringIO
import json
import re
import unittest
from webkitpy.common.host_mock import MockHost
from webkitpy.common.system.outputcapture import OutputCapture
from webkitpy.port.test import TestPort
from webkitpy.performance_tests.perftest import DEFAULT_TEST_RUNNER_COUNT
fro... |
from django.http import HttpResponse
from httplib import HTTPConnection, HTTPSConnection
from urlparse import urlsplit
from django.conf import settings
from django.utils.http import is_safe_url
from django.http.request import validate_host
def proxy(request):
PROXY_ALLOWED_HOSTS = getattr(settings, 'PROXY_ALLOWED... |
"""Extracts OpenStack config option info from module(s)."""
from __future__ import print_function
import argparse
import imp
import os
import re
import socket
import sys
import textwrap
from oslo.config import cfg
import six
import stevedore.named
from ceilometer.openstack.common import gettextutils
from ceilometer... |
#!/usr/bin/env python
import numpy as np
def build(energies, couplings, trans):
'''Builds the Excitonic Hamiltonian, given the energies, the couplings,
and the array of the number of transitions per chromophore.'''
#
# For example, if we have 2 chromophores, the first with 3 transitions
# and the... |
import websocket, json, requests
class RTM():
def __init__(self, token):
self.TOKEN = token
self.connected = False
self.session = requests.Session()
self.ws = websocket.WebSocket()
def receive_dict(self):
return json.loads(self.ws.recv())
def connect(self):
... |
from seecr.test import SeecrTestCase, CallTrace
from seecr.test.portnumbergenerator import PortNumberGenerator
from weightless.core import compose
from meresco.components.http import ObservableHttpServer
from meresco.components.http.observablehttpserver import _convertToStrings
from meresco.components.http.utils impo... |
import inspect
import re
import xmlrpclib
import rtorrentlib
from rtorrentlib.common import bool_to_int, convert_version_tuple_to_str, \
safe_repr
from rtorrentlib.err import MethodError
def get_varname(rpc_call):
"""Transform rpc method into variable name.
@newfield example: Example
@example: if th... |
"""Outputs a cropped image or an image highlighting crop regions on an image.
Examples:
python crop_hints.py resources/cropme.jpg draw
python crop_hints.py resources/cropme.jpg crop
"""
# [START full_tutorial]
# [START imports]
import argparse
import io
from google.cloud import vision
from google.cloud.vision... |
# -*- coding: utf-8 -*-
"""
***************************************************************************
OTBUtils.py
---------------------
Date : August 2012
Copyright : (C) 2012 by Victor Olaya
Email : volayaf at gmail dot com
******************************... |
"""A board is a list of list of str. For example, the board
ANTT
XSOB
is represented as the list
[['A', 'N', 'T', 'T'], ['X', 'S', 'O', 'B']]
A word list is a list of str. For example, the list of words
ANT
BOX
SOB
TO
is represented as the list
['ANT', 'BOX', 'SOB', 'TO']
"""
def is_v... |
# -*- encoding: utf-8 -*-
from . import FixtureTest
class NatureReserveTest(FixtureTest):
def test_nature_reserve_15_way(self):
import dsl
z, x, y = (16, 19788, 24194)
self.generate_fixtures(
# https://www.openstreetmap.org/way/105703183
dsl.way(105703183, dsl.bo... |
import uuid, cache, datetime, model
from tornado import web
from oz.handler import *
from web import *
from web import util, engine
from web.serialization import *
class RecommendationHandler(util.SnowballHandler):
"""Endpoint for handling recommendations between two nodes"""
@util.error_handler
def... |
from sqlalchemy import Column, ForeignKey, Integer, String, UnicodeText, Unicode
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship
from sqlalchemy import create_engine
from ConfigParser import ConfigParser
Base = declarative_base()
config = ConfigParser()
config.read('conf... |
from pycp2k.inputsection import InputSection
class _each379(InputSection):
def __init__(self):
InputSection.__init__(self)
self.Just_energy = None
self.Powell_opt = None
self.Qs_scf = None
self.Xas_scf = None
self.Md = None
self.Pint = None
self.Meta... |
"""
This file contains tasks that are designed to perform background operations on the
running state of a course.
At present, these tasks all operate on StudentModule objects in one way or another,
so they share a visitor architecture. Each task defines an "update function" that
takes a module_descriptor, a particula... |
from PyQt4 import QtCore, QtGui
from PyQt4.QtCore import Qt
class SignalShape:
"""This class holds the possible representation shapes for signal lights.
"""
NONE = 0
CIRCLE = 1
SQUARE = 2
QUARTER_SW = 10
QUARTER_NW = 11
QUARTER_NE = 12
QUARTER_SE = 13
BAR_N_S = 20
BAR_E_W =... |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# envirosim.py
import os
import configparser
def main():
es = Params('Environment simulator', 'simulate evolution via parametric changes')
es.add_param('orbit', 'planet')
es.add_param('dist_to_sun', 'planet')
es.add_param('num_moons', 'planet')
es.add_par... |
from django.conf.urls import patterns, url
from django.http import Http404
from multiurl import ContinueResolving, multiurl
from .views import (AlbumDetailView, SingleDetailView, TrackDetailView,
TrackLyricsView)
urlpatterns = patterns('',
# MultiURL allows us to unite all of the music under a simpler URL.
... |
# -*- coding: utf-8 -*-
from weakref import WeakKeyDictionary, proxy
import attr
from cached_property import cached_property
class AppliancePluginException(Exception):
"""Base class for all custom exceptions raised from plugins."""
@attr.s(slots=True)
class AppliancePluginDescriptor(object):
cls = attr.ib(... |
import discord
from discord.ext import commands
import brawlstats
BOTCOMMANDER_ROLES = ["Family Representative", "Clan Manager",
"Club Manager", "Club Deputy", "Vice President",
"Clan Deputy", "Co-Leader", "Hub Officer", "admin"]
creditIcon = "https://i.imgur.com/TP8GXZb.pn... |
# -*- coding: utf-8 -*-
"""
mygeotab.cli
~~~~~~~~~~~~
Console utilities for working with the MyGeotab API.
"""
import os.path
import sys
import click
import mygeotab
import mygeotab.api
import mygeotab.dates
from six.moves import configparser
class Session(object):
"""The console session object."""
de... |
"""A Postgresql serializer for Spyne objects.
Uses SQLAlchemy for mapping objects to relations.
"""
from spyne.store.relational._base import add_column
from spyne.store.relational._base import gen_sqla_info
from spyne.store.relational._base import gen_spyne_info
from spyne.store.relational._base import get_pk_columns... |
import unittest
import numpy as np
import six
from chainer import computational_graph as c
from chainer import function
from chainer import testing
from chainer import variable
class MockFunction(function.Function):
def __init__(self, n_in, n_out):
self.n_in = n_in
self.n_out = n_out
def f... |
# -*- test-case-name: vumi.transports.twitter.tests.test_twitter -*-
from twisted.python import log
from twisted.internet.defer import inlineCallbacks
from txtwitter.twitter import TwitterClient
from txtwitter import messagetools
from vumi.transports.base import Transport
from vumi.config import ConfigBool, ConfigText... |
# -*- coding: utf-8 -*-
# 经纬度坐标转换
# 用于百度坐标系(bd-09)、火星坐标系(国测局坐标系、gcj02)、WGS84坐标系的相互转换
# Created Time: 2017年05月17日 星期三 15时04分51秒
from src.utils.coordTransform import CoordTransform
class Transform:
"""
经纬度坐标转换,支持以下坐标:
bd09: 百度坐标系
gcj02: 火星坐标系(国标)。中国标准,从国行移动设备中定位获取的坐标数据使用这个坐标系
wgs84: 国际... |
"""A setuptools based setup module.
See:
https://packaging.python.org/en/latest/distributing.html
https://github.com/pypa/sampleproject
"""
# Always prefer setuptools over distutils
from setuptools import setup, find_packages
# To use a consistent encoding
from codecs import open
from os import path
here = path.abspa... |
#!/usr/bin/env python
# encoding: utf-8
from argparse import ArgumentParser
import os
import platform
PLATFORM_NAME = platform.system()
class WhichCommand(object):
def __init__(self, name):
self.name = name
@property
def path_list(self):
path = os.environ.get("PATH", "")
... |
import argparse
import glob
import os
import re
import shutil
import subprocess
import sys
import tempfile
import zipfile
_IGNORED_PATTERNS = [
# Ignored because they're not indicative of specific errors.
re.compile(r'^$'),
re.compile(r'^Analyzing \['),
re.compile(r'^No issues found'),
re.compile(r'^[0-9]+ e... |
from samba.tests import TestCase
import os
import samba
from samba.credentials import Credentials
from samba.dcerpc import netlogon
from samba import NTSTATUSError, ntstatus
import ctypes
"""
Tests whether the netlogon service is running
"""
class NetlogonServiceTests(TestCase):
def setUp(self):
super(N... |
#!/usr/bin/python3
"""
Write an iterator that iterates through a run-length encoded sequence.
The iterator is initialized by RLEIterator(int[] A), where A is a run-length
encoding of some sequence. More specifically, for all even i, A[i] tells us the
number of times that the non-negative integer value A[i+1] is repea... |
import unittest
import weakref
import Gaffer
class WeakMethodTest( unittest.TestCase ) :
def test( self ) :
class A() :
def f( self ) :
return 10
a = A()
w = weakref.ref( a )
wm = Gaffer.WeakMethod( a.f )
self.assertEqual( w(), a )
self.assertEqual( wm(), 10 )
self.failUnles... |
from openerp import api, exceptions, fields, models, _
class AccountInvoiceLine(models.Model):
_inherit = 'account.invoice.line'
vat_prorrate_percent = fields.Float(string="Prorrate perc.", default=100)
@api.multi
@api.constrains('vat_prorrate_percent')
def check_vat_prorrate_percent(self):
... |
# -*- coding: utf-8 -*-
from nose.tools import eq_
import bot_mock
from pyfibot.modules import module_urltitle
bot = bot_mock.BotMock()
def test_one():
msg = "https://en.wikipedia.org/wiki/Hatfield–McCoy_feud"
module_urltitle.init(bot)
eq_(("#channel", u"Title: The Hatfield–McCoy feud involved two famil... |
from django.utils.text import capfirst, get_text_list
from django.utils.encoding import force_unicode
def construct(request, form, formsets):
"""
Construct a change message from a changed object.
"""
change_message = []
if form.changed_data:
try:
form.changed_data.remov... |
from __future__ import with_statement
import pytest
import time
import redis
from redis.exceptions import ConnectionError
from redis._compat import basestring, u, unichr, b
from .conftest import r as _redis_client
from .conftest import skip_if_server_version_lt
def wait_for_message(pubsub, timeout=0.1, ignore_subsc... |
import os
import sys
import json
import argparse
from girder_client import GirderClient, HttpError
def import_calc(config):
try:
target_port = None
if config.port:
target_port = config.port
target_scheme = None
if config.scheme:
target_scheme = config.scheme
... |
# -*- coding: utf-8 -*-
import random
from openerp import SUPERUSER_ID
from openerp.osv import osv, orm, fields
from openerp.addons.web.http import request
class payment_transaction(orm.Model):
_inherit = 'payment.transaction'
_columns = {
# link with the sale order
'sale_order_id': fields.m... |
import sys
import os
from scrapy.commands import ScrapyCommand
from scrapy.exceptions import UsageError
class Command(ScrapyCommand):
requires_project = True
default_settings = {'LOG_ENABLED': False}
def syntax(self):
return "<spider>"
def short_desc(self):
return "Edit spider"
... |
from .test_server import ServerTestCase
import json
import codecs
import library.session as session
from library.app import app
import library.database as database
class LdapStub:
def __init__(self):
self.user = None
self.password = None
self.return_value = True
self.raise_error = ... |
#!/usr/bin/env python
import vtk
from vtk.test import Testing
from vtk.util.misc import vtkGetDataRoot
VTK_DATA_ROOT = vtkGetDataRoot()
# create a rendering window and renderer
ren1 = vtk.vtkRenderer()
ren1.SetBackground(0,0,0)
renWin = vtk.vtkRenderWindow()
renWin.AddRenderer(ren1)
renWin.SetSize(300,300)
iren = vtk.... |
from pynitefields import *
class Curve():
""" Class to hold all points in a curve.
Curves are sets of points of the form :math:`(\\alpha, c(\\alpha)` for
all :math:`\\alpha` in a specified GaloisField, where
.. math::
c(\\alpha) = c_0 + c_1 \\alpha + c_2 \\alpha^2 + ...
... |
from __future__ import absolute_import
from django import forms
from django.db.models import Q
from django.contrib.auth.models import Group
from osf.models import AdminProfile
class LoginForm(forms.Form):
email = forms.CharField(label=u'Email', required=True)
password = forms.CharField(
label=u'Pass... |
# Imports
from subprocess import Popen, PIPE
from os.path import expanduser
from ouimeaux.environment import Environment
from datetime import datetime, timedelta
import xml.etree.cElementTree as ET
# Functions
def startWeMoEnvironment():
"Starts the WeMo environment"
env = Environment()
env.start()
ret... |
# Time: O(n * l), n is the length of S, l is the average length of words
# Space: O(t) , t is the size of trie
import collections
import functools
try:
xrange # Python 2
except NameError:
xrange = range # Python 3
class Solution(object):
def boldWords(self, words, S):
"""
:... |
"""
Hubs and authorities analysis of graph structure.
"""
#!/usr/bin/env python
# Copyright (C) 2008-2010 by
# Aric Hagberg <<EMAIL>>
# Dan Schult <<EMAIL>>
# Pieter Swart <<EMAIL>>
# All rights reserved.
# BSD license.
# NetworkX:http://networkx.lanl.gov/
__author__ = """Aric Hagberg (<EMAIL>)""... |
# -*- coding: utf-8 -*-
"""PowPySol-GUI - A graphical user interface for the PowPySol-tool:
Matplotlib integration
Copyright (C) 2014 Jan M. Simons <<EMAIL>>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public Licens... |
"""catmon logging config."""
dictLogConfig = {
'version': 1,
'handlers': {
'basicHandler':{
'class': 'logging.FileHandler',
'level': 'INFO',
'formatter': 'myFileFormatter',
'filename': 'catmon.log'
},
'fileHandler':{
... |
from boto.sqs.message import MHMessage
from boto.exception import SQSDecodeError
import base64
import simplejson
class JSONMessage(MHMessage):
"""
Acts like a dictionary but encodes it's data as a Base64 encoded JSON payload.
"""
def decode(self, value):
try:
value = base64.b64deco... |
import os
import random
import requests
from cloudbot import hook
from cloudbot.util.http import parse_soup
search_url = "https://www.dogpile.com/search"
CERT_PATH = 'dogpile.crt'
HEADERS = {
'User-Agent': 'Mozilla/5.0 (Linux; Android 4.0.4; Galaxy Nexus Build/IMM76B) AppleWebKit/535.19 '
'(KH... |
from SimpleCV.base import *
from SimpleCV.Features.Features import Feature, FeatureSet
from SimpleCV.Color import Color
from SimpleCV.ImageClass import Image
class FeatureExtractorBase(object):
"""
The featureExtractorBase class is a way of abstracting the process of collecting
descriptive features within ... |
"""I am the Twisted.Web error resources and exceptions."""
#t.w imports
import resource
from twisted.protocols import http
class Error(Exception):
def __init__(self, code, message = None, response = None):
message = message or http.responses.get(code)
Exception.__init__(self, code, message, respo... |
from flask import Flask
from flask import request
from flask import Response
from flask import abort
import json
import logging
import requests
import urllib
import flames_controller
import poofermapping
import pattern_manager
import triggers
PORT = 5000
HYDRAULICS_PORT = 9000
hydraulics_addr = "noetica-hydraulics.lo... |
import mock
def dataProvider(fn_data_provider):
"""
Data provider decorator, allows another callable to provide the data for
the test. This is a nice feature from PHPUnit which is very useful. Am
sticking with the JUnit style naming as unittest does this already.
Implementation based on:
ht... |
#!/usr/bin/python
from basesite import basesite
from time import sleep
from threading import Thread
import os
class fapdu(basesite):
""" Parse/strip URL to acceptable format """
def sanitize_url(self, url):
if not 'fapdu.com/' in url:
raise Exception('')
if '.view/' in url:
url = url[:url.find('.view/')+l... |
"""
Unit tests for :func:`iris.fileformats.name_loaders._build_cell_methods`.
"""
# Import iris.tests first so that some things can be initialised before
# importing anything else.
import iris.tests as tests # isort:skip
from unittest import mock
import iris.coords
from iris.fileformats.name_loaders import _build_... |
from kerapu.boom.boom_parameter.BoomParameter import BoomParameter
from kerapu.lbz.Subtraject import Subtraject
class ZorgActiviteitCode(BoomParameter):
"""
Klasse voor boomparameter zorgactiviteit.
Boomparameternummers: 300, 400, 500.
"""
# ------------------------------------------------------... |
"""
根据.podspec构建
依赖pod package进行构建,若未安装package,请使用sudo gem install cocoapods-packager安装package
"""
import os
specslist = (
"https://github.com/CocoaPods/Specs.git",
)
usingSpec = True
# debug模式
debug = False
# 每次编译是否清除缓存
forceClean = True
# 生成.a静态,否则生成为framework
generateStaticLibrary = True
# 生成动态框架
generat... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django import forms
from django.utils.translation import ugettext_lazy as _
from django.utils.text import capfirst
from django.contrib.auth.forms import ReadOnlyPasswordHashField
from django.contrib.auth import authenticate, get_user_model
class Lo... |
from __future__ import absolute_import, division, print_function, unicode_literals
import braintree
from braintree.test.nonces import Nonces
from gratipay.billing.exchanges import cancel_card_hold
from gratipay.models.exchange_route import ExchangeRoute
from gratipay.testing import Harness
from gratipay.testing.vcr i... |
from __future__ import print_function
import csv
import re
from os import walk
from pdb import set_trace
from scipy.io.arff import loadarff
def do():
print('Doing')
for (a, b, c) in walk('./'):
pass
for file in c:
if 'arff' in file:
# set_trace()
print(a + '/' + f... |
import logging
import serial
import time
logger = logging.getLogger(__name__)
class LuxBusDevice(object):
def __init__(self, port, baudrate=115200, addr=0x00, flags=0x00):
self.ser = serial.Serial(port, baudrate)
self.addresses = {}
def close(self):
self.ser.close()
def raw_packe... |
#!/usr/bin/env python
# pylint: disable=C0103,R0911,R0912,R0915
# disable short-variable-names, too many branches, returns, statements
"""
fingerprint fuzzer and generator
Given a fingerprint, this generates other similar fingerprints
that are functionally equivalent for SQLi detection
"""
import sys
class PermuteFi... |
from mongo_pm2 import MongoDriverPM2
import pymongo
import pymongo.errors
import time
from multiprocessing import Pool
from pyehr.ehr.services.dbmanager.querymanager.results_wrappers import ResultSet,\
ResultColumnDef, ResultRow
from pyehr.ehr.services.dbmanager.errors import *
try:
import simplejson as json
... |
from freepy.lib.actors.actor import Actor
from freepy.lib.actors.utils import object_fqn
from freepy.lib.server import RouteMessageCommand, ServerDestroyEvent, ServerInitEvent
from llist import dllist
from threading import Thread
import logging
import time
class ReceiveTimeoutCommand(object):
def __init__(self, sen... |
from base64 import b16encode, b32decode
from datetime import timedelta
from hashlib import sha1
from urlparse import urlparse
import os
from couchpotato.core._base.downloader.main import DownloaderBase, ReleaseDownloadList
from couchpotato.core.event import addEvent
from couchpotato.core.helpers.encoding import sp
fro... |
'''
http://insight.bitpay.com/
'''
import logging
from lib import config, util
def get_host():
if config.BLOCKCHAIN_SERVICE_CONNECT:
return config.BLOCKCHAIN_SERVICE_CONNECT
else:
return 'https://insight.czarcoin.co' if config.TESTNET else 'https://insight.czarcoin.co'
def check():
result... |
import contextlib
import unittest
import aioxmpp
import aioxmpp.carbons.service as carbons_service
import aioxmpp.carbons.xso as carbons_xso
import aioxmpp.service
from aioxmpp.utils import namespaces
from aioxmpp.testutils import (
make_connected_client,
CoroutineMock,
run_coroutine,
)
TEST_JID = aiox... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.