code stringlengths 1 199k |
|---|
"""
Tests for Trial's interaction with the Python warning system.
"""
from __future__ import division, absolute_import
import sys, warnings
from unittest import TestResult
from twisted.python.compat import NativeStringIO as StringIO
from twisted.python.filepath import FilePath
from twisted.trial.unittest import Synchro... |
import _plotly_utils.basevalidators
class UirevisionValidator(_plotly_utils.basevalidators.AnyValidator):
def __init__(self, plotly_name="uirevision", parent_name="cone", **kwargs):
super(UirevisionValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
... |
import argparse
import errno
import ctypes
import csv
import os
import sys
class Statistics:
"""A simple container for mean, median, mode, range, and count
with string formatting"""
def __init__(self, mean, median, mode, rng, count):
self.mean = mean
self.median = median
self.mod... |
import sys
import os
import pickle
import json
import gettext
from tkinter import *
from tkinter import ttk
from tkinter.simpledialog import Dialog
from tkinter import messagebox
from platform import system
from os import walk,path
from CoolProp.CoolProp import PropsSI
def find_data_file(filename):
if getattr(sys, ... |
import array
from ant.fs.command import parse, DownloadRequest, DownloadResponse,\
AuthenticateCommand
def authenticate_command():
command = AuthenticateCommand(
AuthenticateCommand.Type.REQUEST_SERIAL, 123456789)
assert command.get() == array.array('B',
[0x44, 0x04, 0x01, 0x00, ... |
import os
import sys
sys.path.append('..')
sys.path.append("../..")
import sortingHat
import preprocessGroups
import masterSort
import registerStudents
import unittest
import tempfile
from mongoengine import *
from hatServer.models import Students, Groups
import numpy
from variables import *
class SortingHatTest(unitte... |
__author__ = 'breddels'
import sys
import math
import vaex.dataset
import astropy.io.fits
import numpy as np
import logging
logger = logging.getLogger("vaex.file.colfits")
def empty(filename, length, column_names, data_types, data_shapes, ucds, units, null_values={}):
with open(filename, "wb") as f:
logger.debug("pr... |
import sys
if sys.version_info[0] < 3:
raise Exception("Python Version > 3 is required.")
import urllib.request
from subprocess import call
from PIL import Image
zoomLevel = 3 # change this to either 3 or 4, 4 is higher-resolution than 3
layers = ['background', 'enzymes', 'coenzymes', 'substrates',
'regu... |
from .. import Provider as InternetProvider
class Provider(InternetProvider):
replacements = (
("س", "s"),
("ق", "q"),
("ب", "b"),
("خ", "x"),
("ش", "$"),
("َ", "a"),
("ئ", "}"),
("إ", "<"),
("ل", "l"),
("ٰ", "`"),
("ف", "f"),
... |
import unittest
from hamcrest import assert_that, equal_to, contains_string
import webtest
from google.appengine.ext import testbed
from google.appengine.ext import ndb
from guestbook import make_application, Greeting
class HandlerTestCase(unittest.TestCase):
def setUp(self):
self.testbed = testbed.Testbed(... |
import os, sys
import pygame
from pygame.locals import *
from lib.common.framework.xglobals import *
from lib.common.framework.xframework import *
from lib.common.framework.xxml import xml_load
from lib.common.framework.xgame import XGame
class UserInputTest(XGame):
def __init__(self,element):
XGame.__init__(self,el... |
from lib import _db
from lib._db import get_mongodb
from config.config import CONFIG
import os
import tornado.httpserver
import tornado.ioloop
import tornado.web
import tornado.gen
from tornado.options import options
from urls import url_patterns
from motorengine.connection import connect
from settings import settings,... |
import unittest
import sys
from sonLib.bioio import TestStatus, system, getLogLevelString
from cactus.shared.test import getCactusInputs_random
from cactus.shared.test import getCactusInputs_blanchette
from cactus.shared.test import runWorkflow_multipleExamples
from cactus.shared.test import silentOnSuccess
from cactus... |
import requests
data = {
'foo': '\'bar\''
}
response = requests.post('http://example.com/', data=data) |
"""
Tests to check some functionality of `pyplot`
TODO: change the test to a test directory
"""
import pytest
from os import path
from .. import pyplot
from ..configure import Updater
DIRECTORY = path.join(path.dirname(__file__), 'script_dir')
@pytest.mark.parametrize(
"arguments",
[Updater.get_modules(DIRECTOR... |
S = [int(x) for x in input()]
N = len(S)
if S[0] == 0 or S[-1] == 1 or any(S[i] != S[-i - 2] for i in range(N - 1)):
print(-1)
quit()
edge = [(1, 2)]
root, now = 2, 3
for i in range(1, N // 2 + 1):
edge.append((root, now))
if S[i] == 1:
root = now
now += 1
while now <= N:
edge.append((ro... |
from .titanic import utils, ops, digital, gmpmath
from .fpbench import fpcast, fpcparser
from .arithmetic import evalctx, mpnum, interpreter, ieee754, posit, fixed, mpmf
Float = ieee754.Float
IEEECtx = evalctx.IEEECtx
Posit = posit.Posit
PositCtx = evalctx.PositCtx
Fixed = fixed.Fixed
FixedCtx = evalctx.FixedCtx
MPMF =... |
from __future__ import absolute_import
from sfmutils.warc_iter import BaseWarcIter
from datetime import datetime
import pytz
from urllib.parse import urlparse, parse_qs
TYPE_FLICKR_PHOTO = "flickr_photo"
TYPE_FLICKR_SIZES = "flickr_sizes"
class FlickrWarcIter(BaseWarcIter):
def __init__(self, filepaths, limit_owner... |
import os, sys, ujson
from flask import Flask, render_template, url_for
if len(sys.argv) >= 2 and sys.argv[1] == 'prod':
# In production
app = Flask(__name__, static_url_path='/mtg-cube/static')
else:
app = Flask(__name__)
app.debug = True
@app.route('/mtg-cube')
def app_main():
fin = open('data/generated/cub... |
from flask import Blueprint
tasks = Blueprint('tasks', __name__)
from . import celerymail |
from tridesclous import *
from tridesclous.online import HAVE_PYACQ
if HAVE_PYACQ:
from tridesclous.online import *
import pyacq
from pyacq.viewers import QOscilloscope, QTimeFreq
from tridesclous.gui import QT
import pyqtgraph as pg
from tridesclous.autoparams import get_auto_params_for_catalogue, get_aut... |
from __future__ import absolute_import
from .controllers import *
urlpatterns = [
# open api
("/", flower_rec, "POST"),
] |
import PyPR2
import time
import constants
import tinstate
import tininfo
import tinmind
import os
import stat
from twitter import *
from timers import *
TWITTER_STATE_FILE = '/removable/recordings/laststate.txt'
class TextMessage:
pass
class Messenger( timerclient.TimerClient ):
def __init__( self ):
super(Mess... |
import os
import sys
import imp
import time
import yaml
import uuid
import gnupg
import base64
import socket
import pymongo
import hashlib
import requests
import logging
import logging.handlers
from jose import jwt
from datetime import datetime
from binascii import hexlify
from threading import Event
from itertools imp... |
"""
@version: 1.0
@ __author__: kute
@ __file__: utilscore.py
@ __mtime__: 2017/1/4 13:58
IO多路复用(单进程模块多线程)
select 模块
"""
import socket
import select
server = socket.socket()
server.bind(('localhost', 8801))
server.listen()
def multi_select(rlist=None, wlist=None, xlist=None, timeout=None):
r_list, w_list, x_list = ... |
import _plotly_utils.basevalidators
class ShowtickprefixValidator(_plotly_utils.basevalidators.EnumeratedValidator):
def __init__(
self, plotly_name="showtickprefix", parent_name="mesh3d.colorbar", **kwargs
):
super(ShowtickprefixValidator, self).__init__(
plotly_name=plotly_name,
... |
import importlib
import logging
from werkzeug.contrib.cache import RedisCache
from cache import get_cache
from exceptions import MiddleTierException
from security import SecurityHandler, UnauthorizedSecurityException
logger = logging.getLogger()
class CustomKeyHandler(SecurityHandler):
def __init__(self, config):
... |
import collections
import enum
import uqbar.objects
class MyObject:
def __init__(self, arg1, arg2, *var_args, foo=None, bar=None, **kwargs):
self.arg1 = arg1
self.arg2 = arg2
self.var_args = var_args
self.foo = foo
self.bar = bar
self.kwargs = kwargs
class Enumeration... |
from django.conf.urls import patterns, include, url
from django.contrib import admin
from registration.backends.simple.views import RegistrationView
class MyRegistrationView(RegistrationView):
def get_success_url(self,request, user):
return '/ccbclib/home/'
urlpatterns = patterns('',
# Examples:
url... |
__author__ = 'yograterol'
from flask.blueprints import Blueprint
from flask import render_template
site = Blueprint('site', __name__, static_folder='static', template_folder='templates')
@site.route('/', methods=['GET', ])
@site.route('/home/', methods=['GET', ])
@site.route('/index/', methods=['GET', ])
def index():
... |
default_app_config = 'grauth.config.GRAuthConfig' |
"""
Parametric curves (tracks)
==========================
In this library context, *one-parametric curve* (or *track*) is one-dimensional
entity, defined by it's *track function*:
.. math::
\\DeclareMathOperator{\\tf}{tf}
\\vec{r} = \\tf(s), \\quad s_1 \\le s \\le s_2
where :math:`s` is a freely varying curve par... |
from __future__ import unicode_literals
import json
import logging
import os
from uuid import uuid4
import mimeparse
from django.core.exceptions import ObjectDoesNotExist
from django.http import HttpResponse
from django.utils import six
from django.utils.safestring import mark_safe
from django.utils.translation import ... |
from __future__ import print_function
import sys
from xml.etree.ElementTree import ElementTree, Element, tostring, fromstring
from VMManager import VMManager
SR_IOV_GUESTS_PER_NODE=2
SR_IOV_NICS_PER_GUEST=2
NUM_EXISTING_INTERFACES=2
PATH='/home/sdnnfv-admin/provisioning-slave/temp_xml'
sr_iov_networks = ['sr-iov-port0'... |
try:
from unittest import mock # Python 3.3+
except ImportError:
import mock # noqa: Python 2.7
try:
import unittest2 as unittest # Python 2.7
except ImportError:
import unittest # noqa |
"""
brew --- Brew some beer.
========================
"""
__all__ = [
'Brew',
]
class Brew:
"""Brew some beer.
Default values for optional parameters are retrieved from
`configuration`.
Parameters
----------
ingredients : Ingredients
Ingredients.
target_volume : float
The tar... |
import invariants
import pddl
class BalanceChecker(object):
def __init__(self, task):
self.predicates_to_add_actions = {}
for action in task.actions:
for eff in action.effects:
if isinstance(eff.peffect,pddl.Atom):
predicate = eff.peffect.predicate
self.predicates_to_add_acti... |
"""empty message
Revision ID: 489cf746b500
Revises: None
Create Date: 2015-11-20 17:18:29.015000
"""
revision = '489cf746b500'
down_revision = None
from alembic import op
import sqlalchemy as sa
def upgrade():
### commands auto generated by Alembic - please adjust! ###
op.create_table('users',
sa.Column('id... |
'''
Module for standard MCMC inference
Author(s): Chang, MJ
Usage:
1- If you don't have a local installation of ipython parallel:
***pip install --user "ipython[parallel]"***
2- Start up an ipcluster in another terminal:
***ipcluster start -n 4(number of cores)***
3- Execute this file.
'''
import s... |
import os
import sys
import clib
sys.path.insert(0, os.path.abspath(os.path.join(
os.path.dirname(__file__), '..'))) |
import filecmp
import itertools
import logging
import os
logger = logging.getLogger(__name__)
def dedupe(filenames, prefer_shorter=True):
deleted = set()
for filename1, filename2 in itertools.combinations(filenames, 2):
if filename1 not in deleted and filename2 not in deleted and filecmp.cmp(filename1, ... |
from survox_api.resources.base import SurvoxAPIBase
from survox_api.resources.account.server import SurvoxAPIAccountServer
from survox_api.resources.valid import valid_url_field
from survox_api.resources.exception import SurvoxAPIRuntime
class SurvoxAPIAccountList(SurvoxAPIBase):
"""
Class to manage a list of S... |
import os
import sys
sys.path.insert(0, os.path.abspath('.'))
sys.path.insert(0, "..")
sys.path.insert(0, "../soba/models")
from unittest.mock import MagicMock
class Mock(MagicMock):
@classmethod
def __getattr__(cls, name):
return MagicMock()
MOCK_MODULES = []
sys.modules.update((mod_name, Mock()) f... |
import sys
import traceback
import contextlib
import os, os.path
from PyQt5 import QtCore, QtWidgets, QtGui, uic
from glfloweditor import *
from propertyeditor import *
from synth import *
from keymap import getKeyMap
from nodes import *
import audio
form, base = uic.loadUiType("mainwindow.ui")
class MainWindow(form,ba... |
from __future__ import division
import os
import json
import urllib2
import csv
""" This script downloads one big Json object containing multiple gestures either from the
local server of from accelldatacollect.appspot.com.
It then creates a csv file for each data recorded in the format:
Note: It and creates a tRel vari... |
"""groupby procedure for recipes"""
import fnmatch
import logging
from typing import List
from .. helpers import debuggable, mkfunc
from .. model.ingredient import DataPointIngredient
from .. model.chef import Chef
logger = logging.getLogger('groupby')
@debuggable
def groupby(chef: Chef, ingredients: List[DataPointIngr... |
from __future__ import unicode_literals
import unittest
from random import choice
import frappe
from frappe.custom.doctype.custom_field.custom_field import create_custom_field
from frappe.utils import random_string
from frappe.utils.testutils import clear_custom_fields
class TestDB(unittest.TestCase):
def test_get_val... |
import numpy as np
import os
from os.path import join as pjoin
from setuptools import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext
import subprocess
nvcc_bin = 'nvcc.exe'
lib_dir = 'lib/x64'
import distutils.msvc9compiler
distutils.msvc9compiler.VERSION = 14.0
try:
numpy_in... |
import datetime
import humanize
import json
import memcache
import requests
from flask import (
Flask, render_template,
)
from feed import get_commits_feed
app = Flask(__name__)
app.config["DEBUG"] = True
app.config["STATIC_MINIFY_FILENAME"] = {
"js/": "js/min/",
"css/": "css/min/",
}
if not app.config["DE... |
from __future__ import unicode_literals
from future import standard_library
standard_library.install_aliases()
from django import template
from isisdata.models import *
import base64, urllib.request, urllib.parse, urllib.error
from urllib.parse import quote
import codecs
from haystack.query import EmptySearchQuerySet, ... |
import pytest
from loqusdb.utils.load import load_database
from loqusdb.exceptions import CaseError
def test_load_database(vcf_path, ped_path, real_mongo_adapter, case_id):
mongo_adapter = real_mongo_adapter
db = mongo_adapter.db
load_database(
adapter=mongo_adapter,
variant_file=vcf_path,
... |
print "Hello world" |
numhlines = 3
numvlines = 1
logWindowWidth = 0
controlBarHeight = 3
recordWinWidth = 25
recordWinHeight = 16 |
import SimpleHTTPServer
import SocketServer
import traceback
import os
import sys
import pymysql.cursors
import subprocess
import mysqldb
db = mysqldb.MysqlConn()
if len(sys.argv) != 2:
print('Expecting an argument: filename')
input_path = sys.argv[1]
input_file = open(input_path, 'r')
for line in input_file:
t... |
"""
Implementa um Proxy que proibe acesso a atributos e métodos começados por `_`
para _simular_ atributos protegidos. Isso é feito sobrescrevendo o método
especial `__getattr__`, conforme visto na classe Proxy.
>>> special = Special(2.5, 200)
>>> special.size
2.5
>>> special._value
200
>>> special._protected()
500.0
>... |
from __future__ import unicode_literals
AUTHOR = u'sudo'
SITENAME = u'Criticón '
HIDE_SITENAME = True
SITEURL = ''
SITELOGO = 'images/logo-criticon-sm.png'
PATH = 'content'
OUTPUT_PATH = '../docs'
TIMEZONE = 'America/Bogota'
DEFAULT_LANG = u'es'
FEED_ALL_ATOM = None
CATEGORY_FEED_ATOM = None
TRANSLATION_FEED_ATOM = Non... |
"""Replace quarterly_revalidation_threshold with submission_window_schedule
Revision ID: 471273c020c5
Revises: 9472a2385e99
Create Date: 2020-05-28 11:11:01.594022
"""
revision = '471273c020c5'
down_revision = '9472a2385e99'
branch_labels = None
depends_on = None
from alembic import op
import sqlalchemy as sa
from sqla... |
import sys
import math
sys.setrecursionlimit(4000002)
def prime(num, test=2):
while test != num:
if num % test == 0:
return False
test += 1
return True
def largest_prime_factor(num, test=2, highest=1):
while highest == 1: #while no new high prime factor has been found
if ... |
from __future__ import (unicode_literals, absolute_import,
division, print_function)
import time
import random
from config import (api, logger, PAUSE_DELAY, tweepy,
get_followers, save_followers, get_messages)
def tweet_and_wait(message, media=None):
logger.info(message)
... |
import inspect
import sys
import unittest
from pydevd_save_locals import save_locals
def use_save_locals(name, value):
"""
Attempt to set the local of the given name to value, using locals_to_fast.
"""
frame = inspect.currentframe().f_back
locals_dict = frame.f_locals
locals_dict[name] = value
... |
def bothdaughtershairscombined(x,y):
return 2 * (x + y)
def output(name, amountofhaironface,shouldhaveamountofhaironface, sumofbothdaughtershairs):
out = """
HEY GUYS
My name is {}.
I am your nurse.
Your baby girl might have {} hairs on her face.
We are afraid that if she has more than {} hairs on her face...
Then sh... |
import os
import errno
import fnmatch
import sys
import shlex
from Cython.Distutils import build_ext
from distutils.sysconfig import get_config_var, get_config_vars
import pkg_resources
from subprocess import check_output, CalledProcessError, check_call
from setuptools import setup, Extension
from setuptools.dist impor... |
import sys
import logging
class log(object):
"""
Easily setup logs using the standard `logging module`_.
.. _logging module: https://docs.python.org/3/library/logging.html
:param string logfile: Path to the log file. Defaults to <your_script>_py.log
:param file_level: The `logging level`_ to log to ... |
"""
***************************************************************************
TextToFloat.py
---------------------
Date : May 2010
Copyright : (C) 2010 by Michael Minn
Email : pyqgis at michaelminn dot com
**************************************************... |
import __baseclass
callback_name = "cobbler"
import xmlrpclib
config = {
'server': "http://localhost/cobbler_api" ,
'user': "admin" ,
'pass': "admin"
}
class CobblerAddHost ( __baseclass.AbstractRegisterCallback ) :
name = callback_name
def run ( self , uuid , dbvalues ) :
conn = xmlrpcl... |
import rpyc
import threading
import time
import Queue
import config
import transactions
import blockChain
import bson
import collections
import math
from collections import deque
from rpyc.utils.server import ThreadedServer
from Cryptodome.Hash import SHA256
from Cryptodome.Signature import pss
from keyManagement impor... |
"""
NetworkL
========
NetworkL is a Python package which extends the scope of the NetworkX
package to eXtra-Large time-varying graphs. It supports the manipulation
and efficient longitudinal analysis of complex networks
https://networkl.github.io/
Using
-----
Just write in Python:
>>> import netw... |
from __future__ import division
from __future__ import absolute_import
from __future__ import print_function
from __future__ import unicode_literals
import numpy as np
import matplotlib.pyplot as plt
import sys,Util
sys.path.append("../../../../../../")
from GeneralUtil.python import CheckpointUtilities,GenUtilities
fr... |
from django import forms
from django.contrib.auth.decorators import permission_required
from django.http import HttpResponse
from django.shortcuts import get_object_or_404, redirect
from django.template.defaultfilters import slugify
from django.views.decorators.cache import never_cache
from django.views.generic import ... |
import io
import random
import picamera
import numpy as np
import picamera.array
import argparse
import logging
import sys
import signal
import zmq
import json
import time
from zmq.eventloop import zmqstream
import multiprocessing as mp
import subprocess
logging.basicConfig(format='%(asctime)s - %(levelname)s: %(messag... |
import os
import time
from Tools.CList import CList
from SystemInfo import SystemInfo
from Components.Console import Console
from Tools.HardwareInfo import HardwareInfo
import Task
def readFile(filename):
file = open(filename)
data = file.read().strip()
file.close()
return data
def getProcMounts():
try:
mounts =... |
from twython import Twython, TwythonError
import base64
import ConfigParser
def decode(skey, string):
decoded_chars = []
string = base64.urlsafe_b64decode(string)
for i in xrange(len(string)):
key_c = skey[i % len(skey)]
encoded_c = chr(abs(ord(string[i]) - ord(key_c) % 256))
decoded... |
import random,time
import csv, logging, urllib
import re, sys, os
import settings,MySQLdb
import sendkillermail
dbconn = settings.connect_db()
cursor = dbconn.cursor(MySQLdb.cursors.DictCursor)
def delLinkedIn(sel,amount):
try:
sel.open("http://www.linkedin.com/connections?trk=hb_side_connections")
except:
pass
... |
import os
import sys
from Utils import runCommand, getScriptDir
import json
from lxml import etree
def getGoDirs(directory, test = False):
go_dirs = []
for dirName, subdirList, fileList in os.walk(directory):
# does the dirName contains *.go files
nogo = True
for fname in fileList:
# find any *.go file
if... |
class OSRFException(Exception):
"""Root class for exceptions."""
def __init__(self, info=''):
self.msg = '%s: %s' % (self.__class__.__name__, info)
def __str__(self):
return self.msg
class NetworkException(OSRFException):
def __init__(self):
OSRFException.__init__('Error communic... |
from collections import OrderedDict
import textwrap, argparse
import re, os
if __name__ == '__main__':
argument_parser = argparse.ArgumentParser(
prog='calc_sons_visited.py',
formatter_class=argparse.RawDescriptionHelpFormatter,
description=textwrap.dedent('''\
calculate sons of all synsets from W... |
import pytest
from lazy import strict
def test_cannot_strict_undefined():
from lazy import undefined
with pytest.raises(Exception) as e:
strict(undefined)
assert type(e.value).__name__ == 'undefined' |
import httplib
import urllib,urllib2,re,sys
import cookielib,os,string,cookielib,StringIO,gzip
import os,time,base64,logging
import xbmcaddon,xbmcplugin,xbmcgui
import hashlib,random
import json
from t0mm0.common.addon import Addon
import datetime
addon = Addon("plugin.video.MyDooTv")
ADDON = xbmcaddon.Addon(id='plugin... |
import simuPOP as sim
from simuPOP.utils import migrIslandRates
import random
def demo(pop):
# this function randomly split populations
numSP = pop.numSubPop()
if random.random() > 0.3:
pop.splitSubPop(random.randint(0, numSP-1), [0.5, 0.5])
return pop.subPopSizes()
def migr(pop):
numSP = pop.numSubPop(... |
import sys
try:
from ircbot import *
from irclib import *
except:
print "ERROR !!!!\nircbot.py and irclib.py not found, please install them\n( http://python-irclib.sourceforge.net/ )"
sys.exit(1)
def my_remove_connection(self, connection):
if self.fn_to_remove_socket:
self.fn_to_remove_socket(connection._get_soc... |
import matplotlib
matplotlib.use('Agg')
import os
import sys
import numpy as np
import yt
yt.enable_parallelism()
dir = '/d/d11/ychen/MHD_jet/0517_L45_M10_b1_h1_20Myr'
try:
ind = int(sys.argv[1])
ts = yt.DatasetSeries(os.path.join(dir,'*_hdf5_plt_cnt_%02d?0' % ind), parallel=10)
except IndexError:
ts = yt.D... |
"""
Class that implements pyFoamPlotRunner
"""
from .PyFoamApplication import PyFoamApplication
from PyFoam.Execution.GnuplotRunner import GnuplotRunner
from PyFoam.RunDictionary.SolutionDirectory import SolutionDirectory
from .CommonStandardOutput import CommonStandardOutput
from .CommonPlotLines import CommonPlotLine... |
# ----------------------------------------------------------------------------
# "THE BEER-WARE LICENSE" (Revision 42):
# @tantrumdev wrote this file. As long as you retain this notice you
# can do whatever you want with this stuff. If we meet some day, and you think
# this stuff is worth it, you can buy me a bee... |
LOGGING_LEVEL = 20
HTML_DIR = 'html_output'
IMG_WIDTH = 150
session_id = ""
did = ""
POST = 1
GET = 0
RETRY_DELAY = 30
RETRY_COUNT = 30
TASK_RAND_DELAY = 10
POWER_PER_TASK = 2
POWER_INTERVAL = 360
base_url = "http://app2.nuan.wan.liebao.cn:51000/"
img_url = "http://image2.nuan.wan.liebao.cn/v1/dress/ipad/%s-1.png"
base... |
'''
asylumRL by scotchfield
http://scootah.com/asylumrl
requires python2.x, pygame, and libtcod
headphones would also be nice!
'''
import math
import os
import pygame
import random
import libtcodpy as libtcod
def enum(*sequential, **named):
enums = dict(zip(sequential, range(len(sequential))), **named)
return t... |
"""
Django settings for webapp project.
Generated by 'django-admin startproject' using Django 1.9.1.
For more information on this file, see
https://docs.djangoproject.com/en/1.9/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.9/ref/settings/
"""
import os
BASE_DI... |
from test_util import get_devs, get_devs_netns
from nemu.environ import *
import nemu, test_util
import os, unittest
class TestUtils(unittest.TestCase):
def test_utils(self):
devs = get_devs()
# There should be at least loopback!
self.assertTrue(len(devs) > 0)
self.assertTrue('lo' in... |
from SkunkWeb import Configuration
import PostgreSql
Configuration.mergeDefaults(
PostgreSQLConnectParams = {},
)
for u, p in Configuration.PostgreSQLConnectParams.items():
PostgreSql.initUser ( u, p )
def rollback(*args):
for v in PostgreSql._connections.values():
v.rollback()
from requestHandl... |
from typing import Any, List, Tuple, Dict
import re
from dataclasses import dataclass, field
from dataclasses_json import dataclass_json
import plugins
from plugins.abstract.corparch.corpus import TagsetInfo
from controller.plg import PluginCtx
from argmapping.error import ArgumentMappingError, ValidationError
from arg... |
from portage.process import find_binary
from portage.tests import TestCase, test_cps
from portage.sets.shell import CommandOutputSet
class CommandOutputSetTestCase(TestCase):
"""Simple Test Case for CommandOutputSet"""
def setUp(self):
pass
def tearDown(self):
pass
def testCommand(self):
input = set(test_cps)... |
from nose_tests.constants import SLIM_SHADY_RECORDS
from nose_tests.nd_test_case import NDTestCase
from flask_app import app
class LabelAPITest(NDTestCase):
def setUp(self):
super(LabelAPITest, self).setUp()
def test_get(self):
get_uri = '{}/labels/{}'.format(app.config['BASE_URL'], SLIM_SHADY_R... |
import os
import re
import locale
from gi.repository import GLib
class Singleton(object):
_instance = None
def __new__(cls, *args, **kwargs):
if not cls._instance:
cls._instance = super(Singleton, cls).__new__(
cls, *args, **kwargs)
cls._instance.__in... |
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
def _fromUtf8(s):
return s
try:
_encoding = QtGui.QApplication.UnicodeUTF8
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig, _encoding)
exce... |
import json
from django.conf import settings
from django.db import models
from django.db.models import get_model
from django.utils import timezone
from edc_device import Device
from edc_base.encrypted_fields import FieldCryptor
from edc_sync.models import BaseTransaction
from edc_sync.exceptions import SyncError
class ... |
import sys, re
from pprint import pprint
BEACON_REGEX = b'\x80\x00\x00\x00(?:\xff){6}(.{6})\\1'
PROBE_REGEX = b'\x40(?:\x00|\x10)\x00\x00(?:\xff){6}(.{6})(?:\xff){6}'
if len(sys.argv) < 2:
print "Don't forget to supply the memory dump file..."
sys.exit(1)
dump = open(sys.argv[1]).read()
beacon_pattern = re.compile(B... |
import errno, os, re, shutil, posixpath, sys
import xml.dom.minidom
import stat, subprocess, tarfile
from i18n import _
import config, util, node, error, cmdutil, bookmarks, match as matchmod
import phases
import pathutil
hg = None
propertycache = util.propertycache
nullstate = ('', '', 'empty')
def _expandedabspath(pa... |
from django.shortcuts import render
from .models import Property
from transaction.models import Transaction
from django.shortcuts import get_object_or_404
def property_index(request, property_id):
data = {}
# Grab active property linked to the user
property = get_object_or_404(Property,id=property_id)
transacti... |
"""Widgets for Fetch, Push, and Pull"""
from __future__ import division, absolute_import, unicode_literals
import fnmatch
from qtpy import QtGui
from qtpy import QtWidgets
from qtpy.QtCore import Qt
from ..i18n import N_
from ..interaction import Interaction
from ..models import main
from ..qtutils import connect_butto... |
"""
A tool for comparing FlightControlSystem XML definitions. Useful
for determining differences between hand-edited xml files and ones
generate from NodeConstructor definitions.
Suggested usage:
Normalize.py in1.xml > out1.txt
Normalize.py in2.xml > out2.txt
diff out1.txt out2.txt
"""
import sys
record = 0
object = [... |
from pynestml.meta_model.ast_node import ASTNode
class ASTElifClause(ASTNode):
"""
This class is used to store elif-clauses.
Grammar:
elifClause : 'elif' rhs BLOCK_OPEN block;
Attribute:
condition = None
block = None
"""
def __init__(self, condition, block, source_positio... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.