content stringlengths 4 20k |
|---|
from BaseHTTPServer import BaseHTTPRequestHandler,HTTPServer
# import json
PORT = 8081
def protest (response, message):
response.send_response(200)
response.send_header('Content-type','application/json')
response.end_headers()
response.wfile.write(message)
class handler(BaseHTTPRequestHandler):
d... |
from __future__ import division, unicode_literals
"""
Created on Feb 2, 2012
"""
__author__ = "Shyue Ping Ong"
__copyright__ = "Copyright 2012, The Materials Project"
__version__ = "0.1"
__maintainer__ = "Shyue Ping Ong"
__email__ = "<EMAIL>"
__date__ = "Feb 2, 2012"
import unittest
import os
import json
from mont... |
"""
Module to run abbreviated version of OHDSI Achilles
"""
import os
from run_config import hpo_ids, multi_schema_supported, engine
import resources
import numpy
achilles_sql_path = os.path.join(resources.resource_path, 'achilles.sql')
achilles_heel_sql_path = os.path.join(resources.resource_path, 'achilles_heel.sq... |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
# Created on 2016-07-26 11:04:34
import urllib
import urllib2
from abc import ABCMeta, abstractmethod
import util
logger = util.get_logger("MoJoWX")
# api 地址
# https://github.com/sjdy521/Mojo-Weixin/blob/master/doc/Weixin.pod
class MoJoWXComponent:
def __init__(s... |
from __future__ import unicode_literals
from django.core.management.base import BaseCommand, CommandError
from django.core.files import File
from django.core.exceptions import ValidationError
import os
import sys
import logging
from django.conf import settings
from books import models
from books.epub import Epub
fr... |
from libsaas.filters import auth
from libsaas.services import base
from . import actions, analysis, checks, contacts, credit, probes, reference
from . import reports, results, servertime, settings, summary
from . import single, traceroute
class Pingdom(base.Resource):
"""
"""
def __init__(self, username,... |
# -*- coding: utf-8 -*-
from django.utils.translation import ugettext_lazy as _
UF = [
('AC', 'Acre'),
('AL', 'Alagoas'),
('AP', 'Amapá'),
('AM', 'Amazonas'),
('BA', 'Bahia'),
('CE', 'Ceará'),
('DF', 'Distrito Federal'),
('ES', 'Espírito Santo'),
('GO', 'Goiás'),
('MA', 'Maranhã... |
import json
from django.http import HttpResponse
from django.contrib.gis.geos import Point, Polygon
from point_store.models import *
from datetime import datetime
from django.views.decorators.csrf import csrf_exempt
'''
class DataPoint(models.Model):
#localization
position = models.PointField()
speed = mod... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Created on 05 Apr 2014 3:27 AM
@author: <'Ronny Eichler'> <EMAIL>
"""
import time
import logging
from constants import *
from util import memoize_with_expiry, unpack_string
class Channel(object):
def __init__(self, chan_num=0):
self.log = logging.getLogge... |
"""Custom configurations and functions for Google App Engine."""
__author__ = '<EMAIL> (Pavel Simakov)'
import datetime
import importlib
import logging
import os
import sys
# configure Appstats
appstats_MAX_STACK = 20
# Whether we are running in the production environment.
PRODUCTION_MODE = not os.environ.get(
... |
from __future__ import absolute_import, division, print_function
import pytest
pytest.importorskip('flask')
import datashape
import numpy as np
from flask import json
from datetime import datetime
from pandas import DataFrame
from toolz import pipe
from odo import odo
from blaze.utils import example
from blaze impor... |
'''
:Partially Blind Signature Scheme
| From: "M. Abe, T. Okamoto Provably Secure Partially Blind Signatures"
| Published in: CRYPTO 2000
| Available from: http://www.iacr.org/archive/crypto2000/18800272/18800272.pdf
* type: signature (partially blind)
* setting: integer groups
:Authors: Antonio... |
import uuid
from glanceclient import exc
from glanceclient.openstack.common.apiclient import exceptions
import mock
from heat.engine.clients.os import glance
from heat.tests import common
from heat.tests import utils
class GlanceUtilsTests(common.HeatTestCase):
"""Basic tests for :module:'heat.engine.resources.... |
"""Tests for the certificates Python API. """
from contextlib import contextmanager
import ddt
from django.test import TestCase, RequestFactory
from django.test.utils import override_settings
from mock import patch
from nose.plugins.attrib import attr
from opaque_keys.edx.locator import CourseLocator
from xmodule.mod... |
import re
import sys
#
# Miscellaneous constants, tags, and masks used for object identification.
#
consts_misc = [
{ 'name': 'FirstNonstringType', 'value': 'FIRST_NONSTRING_TYPE' },
{ 'name': 'IsNotStringMask', 'value': 'kIsNotStringMask' },
{ 'name': 'StringTag', 'value': 'kStrin... |
from bunq_bot.commands.controller import Controller
from bunq_bot.models import ChatInfo
from django.core.exceptions import ObjectDoesNotExist
# import sqlite3
# from config import config
# config = config()
# from pprint import pprint
class Commands(Controller):
def __init__(self, msg):
super().__init... |
from asposeslides import Settings
from com.aspose.slides import Presentation
from com.aspose.slides import SaveFormat
from com.aspose.slides import XpsOptions
class Properties:
def __init__(self):
# Accessing Built-in Properties
self.get_properties()
# M... |
import glob
import json
import os
import pprint
import sys
import click
import pandas as pd
import tabulate
from ray.tune.util import flatten_dict
def print_df_tabular(df):
headers = list(df.columns)
headers.remove("Experiment Name")
headers.insert(0, "Experiment Name")
table = [headers]
for _, ... |
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import numpy as np
import sympy
from pylab import rcParams
from pySDC.implementations.problem_classes.FastWaveSlowWave_0D import swfw_scalar
from pySDC.implementations.datatype_classes.complex_mesh import mesh, rhs_imex_mesh
from pySDC.implement... |
def player_ai(game_board, player_hand, first_move):
print("Player 1 AI Called")
moves = []
move_point_total = 0
# TODO: Fix offsets so we don't have tile value 1 in the position 0, etc
# Create a 4 x 13 array with the values of the tiles in the player's hand
# Ignores the possibility of dupli... |
from django.utils.translation import ugettext_lazy as _
from glanceclient import exc
from horizon import exceptions
from horizon import forms
from horizon import messages
from openstack_dashboard import api
def str2bool(value):
"""Convert a string value to boolean
"""
return value.lower() in ("yes", "t... |
"""
HTML writing objects
TODO: remove from __init__
"""
import types
TAB_SIZE = 4
def write_html(out, object):
if hasattr(object, '__write_html__'):
return object.__write_html__(out)
else:
if isinstance(object, types.StringTypes):
out.write(escape(object))
else:
out.write(escape(str(object)))
def esc... |
import pytest
from plenum.common.util import SortedDict
from plenum.common.messages.node_messages import PrePrepare, Commit
# from plenum.test.replica.conftest import *
from plenum.server.consensus.ordering_service import OrderingService
from plenum.server.replica_helper import generateName
from plenum.test.consensus... |
import time
from itertools import chain
from .connection import Urllib3HttpConnection
from .connection_pool import ConnectionPool, DummyConnectionPool
from .serializer import Deserializer, DEFAULT_SERIALIZERS, DEFAULT_SERIALIZER
from .exceptions import ConnectionError, TransportError, SerializationError, ConnectionTim... |
from __future__ import division
import warnings
import unittest
import os
import shutil
import salem
from geoget.tests import is_download, is_slow, requires_credentials, cred
from geoget import core
# Setting for warnings
warnings.filterwarnings("once", category=DeprecationWarning)
# Globals
CURRENT_DIR = os.path.dir... |
import six
import os
import ruamel.yaml as yaml
import datetime
import logbook
import locale
from pprint import pformat
import codecs
import shutil
from . import RqAttrDict, logger
from .exception import patch_user_exc
from .logger import user_log, user_system_log, system_log, std_log, user_std_handler
from ..const im... |
from Acquisition import aq_base
from opencore.browser.naming import get_view_names
import logging
import transaction
logger = logging.getLogger("opencore.upgrades")
def default_profile_id():
from opencore.utility.interfaces import IProvideSiteConfig
from zope.component import getUtility
configparser = ge... |
"""
A simple challenge response server
Request:
encrypted-message-of-challenge
Response:
status-code;body-of-response
Good response:
200-299;base64 of rsa-sha256 of challenge
Bad response:
400-599;error-message
"""
import os
import sys
import argparse
import time
import hashlib
import zmq
import... |
"""
RHEL-7 installation
"""
import os
import oz.ozutil
import oz.RedHat
import oz.OzException
class RHEL7Guest(oz.RedHat.RedHatLinuxCDYumGuest):
"""
Class for RHEL-7 installation
"""
def __init__(self, tdl, config, auto, output_disk=None, netdev=None,
diskbus=None, macaddress=None):
... |
# coding: utf-8
# In[ ]:
get_ipython().system('pip install regex # A sligthly better version of RE')
get_ipython().system('pip install html5lib # For Pandas read_html used to parse mapping wikitables ')
get_ipython().system('pip install pandas # A great library for data wrangling (and analysis) ')
# In[1]:
import ... |
import abc
import typing
import pkg_resources
import google.auth # type: ignore
from google.api_core import gapic_v1 # type: ignore
from google.api_core import retry as retries # type: ignore
from google.auth import credentials as ga_credentials # type: ignore
from google.ads.googleads.v8.resources.types import c... |
"""Philips hue proxy code."""
import abc
import logging
import sys
import threading
from pi import proxy
class ScanningProxy(proxy.Proxy):
"""A proxy object with a background scan thread."""
__metaclass__ = abc.ABCMeta
def __init__(self, refresh_period):
self._refresh_period = refresh_period
self._... |
import copy
from distutils.version import LooseVersion
from functools import wraps
import random
import uuid
from configman import ConfigurationManager, environment
from elasticsearch.helpers import bulk
import pytest
from socorro.external.es.connection_context import ConnectionContext
from socorro.external.es.supers... |
from __future__ import print_function
from __future__ import unicode_literals
import codecs
import re
def is_emoji(cp):
'''
This function identifies emojis, cp is assumed to be a 32bit character
:param cp: unicode codepoint
:return: True if is a emoju
'''
# new in unicode 7
... |
__author__ = 'cutylewiwi'
# -*- coding:utf-8 -*-
import urllib
import urllib2
import re
class Group:
def __init__(self, name, faculties):
self.name = name
self.faculties = faculties
class GroupList:
def __init__(self, baseUrl):
self.baseUrl = baseUrl
self.grou... |
from __future__ import with_statement
import os
from os.path import isabs, join
from subprocess import Popen, check_call, PIPE, STDOUT
import tempfile
import shutil
from cStringIO import StringIO
from sympy.utilities.exceptions import SymPyDeprecationWarning
from sympy.utilities.misc import find_executable
from latex... |
#!/usr/bin/python
from participantCollection import ParticipantCollection
import re
import datetime
import pyperclip
# Edit Me!
# This script gets run on the first day of the following month, and that month's URL is
# what goes here. E.g. If this directory is the directory for February, this script gets
# run on Marc... |
from datetime import datetime
from django.conf import settings
from django.shortcuts import get_object_or_404
from django.test import RequestFactory, Client, TestCase
from models import Dashboard, Location, Product, Category, ShoppingList
from src.accounts.models import User
from .views import (AddForm, change_item, ad... |
from rest_framework import serializers
from rest_framework_bulk import BulkListSerializer, BulkSerializerMixin
from api.models import *
class ProductSerializer(BulkSerializerMixin, serializers.ModelSerializer):
class Meta(object):
model = Product
fields = (
'id', 'name', 'description... |
import os
import shutil
import re
from Utils.RegexUtils import dollar_replace
from Utils.KivyConfNavConfig import get_config
class AreaTemplater:
def __init__(self, path, area):
self.path = path if path.endswith('/') else path + '/'
self.area = area
def prepare_dir(self, path):
temp_p... |
from __future__ import absolute_import, division, print_function
import requests
from flask import current_app
from mock import patch
from inspirehep.modules.records.api import InspireRecord
from inspirehep.modules.workflows.tasks.magpie import (
get_magpie_url,
prepare_magpie_payload,
filter_magpie_respo... |
import asyncio
from unittest.mock import patch
class _asyncio_patch:
"""
A wrapper around python patch supporting asyncio.
Like the original patch you can use it as context
manager (with)
The original patch source code is the main source of
inspiration:
https://hg.python.org/cpython/file... |
"""
Cross Section Database Generator
uses the cross_section_calculator to calculate bulk cross sections and store in
sqlite database
"""
import os
import SEAS_Aux.cross_section.cross_section_calculator as csc
import lines2xsec as l2x
import SEAS_Utils.common_utils.db_management2 as dbm
from SEAS_Utils.common_util... |
# -*- coding: utf-8 -*-
import os
import sys
from setuptools import setup, find_packages, Command
class BaseCommand(Command):
user_options = []
def initialize_options(self):
pass
def finalize_options(self):
pass
class TestCommand(BaseCommand):
description = "run self-tests"
d... |
'''
Support
=======
Activate other framework/toolkit inside our event loop
'''
__all__ = ('install_gobject_iteration', 'install_twisted_reactor',
'install_android')
from kivy.compat import PY2
def install_gobject_iteration():
'''Import and install gobject context iteration inside our event loop.
This i... |
import random
from lollypop.define import Shuffle
from lollypop.player_base import BasePlayer
from lollypop.objects import Track
class UserPlaylistPlayer(BasePlayer):
"""
Manage user playlist
"""
def __init__(self):
"""
Init user playlist
"""
BasePlayer.__init... |
# coding: utf-8
import os, time, re
from django import template
from django.conf import settings
from djclub.app.models import User, Topic, Notify, Reply, Thanks
register = template.Library()
@register.filter
def get_notify_count(user_id):
count = 0
try:
user = User.objects.get(id=user_id)
count = user.notif... |
import logging
from django.utils.translation import ugettext as _
from ..images.tables import ImagesTable, LaunchImage, EditImage, DeleteImage
LOG = logging.getLogger(__name__)
class DeleteSnapshot(DeleteImage):
data_type_singular = _("Snapshot")
data_type_plural = _("Snapshots")
class SnapshotsTable(Im... |
class UpdateMaker:
def __init__(self, message, condition, args=[]):
self.message = message
self.condition = condition
self.args = args
def make(self, forecasts):
matching = [f for f in forecasts if self.condition(f)]
if matching:
return self.format_message(ma... |
"""Fichier contenant le contexte 'personnage:creation:choix_genre'"""
from primaires.interpreteur.contexte import Contexte
from primaires.format.fonctions import *
class ChoixGenre(Contexte):
"""Contexte demandant au client de choisir le genre de son personnage.
Le genre est fonction de la race choisie. Une... |
from telemetry.page import page as page_module
from telemetry.page import page_set as page_set_module
from page_sets import key_mobile_sites_pages
def _IssueMarkerAndScroll(action_runner):
interaction = action_runner.BeginGestureInteraction(
'ScrollAction')
action_runner.ScrollPage()
interaction.End()
... |
#!/usr/bin/env python
# Creates the parasail.pyx file used for the python bindings.
import glob
import os
print """# cython: c_string_type=str, c_string_encoding=ascii
from libc.string cimport const_char
import numpy as np
cimport numpy as np
from cpython cimport PyObject, Py_INCREF
np.import_array()
cdef extern ... |
import os
import sys
import sqlite3
import operator
import subprocess
from PyQt import QtCore, QtGui
from launchpad_ui import Ui_launchpadDialog
from actionDetailDialog import ActionDetailDialog
class Launchpad(QtGui.QDialog):
def __init__(self, parent=None):
QtGui.QDialog.__init__(self, parent)
se... |
from django.db import models
from django.contrib.auth.models import User
from django.db.models import JSONField
from seqr.models import ModelWithGUID, Individual
from settings import MME_DEFAULT_CONTACT_NAME, MME_DEFAULT_CONTACT_HREF
class MatchmakerSubmission(ModelWithGUID):
SEX_LOOKUP = {Individual.SEX_MALE: ... |
from unittest.mock import Mock
from pyramid import testing
from pytest import fixture
from pytest import raises
def test_includeme_register_has_asset_pool_sheet(config):
from adhocracy_core.sheets.asset import IHasAssetPool
from adhocracy_core.utils import get_sheet
config.include('adhocracy_core.content... |
# -*- coding: utf-8 -*-
"""
tests/test_views_depends.py
:copyright: (C) 2015 by Fulfil.IO Inc.
:license: see LICENSE for more details.
"""
import unittest
import trytond.tests.test_tryton
from trytond.tests.test_tryton import test_view, test_depends
class TestViewsDepends(unittest.TestCase):
'''
... |
# -*- coding:utf-8 -*-
from __future__ import absolute_import, unicode_literals
import os
from django import VERSION as DJANGO_VERSION
from django.utils.translation import ugettext_lazy as _
import dj_database_url
# Make these unique, and don't share it with anybody.
SECRET_KEY = os.environ.get('SECRET_KEY')
NEVERCA... |
from urllib.request import urlretrieve
import os
from gzip import GzipFile
from time import time
import argparse
import numpy as np
import pandas as pd
from joblib import Memory
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score, roc_auc_score
from sklearn.ensemble import H... |
from server.devices.base import BaseDevice
from server.devices.storages import HeatStorage, PowerMeter
class CogenerationUnit(BaseDevice):
"""Represents a basic interface to a cogeneration unit.
The configuration is read from the database and can be set from the frontend.
The following parameters are avai... |
import os
import sys
sys.path.insert(0, os.path.abspath('..'))
import unittest
import miner.utils
class TestMatrix(unittest.TestCase):
def setUp(self):
self.matrix = miner.utils.Matrix(3)
def test_single_record(self):
# NumPy does some funky stuff with the shape
# for matrixes with... |
from django.shortcuts import render, HttpResponseRedirect
from .forms import EmailForm, JoinForm
from .models import Join
def share(request, ref_id):
context={'ref_id':ref_id}
# context = {}
print(ref_id)
return render(request, 'share.html', context)
def get_ip(request):
try:
x_forward =... |
from random import randint
from rapidsms.contrib.locations.models import Location, LocationType
from survey.models import LocationTypeDetails, EnumerationArea
from survey.tests.base_test import BaseTest
from survey.views.location_widget import LocationWidget
class LocationWidgetTest(BaseTest):
def setUp(self):
... |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Mon Jul 31 14:19:35 2017
Author: Peiyong Jiang : <EMAIL>
Function:
BetaC & GammaC:
_______________________________________________________
Energy -> Gamma
Energy -> Beta
Energy->Beta*Gamma
Energy->Beta, Gamma
Gamma->Ener... |
from PyQt5.QtGui import *
from PyQt5.QtWidgets import (QVBoxLayout, QGridLayout, QPushButton)
from electrum.plugins import BasePlugin, hook
from electrum.i18n import _
import random
class Plugin(BasePlugin):
vkb = None
vkb_index = 0
@hook
def password_dialog(self, pw, grid, pos):
vkb_button =... |
import time
from datetime import date, timedelta
from django.core.management.base import BaseCommand
from apps.api.models import Game, Geek, Hotness, GeekStats
from apps.utils.scraper import boardgamegeek as games
from apps.api.modules.game import add_ranking, save_item
class Command(BaseCommand):
help = 'Get h... |
#!/usr/bin/python
# -*- coding: iso8859-1 -*-
# Descripción: Este script define el juego Othello: La configuración de una
# partida en cierto instante de tiempo (estado). Y que movimientos puede
# realizar el jugador con el turno actual dada cierta configuración de la partida.
from minmax import State, Move... |
__license__ = 'GPL v3'
__copyright__ = '2008, Kovid Goyal <kovid at kovidgoyal.net>'
"""
Defines the errors that the device drivers generate.
G{classtree ProtocolError}
"""
class ProtocolError(Exception):
""" The base class for all exceptions in this package """
def __init__(self, msg):
Exception.__... |
"""
worker/worker.py
=========
Worker to execute pipeline stages and produce artifacts
"""
def run_pipeline_stage(config_obj, stage_name):
"""
Run a pipeline stage locally, given a config object and a stage name
"""
# Step 0: Acquire artifact metadata for all input items
# - Abort if requ... |
"""
created 09/05/17
For executation of the kallisto quantification step
To be run with three arguements
* basedir - top level output directory
* input directory - contains folders with .fastq.gz files
* max_threads - how many threads to allocate to kallisto
Returns kallisto quantifications and associated l... |
"""
All the test functions for the pytest example in the order they should
be presented in.
#1 is in the default test file (passes)
#2 generates a failure, it will be replaced with #3 (fails)
#3 replaces #2 (passes)
#4 is added to cover the specified axis case (passes)
#5 demonstrates a problem with masked arrays (fai... |
import os.path
from requests_cache import CachedSession
import responses
import unittest
from openbadges.verifier.actions.tasks import add_task
from openbadges.verifier.actions.action_types import STORE_ORIGINAL_RESOURCE
from openbadges.verifier.reducers.input import input_reducer
from openbadges.verifier.tasks import... |
import os
import json
from argparse import ArgumentParser
from CloudFormationGraph import GraphvizGenerator
def main():
parser = ArgumentParser()
parser.add_argument('--in', dest='stack', required=True, metavar='FILE',
help='File containing CloudFormation template',
... |
#!/usr/bin/envpython2
# -*-coding:utf-8-*-
import cv
import cv2
import time
import os
import sys
import face
import numpy as np
#(281, 191, 80, 100)
if __name__ == "__main__":
#Ce code ne s’e x c u t e que si on e x c u t e directement le module(pas en cas d’import)
webcam = cv.CaptureFromCAM (0)
#nb_tof =... |
import os
import sys
import gettext
__trans = gettext.translation('pisi', fallback=True)
_ = __trans.ugettext
# PiSi Modules
import pisilinux.actionsapi
import pisilinux.context as ctx
# ActionsAPI Modules
import pisilinux.actionsapi.variables
class BinutilsError(pisi.actionsapi.Error):
def __init__(self, value... |
# -*- coding: utf-8 -*-
"""
Created on Tue Apr 14 20:41:09 2015
@author: oliver
"""
import numpy as np
from sympy import symbols
import mubosym as mbs
###############################################################
# general system setup example
myMBS = mbs.MBSworld('strange_pendulum', connect=True, force_db_setup=... |
import re, sys, traceback
from bs4 import BeautifulSoup
# from lexer import lexer
import pickle
from MTG import cardtype
from MTG import static_abilities
def run():
# switch to sm_cards and replace-all 'all_set', 'sm_set' to just parse a sample of cards
with open('parser/data/cards.xml') as f:
so... |
"""Simple word2vec implementation on Tensorflow
"""
# Origin: https://github.com/tensorflow/blob/r0.9/tensorflow/examples/tutorials/word2vec/word2vec_basic.py
# Coding: utf-8
# Description:
## v0.0: Basic skip-gram model with Tensorflow
## v0.1: Refactorize code
from __future__ import division
from __future__ import ... |
import os
import random
random.seed(int(os.getenv("SEED"), 16))
from utils import util
from prjuray.db import Database
def gen_sites():
db = Database(util.get_db_root(), util.get_part())
grid = db.grid()
for tile_name in sorted(grid.tiles()):
loc = grid.loc_of_tilename(tile_name)
gridinfo ... |
#!/usr/bin/python
#Import modules for CGI handling
import cgi, cgitb
import Cookie, os, time
try:
import pigpio
except:
pass
#============================ config ALERT ===================== #
import ConfigParser
Config = ConfigParser.ConfigParser()
setting = Config.read('setting/config.ini')
settingSec = Conf... |
import sublime
import sublime_plugin
import subprocess
# TODO: Use PATH to find drush (preferably cross platform method?)
# TODO: Menu Item
# TODO: Define default settings ala ST3 readonly ones
''' SublimeDrush: Parent Class '''
class SublimeDrush():
# Init class vars
name = "SublimeDrush AutoCache"
cmd... |
import deform
import colander
from pyramid.view import view_config
from dace.objectofcollaboration.principal.util import get_current
from dace.processinstance.core import DEFAULTMAPPING_ACTIONS_VIEWS
from pontus.form import FormView
from pontus.schema import Schema, select
from pontus.widget import RadioChoiceWidget
f... |
"""
Django settings for amadaa project.
Generated by 'django-admin startproject' using Django 1.10.1.
For more information on this file, see
https://docs.djangoproject.com/en/1.10/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.10/ref/settings/
"""
import os
... |
import pytest
from figment import Zone, Entity
from theworldfoundry.components import *
from theworldfoundry.modes import *
from tests.utils import room, connect, make_player
class WitnessError(Exception):
pass
def tell(entity, msg):
try:
entity.memory.append(msg)
except AttributeError:
... |
import argparse
import logging
import os
import re
import subprocess
import sys
from collections import OrderedDict
from six import iteritems
here = os.path.dirname(__file__)
wpt_root = os.path.abspath(os.path.join(here, os.pardir, os.pardir))
logger = logging.getLogger()
def get_git_cmd(repo_path):
"""Create ... |
# coding:utf-8
import requests
import random
class MySession(requests.Session):
"""A Requests session. @lite"""
useragents = [
'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.1b2pre) Gecko/20081015 Fennec/1.0a1',
'Mozilla/5.0 (X11; U; Linux armv7l; en-US; rv:1.9.2a1pre) Gecko/20090322 Fennec/1.0b2pre'... |
# flake8: noqa
from typing import NamedTuple
def SchemaGen(
statistics_uri: 'ExampleStatisticsUri',
output_schema_uri: 'SchemaUri',
infer_feature_shape: bool = None,
beam_pipeline_args: list = None,
) -> NamedTuple('Outputs', [
('schema_uri', 'SchemaUri'),
]):
from tfx.components import Schema... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import (division, print_function, absolute_import,
unicode_literals)
__all__ = ["sample_ball", "MH_proposal_axisaligned"]
import numpy as np
# If mpi4py is installed, import it.
try:
from mpi4py import MPI
MPI = MPI
excep... |
import filecmp
import json
import os
import shutil
import tempfile
from tests.compat import unittest, mock
from tests.utils import fixture_path, fixture_content
from namesync.main import main
from namesync.packages.six import StringIO
from namesync.records import flatfile_to_records
class IntegrationTestCase(unittes... |
"""This module represents the Songhai languages.
.. seealso:: http://en.wikipedia.org/wiki/Songhai_languages
"""
from __future__ import unicode_literals
from translate.lang import common
class son(common.Common):
"""This class represents Songhai."""
specialchars = "ɲŋšžãõẽĩƝŊŠŽÃÕẼĨ" |
"""Test logic for setting nMinimumChainWork on command line.
Nodes don't consider themselves out of "initial block download" until
their active chain has more work than nMinimumChainWork.
Nodes don't download blocks from a peer unless the peer's best known block
has more work than nMinimumChainWork.
While in initial... |
from odoo.tests.common import TransactionCase
class TestQualityControlTeam(TransactionCase):
def setUp(self):
super(TestQualityControlTeam, self).setUp()
self.qc_team_obj = self.env['qc.team']
self.main_qc_team = self.env.ref('quality_control_team.qc_team_main')
self.other_company... |
# coding=utf-8
"""**Tests for safe vector layer class**"""
__author__ = 'Tim Sutton <<EMAIL>>'
__revision__ = '$Format:%H$'
__date__ = '21/08/2012'
__license__ = "GPL"
__copyright__ = 'Copyright 2012, Australia Indonesia Facility for '
__copyright__ += 'Disaster Reduction'
import os
import logging
import unittest
fr... |
"""
This is the original exercise (43) from the book 'Learn Python the Hard Way'.
It is included here for reference and not used with Realm of Reckoning.
"""
from sys import exit
from random import randint
class Scene(object):
def enter(self):
print "This scene is not yet configured. Subclass ... |
# Read and process data from files/system
import subprocess
# Return lines of text
def read_txt(filename):
lines = []
with open(filename, mode='r') as infile:
lines = infile.read().splitlines()
return lines;
# Return current uptime
def get_uptime():
ps = subprocess.Popen("uptime -p", shell=Tr... |
__doc__="""Tests Postscript XObjects.
Nothing visiblke in Acrobat, but the resulting files
contain graphics and tray commands if exported to
a Postscript device in Acrobat 4.0"""
__version__='''$Id: test_pdfbase_postscript.py 3959 2012-09-27 14:39:39Z robin $'''
from reportlab.lib.testutils import setOutDir,make... |
from __future__ import unicode_literals
import re
from .common import InfoExtractor
from ..utils import (
determine_ext,
ExtractorError,
int_or_none,
lowercase_escape,
update_url_query,
)
class GoogleDriveIE(InfoExtractor):
_VALID_URL = r'''(?x)
https?://
... |
import html
from django.contrib import messages
from django.contrib.auth import login as auth_login
from django.contrib.auth.models import User
from django.db import IntegrityError
from django.http.response import Http404, HttpResponse
from django.urls import reverse
from django.utils.translation import ugettext_lazy ... |
from ptrace.ctypes_tools import formatAddress
from ptrace import PtraceError
from logging import info
from weakref import ref
from ptrace.cpu_info import CPU_POWERPC, CPU_WORD_SIZE
from ptrace.ctypes_tools import word2bytes
from ptrace.six import b
class Breakpoint(object):
"""
Software breakpoint.
Use de... |
from sqlalchemy.sql.expression import func
from sqlalchemy.orm.collections import InstrumentedList
# Cannot import galaxy.model b/c it creates a circular import graph.
import galaxy
import logging
import datetime
import uuid
log = logging.getLogger( __name__ )
class RuntimeException( Exception ):
pass
class Uses... |
"""
Utility methods to resize, repartition, and modify disk images.
Includes injection of SSH PGP keys into authorized_keys file.
"""
import crypt
import os
import random
import tempfile
from nova import exception
from nova import flags
from nova.openstack.common import cfg
from nova.openstack.common import jsonuti... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.