src stringlengths 721 1.04M |
|---|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2015-2016: Alignak team, see AUTHORS.txt file for contributors
#
# This file is part of Alignak.
#
# Alignak is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free So... |
#!/usr/bin/env python
# encoding: utf-8
from pandocfilters import walk, stringify, Para
import re
import json
import sys
def purify(k, v, fmt, meta):
"""
First Step: Remove nonsense from unoconv
"""
if k == 'Span':
return [stringify(v[1])]
inselection = False
def phaseSelection(k, v, fmt, m... |
# Generated by Django 3.1.4 on 2021-02-01 14:12
import os
from django.conf import settings
from django.db import migrations
from django.utils.text import slugify
from translate.misc.xml_helpers import valid_chars_only
from weblate.formats.ttkit import TBXFormat
from weblate.utils.hash import calculate_hash
from webl... |
# coding:utf-8
__author__ = "seerjk"
# 简单的nginx日志分析
# 日志文件在/home/shre/www_access_20140823.log
# 61.159.140.123 - - [23/Aug/2014:00:01:42 +0800] "GET /favicon.ico HTTP/1.1" 404 \ "-" "Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.66 Safari/537.36 LBBROWSER" "-"
# 期望输出一个list,分别存储这h... |
import os, sys
import cv2
import atb
import numpy as np
from plugin import Plugin
from time import strftime,localtime,time,gmtime
from ctypes import create_string_buffer
from git_version import get_tag_commit
class Recorder(Plugin):
"""Capture Recorder"""
def __init__(self, session_str, fps, img_shape, shared_... |
from django.conf import settings
from django.core.paginator import EmptyPage, PageNotAnInteger, Paginator
from django.http.response import HttpResponseRedirect
from django.shortcuts import render_to_response, get_object_or_404
from django.template.context import RequestContext
from mezzanine.utils.email import send_mai... |
#
from setuptools import setup, find_packages
import sys, os
version = "1.0"
shortdesc = ""
longdesc = open(os.path.join(os.path.dirname(__file__), 'README.rst')).read()
setup(name="agx.dexteritytemplate",
version=version,
description=shortdesc,
long_description=longdesc,
classifiers=[
... |
# TODO: add Group and/or Selection
class Region(object):
""" Base class for a spatial Region container
A Region can contain simple and advanced geometry.
A Region can be thought of as a 3D analogy to a sheet of
paper in 2D. A Region defines its own coordinate system,
dimension and resolution.
... |
#!/usr/bin/env python3
#######################################################################################################################
#
# DATE: 2017-12-15
# NAME: build_Event2Transcript_index.py
# AUTHOR: Jeremy R. B. Newman (jrbnewman@ufl.edu)
#
# DESCRIPTION: This script creates an intron-to-border junction ... |
"""
Editor for editing the cameras ori files
"""
# Imports:
from traits.api \
import HasTraits, Code, Int, List, Str, Button, Float, Instance, Directory, File
from traitsui.api \
import Item, Group, View, Handler, Tabbed, ListEditor
from traitsui.menu import MenuBar, ToolBar, Menu, Action, OKCance... |
#! /usr/bin/python3
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import numpy as np
import sys
first = True
s = 2e-5
eta_contour_levels = np.append(np.arange(-1e-4, 0, s), np.arange(s, 1e-4, s))
hs = 5
h_contour_levels = np.append(np.arange(900, 1000-hs, hs), np.arange(1000+hs, 1100, hs))... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Run tests for this base image.
Each test must be a valid docker-compose.yaml file with a ``odoo`` service.
"""
import logging
import unittest
from itertools import product
from os import environ
from os.path import dirname, join
from subprocess import Popen
logging.ba... |
# -*- encoding: utf-8 -*-
################################################################################
# #
# Copyright (C) 2013-Today Carlos Eduardo Vercelino - CLVsol #
# ... |
# coding: utf-8
# ### Sentiment Analysis on "Jallikattu" with Twitter Data Feed <h3 style="color:red;">#DataScienceForSocialCause</h3>
#
# Twitter is flooded with Jallikattu issue, let us find peoples sentiment with Data Science tools. Following is the approach
# * Register a Twitter API handle for data feed
# * Pul... |
from django import forms
from django.conf import settings
from django.utils.translation import ugettext_lazy as _
from modelforms.forms import ModelForm
from touchtechnology.common.forms.mixins import (
BootstrapFormControlMixin, SuperUserSlugMixin,
)
from touchtechnology.news.models import Article, Category, Trans... |
import os
import sys
import re
from kitchen.text.converters import to_bytes
import irc
import plugins.BasePlugin
import random
import plugins.MiniSandbox
class InterpreterPlugin(plugins.BasePlugin.BasePlugin, object):
name = None
author = None
description = None
connection = None
interpreter_comm... |
from _common import *
if has_qt4:
from PyQt4 import QtGui, QtCore
from PyQt4.QtCore import Qt
import srllib.qtgui.widgets
if has_qt4:
class _LineEdit(srllib.qtgui.widgets._LineEditHelper,
guimocks.QLineEditMock):
_qbase = __qbase = guimocks.QLineEditMock
def __init__(self... |
from numpy import zeros
from cosmoslik import Likelihood, SubprocessExtension
import os
class wmap(Likelihood):
"""
===============
WMAP Likelihood
===============
- Written by WMAP team (see `<http://lambda.gsfc.nasa.gov/>`_)
- CosmoSlik module by Marius Millea
- Updated July 1, 2012
... |
# Copyright (C) 2007 Samuel Abels, http://debain.org
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2, as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOU... |
import networkx as nx
import random
class VaxGame:
"""Stores the state of the Vax game, including the main graph.
stage - stage of main game (see enum below)
graph - main game NetworkX graph object
status - an array indexed by node integer of node state (see enum below)
orig_num_nodes - original ... |
import time
from django.contrib.auth import logout
from ..apps.sessionmgmt.models import TrustedSession
class SessionManagementMiddleware:
"""
Handles session management.
"""
def __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
if requ... |
import feedparser
import pprint
import time
print(feedparser.__version__)
# 5.2.1
d_atom = feedparser.parse('http://gihyo.jp/feed/atom')
print(type(d_atom))
# <class 'feedparser.FeedParserDict'>
pprint.pprint(d_atom, depth=1)
# {'bozo': 0,
# 'encoding': 'UTF-8',
# 'entries': [...],
# 'feed': {...},
# 'headers':... |
# Tests that require installed backends go into
# sympy/test_external/test_autowrap
import os
import tempfile
import shutil
from sympy.core import symbols, Eq
from sympy.core.compatibility import StringIO
from sympy.utilities.autowrap import (autowrap, binary_function,
CythonCodeWrapper, UfuncifyCodeWrapp... |
"""
Support for custom structures in client and server
We only support a subset of features but should be enough
for custom structures
"""
import os
import importlib
import re
import logging
# The next two imports are for generated code
from datetime import datetime
import uuid
from enum import Enum, IntEnum, EnumMeta... |
# coding: utf-8
# -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# --------------------------------------------------------------------... |
# -*- coding: utf-8 -*-
"""
Copyright (C) 2016 Dariusz Suchojad <dsuch at zato.io>
Licensed under LGPLv3, see LICENSE.txt for terms and conditions.
"""
from __future__ import absolute_import, division, print_function, unicode_literals
# stdlib
import itertools
from urlparse import urlparse
# ipaddress
from ipaddre... |
import numpy as np
from numpy.testing import assert_allclose
import random
import math
from menpo.image import MaskedImage
import menpo.io as mio
def test_imagewindowiterator_hog_padding():
n_cases = 5
image_width = np.random.randint(50, 250, [n_cases, 1])
image_height = np.random.randint(50, 250, [n_cas... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import httplib
#import re
#import sys
import os
import Cookie
import string, xbmc, xbmcgui, xbmcplugin, urllib, cookielib, xbmcaddon
#-------------------------------
import urllib, urllib2, time, random
#from time import gmtime, strftime
#from urlparse import urlparse
impo... |
#!/usr/bin/python
import os,sys
ncs_lib_path = ('../../../../python/')
sys.path.append(ncs_lib_path)
import ncs
def Run(argv):
sim = ncs.Simulation()
excitatory_parameters = sim.addNeuron("label_excitatory",
"izhikevich",
... |
# hgweb/wsgicgi.py - CGI->WSGI translator
#
# Copyright 2006 Eric Hopper <hopper@omnifarious.org>
#
# This software may be used and distributed according to the terms of the
# GNU General Public License version 2, incorporated herein by reference.
#
# This was originally copied from the public domain code at
# http://w... |
#!/usr/bin/env python
#coding:utf-8
import requests
import time
import sys
import os
from bs4 import BeautifulSoup as bss
import threading
import smtplib
from email.mime.text import MIMEText
from email.header import Header
mylock = threading.Lock()
global prtnum
prtnum=dict()
## 定义2420打印机类
class th24(threading.Thread)... |
from vsg import parser
from vsg import rule
from vsg import violation
from vsg.rules import utils as rules_utils
from vsg.vhdlFile import utils
class single_space_between_tokens(rule.Rule):
'''
Checks for a single space between two tokens.
Parameters
----------
name : string
The group... |
# -*- coding: utf-8 -*-
'''
Created on 19 Sep 2012
@author: piel
Copyright © 2012-2013 Éric Piel & Kimon Tsitsikas, Delmic
This file is part of Odemis.
Odemis is free software: you can redistribute it and/or modify it under the terms
of the GNU General Public License version 2 as published by the Free Software
Fo... |
# Copyright (c) 2013 Qubell Inc., http://qubell.com
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... |
# Copyright 2014 Scality
# All Rights Reserved.
#
# 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 appli... |
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2013 Rackspace
# All Rights Reserved.
#
# 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/licen... |
#!/usr/bin/env python3
import random, pickle, sys, cmd
class Dice:
""" Contains x dice with n sides, or a plain modifier """
def __init__(self, dice):
""" Either takes in a string with a modifier, such as +4, or a dice description, such as 2d8 """
if dice[0] in ("+", "-"):
self.mod = int(dice)
self.num, se... |
"""Unittests for the pymp package."""
# pylint: disable=protected-access, invalid-name
from __future__ import print_function
import logging
import unittest
logging.basicConfig(level=logging.INFO)
class ParallelTest(unittest.TestCase):
"""Test the parallel context."""
def test_init(self):
"""Initia... |
# vim: noexpandtab:ts=4:sw=4
# This file is part of ReTextWiki
# Copyright: CKolumbus (Chris Drexler) 2014
# License: GNU GPL v2 or higher
import os
import markups
from subprocess import Popen, PIPE
from ReText import QtCore, QtPrintSupport, QtGui, QtWidgets, QtWebKitWidgets, \
icon_path, DOCTYPE_MARKDOWN, DOCTYPE... |
## NIFTY (Numerical Information Field Theory) has been developed at the
## Max-Planck-Institute for Astrophysics.
##
## Copyright (C) 2013 Max-Planck-Society
##
## Author: Marco Selig
## Project homepage: <http://www.mpa-garching.mpg.de/ift/nifty/>
##
## This program is free software: you can redistribute it and/or mod... |
#!/usr/bin/python2
# DNT: a satirical post-apocalyptical RPG.
# Copyright (C) 2005-2013 DNTeam <dnt@dnteam.org>
#
# This file is part of DNT.
#
# DNT is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, ei... |
import os
from setuptools import setup
README = open(os.path.join(os.path.dirname(__file__), 'README')).read()
setup(
zip_safe=False,
name='django-lavaflow',
version='1.1',
packages=['lavaFlow'],
include_package_data=True,
license="GPL 3",
description="LavaFlow creates useful reports on the usage of hi... |
from PyQt5.QtWidgets import (QWidget, QFrame, QLabel, QPushButton, QComboBox, QLineEdit,QTextEdit, QGridLayout, QApplication, QHBoxLayout, QRadioButton)
import logging
class AlgorithmRadioButton(QRadioButton):
def __init__(self, text, id=None, group=None):
super().__init__(text)
self.algorithmId = ... |
# -*- coding: utf-8 -*-
import csv
import codecs
from cStringIO import StringIO
from zipfile import ZipFile
# prepare a single csv file to download
def single_file( file_descr ):
from sqldb import Collection
# if it's a full collection - read it from server
endpoint = file_descr['endpoint']
try:
... |
# Copyright 2015 EMC Corporation
from flocker.node import BackendDescription, DeployerType
from .emc_sio import (
scaleio_from_configuration, DEFAULT_STORAGE_POOL,
DEFAULT_PROTECTION_DOMAIN, DEFAULT_PORT, DEBUG
)
def api_factory(cluster_id, **kwargs):
protection_domain = DEFAULT_PROTECTION_DOMAIN
if ... |
#!/usr/bin/env python
from __future__ import print_function
from builtins import range
import sys
import pmagpy.pmag as pmag
def main():
"""
NAME
agm_magic.py
DESCRIPTION
converts Micromag agm files to magic format
SYNTAX
agm_magic.py [-h] [command line options]
OPTIO... |
import errno
import json
import os
from datetime import datetime
from smart_open import smart_open
from crashsimilarity.downloader import SocorroDownloader
def utc_today():
return datetime.utcnow().date()
def read_files(file_names, open_file_function=smart_open):
for name in file_names:
with open_... |
###########################################################
#
# Copyright (c) 2015, Southpaw Technology
# All Rights Reserved
#
# PROPRIETARY INFORMATION. This software is proprietary to
# Southpaw Technology, and is not to be reproduced, transmitted,
# or disclosed in any way without written permi... |
# -*- coding: utf-8 -*-
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from qgis.core import *
from qgis.gui import *
from ui_widgetTranslate import Ui_GdalToolsWidget as Ui_Widget
from widgetBatchBase import GdalToolsBaseBatchWidget as BaseBatchWidget
from dialogSRS import GdalToolsSRSDialog as SRSDialog
import... |
#!/usr/bin/python3
import socket
import os
import sys
import logging as log
import getpass
from helper import *
log.basicConfig(format="[%(levelname)s] %(message)s", level=log.DEBUG)
class FTPError(Exception):
pass
class FTPClient:
def __init__(self):
self.sock = None
self.is_connected =... |
import view
import wx
import wx.gizmos as gizmos
from cuttlebug.ui.controls import DictListCtrl
from cuttlebug.util import ArtListMixin, has_icon, bidict, KeyTree, str2int
from functools import partial
import cuttlebug.gdb as gdb
import os, threading
import cuttlebug.ui.menu as menu
import cuttlebug.settings a... |
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# MIT License. See license.txt
from __future__ import unicode_literals
import frappe
import os
from frappe.model.document import Document
from frappe.build import html_to_js_template
from frappe.model.utils import render_include
from frappe import co... |
#! /usr/bin/env python3
"""Create a media website"""
import media
import fresh_tomatoes
def main():
# Create
grand_budapest_hotel = media.Movie(
"The Grand Budapest Hotel",
"The adventures of Gustave H, a legendary concierge at The \
Grand Budapest Hotel",
"https://upload.wik... |
from zope.interface import Interface
# -*- Additional Imports Here -*-
from zope import schema
from leam.stress import stressMessageFactory as _
class IStressAnalysis(Interface):
"""Frontend to the LEAM Stress Analysis Model"""
# -*- schema definition goes here -*-
layer = schema.Object(
title=... |
import functools
import os
import pkgutil
import sys
from collections import OrderedDict, defaultdict
from contextlib import suppress
from importlib import import_module
import django
from django.apps import apps
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from django.core.... |
ARRUMAR
import Pmw
import Tkinter as tk
import matplotlib as mpl
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.widgets import Slider, Button
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from os import chdir,listdir,path,getcwd
import read_signal as rs
class PlotWindow():
de... |
from decimal import Decimal
import unittest
from .helpers import *
from .. import *
from ..engine import *
class TestTimingEngine(unittest.TestCase):
def test_init(self):
timing_data = testing_timing_data()
engine = TimingEngine(timing_data)
self.assertEqual(timing_data, engine.timing_dat... |
from enum import Enum
import csv
import math
from sklearn import tree
from sklearn.ensemble import RandomForestClassifier
class LearningAlgorithms(Enum):
cart = 0,
random_forest = 1
class RandomForestsConfig:
def __init__(self, n_tree, max_features):
self.n_tree = n_tree
self.max_feature... |
# -*- coding: utf-8 -*-
# Copyright (c) 2017, Frappe Technologies Pvt. Ltd. and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe
import calendar
from frappe import _
from frappe.desk.form import assign_to
from frappe.utils.jinja import validate_templa... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Copyright 2010-2012 Asidev s.r.l.
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 b... |
# -*- coding: utf-8 -*-
# Copyright 2020 Google LLC
#
# 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... |
"""
Class for planning with an augmented linear-quadratic regulator (aLQR)
on a given system and associated with a given cost field.
The system must be linearizable, time-invarient, and control affine:
xdot = f(x) + B(x)*u with jac(f)|x_i = A_i such that
xdot = A_i*x + B(x_i)*u is accurate near x_i.
After running... |
# This program is free software; you can redistribute it and/or modify it under
# the terms of the GNU Lesser General Public License as published by the Free Software
# Foundation; either version 2 of the License, or (at your option) any later
# version.
# copyright 2003-2010 LOGILAB S.A. (Paris, FRANCE), all rights re... |
#!/usr/bin/env python
#coding:utf-8
# Purpose: test spreadpage body
# Created: 29.01.2011
# Copyright (C) 2011, Manfred Moitzi
# License: MIT
from __future__ import unicode_literals, print_function, division
__author__ = "mozman <mozman@gmx.at>"
# Standard Library
import unittest
# trusted or separately t... |
from sovrin_client.test import waits
from stp_core.loop.eventually import eventually
from anoncreds.protocol.types import SchemaKey, ID
from sovrin_client.test.agent.messages import get_claim_request_libsovrin_msg
def test_claim_request_from_libsovrin_works(
aliceAgent,
aliceAcceptedFaber,
ali... |
from __future__ import division
from math import log, sqrt, pi
from barak.utilities import adict
from barak.absorb import split_trans_name
from barak.io import parse_config, loadobj
from barak.interp import AkimaSpline, MapCoord_Interpolator
from cloudy.utils import read_observed
import numpy as np
import os
from glob... |
# coding: utf-8
import re
import string
from unicodedata import normalize
from arpeggio import ParserPython, PTNodeVisitor, visit_parse_tree, Optional, ZeroOrMore, OneOrMore, EOF
from arpeggio import RegExMatch as _
from syntax_tree import SyntaxNode, SyntaxTreeEvaluator
DEBUG = False
def token_and(): return _(u... |
# -*- coding: utf-8 -*-
import random
from imageporndirtyrubot.exception import APIException, GoogleCaptchaAPIException
try:
import urlparse
except ImportError:
import urllib.parse as urlparse
from bs4 import BeautifulSoup
import requests
USER_AGENTS = [
'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit... |
# Copyright 2020 Google LLC
#
# 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 writing, ... |
# Copyright (C) 2011 Dustin Spicuzza
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2, or (at your option)
# any later version.
#
# This program is distributed in the hope that... |
# -*- coding: us-ascii -*-
# vim:ts=4:sw=4:softtabstop=4:smarttab:expandtab
#
import json
import urllib
import redis
from django.core.exceptions import PermissionDenied
from django.http import Http404, HttpResponse
from django.utils.safestring import mark_safe
from django.utils.html import strip_tags
from django.vie... |
import os.path
import tornado.ioloop
import tornado.web
import tornado.options
import tornado.httpserver
import mongoengine
from models import Challenge, ChallengePoint
from tornado.options import define, options
define("port", default=8000, help="run on the given port", type=int)
class Application(tornado.web.App... |
# -*- coding: utf-8 -*-
from decimal import Decimal
from django.db import models
from django.utils.translation import ugettext_lazy as _
from parler.managers import TranslatableQuerySet
from parler.models import TranslatableModel, TranslatedFields
import datetime
import random
CAMPAIGN_CODE_KEYSPACE = "acdefghkmnpq... |
#!/usr/bin/python
from time import sleep
import os
import sys
import subprocess
from subprocess import Popen
import RPi.GPIO as GPIO
# global variables for commands and status
global alertcmd
alertcmd = "/opt/doorbell/ringer.py"
bellButtonPin=26
# board pin numbers are easier for me. If I move to another RPI versio... |
#!/usr/bin/env python
# vim: set fileencoding=utf-8 :
# Chi ho CHAN <c.chan@surrey.ac.uk>
# Wed Jan 29 16:29 CEST 2014
# This file contains the python (distutils/setuptools) instructions so your
# package can be installed on **any** host system. It defines some basic
# information like the package name for instance, o... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
rq command line tool
"""
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import click
import redis
from rq import get_failed_queue, Queue, use_connection
from rq.exceptions import InvalidJobOperationError
fr... |
import _ffi
import _rawffi
import weakref
import sys
SIMPLE_TYPE_CHARS = "cbBhHiIlLdfguzZqQPXOv?"
from _ctypes.basics import _CData, _CDataMeta, cdata_from_address,\
CArgObject
from _ctypes.builtin import ConvMode
from _ctypes.array import Array
from _ctypes.pointer import _Pointer, as_ffi_pointer
#from _ctypes.... |
__author__ = 'corbinq27'
import re
import json
import urllib2
#fairly specialized python script to extract prices from specific pages on wholesalegaming.biz
class ProductExtractor():
def __init__(self):
pass
def product_extractor(self):
the_magic_regex_string = '<tr bgcolor="#FFFFFF">\r\n ... |
# ----------------------------------------------------------------------
# Numenta Platform for Intelligent Computing (NuPIC)
# Copyright (C) 2013, Numenta, Inc. Unless you have an agreement
# with Numenta, Inc., for a separate license for this software code, the
# following terms and conditions apply:
#
# This progra... |
import uuid
from nose.tools import eq_
from kazoo.testing import KazooTestCase
class KazooCounterTests(KazooTestCase):
def _makeOne(self, **kw):
path = "/" + uuid.uuid4().hex
return self.client.Counter(path, **kw)
def test_int_counter(self):
counter = self._makeOne()
eq_(co... |
import tornado.websocket
from Server.Chat.SimpleTypes import Participant
from Server.Tools.Response.Json import *
class ChatWebSocketManager(tornado.websocket.WebSocketHandler):
"""
The main chat socket manager, which handles both server commands
from the user as well as chat messages themselves.
"""
... |
import urllib2
import time
import json
import os
import shutil
class Model(object):
@staticmethod
def resolve_redirects(url):
try:
return urllib2.urlopen(url), urllib2.urlopen(url).getcode()
except urllib2.HTTPError as e:
if e.code == 429:
time.sleep(20)... |
# Copyright 2011 OpenStack Foundation
# All Rights Reserved.
#
# 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 requ... |
# encoding: utf-8
from gmsdk.api import StrategyBase
from gmsdk import md
from gmsdk.enums import *
import arrow
import time
# 每次开仓量
OPEN_VOL = 5
class SkyPark(StrategyBase):
def __init__(self, *args, **kwargs):
super(SkyPark, self).__init__(*args, **kwargs)
# 上、下轨
self.upr = None
... |
#!/usr/bin/env python
"""
Helper utility to compile / upgrade requirements files from templates.
This only manages dependencies between requirements sources.
The actual compiling is delegated to ``pip-compile`` from the ``pip-tools` package.
NOTE: This utility *must only* use stdlib imports in order to be runnable ev... |
from time import sleep
from datetime import datetime, timedelta
from axpert.protocol import (
CMD_REL, parse_inverter_conf, empty_inverter_conf, CmdSpec
)
from axpert.settings import charger_conf
from axpert.datalogger import get_avg_last
FLOAT_VOL = charger_conf['float_voltage']
ABSORB_VOL = charger_conf['absorb... |
import os
import shutil
import time
import json
from nose.tools import raises
from blimey.agile_keychain._manager._item_manager import ItemManager
from blimey.agile_keychain.data_source import AgileKeychainItem
from blimey.exceptions import ItemNotFoundException
class ItemManagerTest:
_fixture_path = os.path.joi... |
from functools import partial
from mri import _entropy
BLOCK_LEN = _entropy.BLOCK_LEN
def entropy(data, **kwargs):
length = kwargs.get('length', 512)
index = kwargs.get('index', 0)
retsel = kwargs.get('retsel', 0)
return _entropy.entropy512(data, length, index, retsel)
def entropy_file(file_, **kwa... |
"""
flashcards.sets
~~~~~~~~~~~~~~~~~~~
Contain the StudySet object and logic related to it.
"""
from collections import OrderedDict
from flashcards import cards
from flashcards.cards import StudyCard
TITLE_KEY = 'title'
DESC_KEY = 'description'
CARDS_KEY = 'cards'
def create_from_dict(data):
"""
Construct... |
#!/usr/bin/env python
# coding=utf-8
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import absolute_import
import argparse
import hashlib
import inspect
import subprocess
import sys
import os
import urllib2
import shutil
WHEEL_PIP = 'https://pypi.python.org/packages/py2.p... |
# Network module used for all UDP networking aspects of the Gatecrasher script.
# Developed by Michael Telford.
import socket
# Initializes socket with datagram proto and binds to port arg.
def bind(port):
global s
host = ''
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind((host, port))
... |
# blocktag.py
from error import PostgresError
import define as d
import profile
import searchtag
from libweasyl import ratings
from weasyl.cache import region
# For blocked tags, `rating` refers to the lowest rating for which that tag is
# blocked; for example, (X, Y, 10) would block tag Y for all ratings, whereas... |
"""
This module is used by agent to execute spider task.
"""
# pylint: disable=missing-module-docstring
# pylint: disable=missing-class-docstring
# pylint: disable=missing-function-docstring
import asyncio
import os
import logging
import tempfile
import shutil
from urllib.parse import urlparse
from configpa... |
# -*- coding: utf-8 -*-
import re
import decimal
from os import path
from datetime import datetime, date, time, timedelta
from .names import MonthNames
from .utils import absolutize_url, now
class NormalizeSpace(object):
_whitespace_re = re.compile(
ur'[{0}\s\xa0]+'.format(
re.escape(''.jo... |
#!/usr/bin/env python
# Copyright (c) 2014, Jelmer Tiete <jelmer@tiete.be>.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# 1. Redistributions of source code must retain the above copyright
#... |
#!/usr/bin/env python
# debianbts.py - Methods to query Debian's BTS.
# Copyright (C) 2007-2010 Bastian Venthur <venthur@debian.org>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either ve... |
from aiohttp import ClientSession, ClientTimeout, ContentTypeError, web
from multidict import MultiDict
class AsyncTestServer(object):
scopes = {}
def __init__(self, host, port, timeout = 5):
self.host = host
self.port = port
self.timeout = ClientTimeout(total = timeout)
self.app = web.Application()
self.... |
# -*- coding: utf-8 -*-
# -----------------------------------------------------------------------------
# Getting Things GNOME! - a personal organizer for the GNOME desktop
# Copyright (c) 2008-2012 - Lionel Dricot & Bertrand Rousseau
#
# This program is free software: you can redistribute it and/or modify it under
# t... |
import numpy
import pdb
'''This module contains various I/O helper methods'''
def get_coord(filename):
f = file(filename,'r')
# first count number of atoms to instantiate coord array
n = 0
for line in f:
if 'ATOM' in line:
n += 1
coord = numpy.empty((n,3))
pdb_text = [] # w... |
"""
An implementation of PEP 333: Python Web Server Gateway Interface (WSGI).
"""
import os, threading
import Queue
from zope.interface import implements
from twisted.internet import defer
from twisted.python import log, failure
from twisted.web2 import http
from twisted.web2 import iweb
from twisted.web2 import serv... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.