code stringlengths 1 199k |
|---|
from ._action import EncounterAction # inherits EncounterBase
class Encounter(EncounterAction):
"""
The encounter class is the arena for the battle
In a dimentionless model, move action and the main actions dash, disengage, hide, shove back/aside, tumble and overrun are meaningless.
weapon attack —defau... |
import argparse
import sys
import game
class Parser(argparse.ArgumentParser):
"""Simple wrapper class to provide help on error"""
def error(self, message):
sys.stderr.write('error: %s\n' % message)
self.print_help()
sys.exit(1)
class ArgHelper(object):
"""Helper class to lazily handl... |
"""
This file is part of the TheLMA (THe Laboratory Management Application) project.
See LICENSE.txt for licensing, CONTRIBUTORS.txt for contributor information.
Organization entity classes.
"""
from everest.entities.base import Entity
from everest.entities.utils import slug_from_string
__docformat__ = "reStructuredTex... |
from django.conf.urls.defaults import *
from views import paste_list
urlpatterns = patterns('',
url(r"$", paste_list, name="paste_list"),
) |
"""social_website_django_angular URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.10/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, ... |
"""
The MIT License (MIT)
Copyright (c) 2017 SML
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, d... |
"""
Spyder Editor
This temporary script file is located here:
C:\Users\moriarty.PENTAGON\.spyder2\.temp.py
"""
from pylab import *
foo = 0
tmp = []
for j in range(1000):
foo = randn(7)
s = 0
for i in foo:
s +=foo[i]
tmp.append(s)
hist(tmp,100)
show() |
import json
import logging
import jwt
import six
import umapi_client
import user_sync.connector.helper
import user_sync.config
import user_sync.helper
import user_sync.identity_type
from user_sync.error import AssertionException
from user_sync.version import __version__ as app_version
from user_sync.connector.umapi_uti... |
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('project_admin', '0018_auto_20151113_1702'),
]
operations = [
migrations.AddField(
model_name='projectgoal',
name='update_goal_inf... |
"""
Config file for The Powder Toy's website <http://powdertoy.co.uk>
Contains the message we post before we lock a thread, group ID, whitelist, etc.
"""
daysUntilLock = 182
daysUntilDelete = 200
lockmsg = ''.join([
'<p>Hey there!</p>',
'<p>We\'re automatically closing this thread since the original poster ',
... |
from syned.beamline.beamline import Beamline
from wofrysrw.srw_object import SRWObject
from wofrysrw.beamline.optical_elements.srw_optical_element import SRWOpticalElementDisplacement
from wofrysrw.storage_ring.srw_light_source import SRWLightSource
from wofrysrw.propagator.wavefront2D.srw_wavefront import WavefrontPro... |
from enum import IntEnum
class QV_TYPES(IntEnum):
LIBRARY = 1
NOTEBOOK = 2
NOTE = 3 |
from django.shortcuts import render, redirect
from django.conf import settings
from django.views.decorators.csrf import ensure_csrf_cookie
@ensure_csrf_cookie
def index(request):
if request.user.is_authenticated():
return redirect(request.GET.get('next', '/ide/'))
else:
return render(request, 'r... |
from django.db.models import Sum
from le_utils.constants import content_kinds
from requests.exceptions import ConnectionError
from requests.exceptions import HTTPError
from requests.exceptions import Timeout
from kolibri.content.models import ContentNode
from kolibri.content.models import LocalFile
from kolibri.content... |
from sqlalchemy.testing import eq_
import datetime
from sqlalchemy import *
from sqlalchemy.sql import table, column
from sqlalchemy import sql, util
from sqlalchemy.sql.compiler import BIND_TEMPLATES
from sqlalchemy.testing.engines import all_dialects
from sqlalchemy import types as sqltypes
from sqlalchemy.sql import... |
import logging
import os
import traceback
from dart.client.python.dart_client import Dart
from dart.engine.dynamodb.metadata import DynamoDBActionTypes
from dart.engine.dynamodb.actions.load_dataset import load_dataset
from dart.engine.dynamodb.actions.create_table import create_table
from dart.engine.dynamodb.actions.... |
from setuptools import setup
setup(
name = "vispa_jsroot",
version = "0.0.0",
description = "VISPA ROOT Browser - Inspect contents of root files.",
author = "VISPA Project",
author_email = "vispa@lists.rwth-aachen.de",
url = "http://vispa.phys... |
"""Strategies for creating new instances of Engine types.
These are semi-private implementation classes which provide the
underlying behavior for the "strategy" keyword argument available on
:func:`~sqlalchemy.engine.create_engine`. Current available options are
``plain``, ``threadlocal``, and ``mock``.
New strategies... |
r"""
This code was generated by
\ / _ _ _| _ _
| (_)\/(_)(_|\/| |(/_ v1.0.0
/ /
"""
from twilio.base import deserialize
from twilio.base import serialize
from twilio.base import values
from twilio.base.instance_context import InstanceContext
from twilio.base.instance_resource import InstanceResourc... |
from __future__ import unicode_literals
import functools
import itertools
import posixpath
import re
from operator import itemgetter
from flask import current_app
from flask_pluginengine.util import get_state
from jinja2 import environmentfilter
from jinja2.ext import Extension
from jinja2.filters import _GroupTuple, m... |
from rinde.property.animation import Animation
"""
Represents collection of properties with user-friendly interface.
"""
class Properties:
"""
Creates new collection of properties.
"""
def __init__(self):
self.__properties = {}
"""
Inserts new Property object to the collection.
"""
def create(self, name, trig... |
"""
Master Boot Record
The first sector on disk, contains the partition table, bootloader, et al.
http://www.win.tue.nl/~aeb/partitions/partition_types-1.html
"""
from construct import *
from construct.lib.py3compat import b
from binascii import unhexlify
mbr = Struct("mbr",
HexDumpAdapter(Bytes("bootloade... |
"""
Fit to a set of phase diversity images.
For the laboratory setup done by Hancheng, the focal length of the custom lens was ~0.8mm
in air (2mm in glass), meaning that the image was at ~0.813mm from the lens (thin lens
approx for focusing at 50mm or 0.800mm for focusing at infinity. This means that when
defocusing, t... |
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('books', '0004_tag'),
]
operations = [
migrations.AddField(
model_name='book',
name='tags',
field=models.ManyToManyFie... |
"""
A simple validation library for verifying structure and other details of given
data. The motivation for creating this library was failing fast on data
recieved from web services.
""" |
from html.parser import HTMLParser
from urllib import parse
class LinkFinder(HTMLParser):
def __init__(self, base_url, page_url):
super().__init__()
self.base_url = base_url
self.page_url = page_url
self.links = set()
# When we call HTMLParser feed(), this function is called when... |
import sys
import os
cwd = os.getcwd()
project_root = os.path.dirname(cwd)
sys.path.insert(0, project_root)
import swagger_stub
extensions = ['sphinx.ext.autodoc', 'sphinx.ext.viewcode']
templates_path = ['_templates']
source_suffix = '.rst'
master_doc = 'index'
project = u'Swagger Stub'
copyright = u'2016, Cyprien Gui... |
"""
输入一个数组a,和一个整数k,计算出这个数组随机组成的数字,大于或等于的值中最小的一个
"这个算法有问题.有时间再改吧."
"""
a = [1, 3, 4, 5]
k = 1222
a.sort()
kps = False
ks = list(str(k))
length = len(ks)
def _min(lis, v):
for n in lis:
if n < v:
continue
else:
return n
return None
def deep(start, length, kps):
for i in... |
import gzip
import cPickle
from itertools import groupby, compress, imap
from operator import or_
import numpy as np
from learntools.data import Dataset
from learntools.libs.logger import log, log_me
from learntools.libs.utils import normalize_table
def convert_task_from_xls(fname, outname=None):
headers = (('subje... |
from os import stat
from sys import stdout, stderr
import envoy
def run(cmd, *args, **kwargs):
if 'quiet' in kwargs:
del kwargs['quiet']
else:
print cmd
out = envoy.run(cmd, *args, **kwargs)
if out.status_code > 0:
stdout.write("error running command: %s\n" % cmd)
stdout.... |
from __future__ import division # as long as python 2.x is being used
import numpy as np
import spinspy as spy
from .spinspy_classes import SillyHumanError
def get_gridparams(style='vector'):
# read parameters and grid
params = spy.get_params()
gd = spy.get_grid(style=style)
try:
if params.mapp... |
import sys
import llfuse
sys.path.append('./')
from models.zookeepermodel import ZookeeperModel
from core.modelmount import ModelMount
if __name__ == '__main__':
if len(sys.argv) < 2:
raise SystemExit('Usage: %s <mountpoint>' % sys.argv[0])
mountpoint = sys.argv[1]
host = sys.argv[2] if len(sys.argv... |
import webapp2
from common import cloudstorage
from common import template
from google.appengine.ext import blobstore
from google.appengine.api import images
class HomeHandler(webapp2.RequestHandler):
def get(self):
View = template.Jinja("/templates/pages/home")
self.response.out.write(View.render()... |
from __future__ import absolute_import
import warnings
try:
import xraylib_np
except ImportError:
xraylib_np = None
try:
from xraylib import *
except ImportError:
XRayInit = None
warnings.warn("xraylib is not installed", ImportWarning)
else:
XRayInit()
SetErrorMessages(0)
# Code <-> Name... |
from zope.interface import implementer
from rtmlparse.irtml import ITemplate
from rtmlparse.elements import *
@implementer(ITemplate)
class SimplePhotometry(object):
name = "SimplePhotometry"
type = Setup
def __init__(self, element=None, rtml=None):
# define our elements
self.setup = None
... |
from setuptools import setup
with open('README.rst') as readme_file:
readme = readme_file.read()
requirements = [
# TODO: put package requirements here
]
test_requirements = [
# TODO: put package test requirements here
]
setup(
name='asyncio_utils',
version='0.1.4',
description="Asyncio utilitie... |
import unittest
import numpy as np
import pycqed.instrument_drivers.meta_instrument.lfilt_kernel_object as lko
from qcodes import station
class Test_LinDistortionKernelObject(unittest.TestCase):
@classmethod
def setUpClass(self):
self.k0 = lko.LinDistortionKernel('k0')
def setUp(self):
self.... |
import sublime
import sublime_plugin
import json
from os.path import dirname, realpath, join
try:
# Python 2
from node_bridge import node_bridge
except:
from .node_bridge import node_bridge
sublime.Region.totuple = lambda self: (self.a, self.b)
sublime.Region.__iter__ = lambda self: self.totuple().__iter__()
BIN_PAT... |
import os
import sys
import base64
import json
from collections import defaultdict
from itertools import chain
from functools import partial
from operator import attrgetter
from snakemake.io import IOFile, Wildcards, Resources, _IOFile
from snakemake.utils import format, listfiles
from snakemake.exceptions import RuleE... |
__author__ = 'Stefan Wendler, sw@kaltpost.de'
"""
Very simple example showing how to use the SmartPlug API to set the schedule of one day.
"""
from ediplug.smartplug import SmartPlug
p = SmartPlug("192.168.1.117", ('admin', '1234'))
p.schedule = {'state': u'ON', 'sched': [[[11, 15], [11, 45]]], 'day': 6} |
import argparse, json
from boto.mturk.connection import MTurkConnection
from boto.mturk.qualification import *
from jinja2 import Environment, FileSystemLoader
"""
A bunch of free functions that we use in all scripts.
"""
def get_jinja_env(config):
"""
Get a jinja2 Environment object that we can use to find templat... |
from maxwellbloch.version import VERSION as __version__ |
import os, webbrowser, shutil
from string import Template
from pyven.reporting.style import Style
import pyven.constants
from pyven.utils.utils import str_to_file, file_to_str
class HTMLUtils(object):
INDEX = 'index.html'
TEMPLATE_DIR = os.path.join(os.environ.get('PVN_HOME'), 'report', 'html')
TEMPLATE_FIL... |
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello_world():
return 'Hello World!'
if __name__ == '__main__':
app.run(host='0.0.0.0',port=80) |
from django.db import models
from django.conf import settings
from django.db.models import Q
class QuestionManager(models.Manager):
def get_unanswered(self, user):
q1 = Q(useranswer__user=user)
qs = self.exclude(q1)
return qs
class Question(models.Model):
text = models.TextField()
ac... |
import sys
import pickle
import os
import random
print(str(sys.argv))
print(random.uniform(0,1)) |
import sys
import time
import numpy as np
import pygame
try:
#ty @ gdb & ppaquette
import doom_py
import doom_py.vizdoom as vizdoom
except ImportError:
raise ImportError("Please install doom_py.")
class DoomWrapper(object):
def __init__(self, width, height, cfg_file, scenario_file):
self.doo... |
from rdkit import Chem
from rdkit.Chem import AllChem
from sklearn.naive_bayes import BernoulliNB
import cPickle
import glob
import os
import sys
import numpy as np
def introMessage():
print '=============================================================================================='
print ' Author: Lewis Me... |
import codecs
import io
import csv
import sys
import xml.etree.ElementTree as ET
class UnicodeWriter:
"""
A CSV writer which will write rows to CSV file "f", which is encoded in the given encoding.
"""
def __init__(self, f, dialect=csv.excel, encoding="utf-8", **kwds):
# Redirect output to a que... |
import re
def flag(value):
"convert value to integer bool type"
s = str(value).strip().lower()
is_true = s in "yes y true t on 1".split(' ')
return int(is_true)
def join(lst,dlm='',fmt="{0}",strip=True):
if strip:
lst = [x.strip() if hasattr(x,"strip") else x for x in lst]
return dlm.join([fmt.format(x) for x i... |
from big_data_for_education.users import views
from django.conf import settings
from django.conf.urls import include, url
from django.conf.urls.static import static
from django.contrib import admin
from django.views.generic import TemplateView
from django.views import defaults as default_views
urlpatterns = [
url(r... |
"""
statico.pylog
-------------
Provides logging constants and functions
:license: MIT, see LICENSE for more details.
"""
from .utils import u
from colorama import Fore, Back, Style
TICK = u('\u2713')
CROSS = u('\u2717')
ERROR = Fore.WHITE + Back.RED + 'ERROR' + Fore.RESET + Back.RESET
WARNING = Fore.WH... |
"""
Python Interchangeable Virtual Instrument Library
Copyright (c) 2012-2016 Alex Forencich
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the ri... |
from django.shortcuts import get_object_or_404, render
from django.http import HttpResponseRedirect, HttpResponse, HttpResponseNotModified, JsonResponse, HttpResponsePermanentRedirect
from django.db.models import Q, F
from django.contrib.auth.decorators import login_required
from django.utils import timezone
from djang... |
import commands
from scapy.all import *
base = "10.11.1." #IP range to scan minus the last octet.
f = open('snmp_output.txt', 'w+')
for i in range(1, 255):
ip = base+str(i)
print ip+"\n"
p = IP(dst=ip)/UDP(dport=161, sport=39445)/SNMP(community="public",PDU=SNMPget(id=1416992799, varbindlist=[SNMPvarbind(oi... |
import pytest
import random
def create_random(num_elemets):
"""generates a list of random ints, and the sorted list"""
l1 = []
for i in range(num_elemets):
l1.append(random.randint(1, 100))
return l1, sorted(l1)
TABLE = [
([], []),
([0], [0]),
([1, 1], [1, 1]),
([11, 21], [11, 21... |
"""
pyvisa-py.protocols.vxi11
~~~~~~~~~~~~~~~~~~~~~~~~~
Implements a VX11 Session using Python Standard Library.
Based on Python Sun RPC Demo and Alex Forencich python-vx11
This file is an offspring of the Lantz project.
:copyright: 2014 by PyVISA-py Authors, see AUTHORS for more details.
:l... |
"""
homeassistant.components.httpinterface
~~~~~~~~~~~~~~~~~~~~~~~~~~~
This module provides an API and a HTTP interface for debug purposes.
By default it will run on port 8123.
All API calls have to be accompanied by an 'api_password' parameter and will
return JSON. If successful calls will return status code 200 or 20... |
import copy
class Configurable:
global_defaults = {} # type: dict
def __init__(self, **config):
self._variable_defaults = {}
self._user_config = config
def add_defaults(self, defaults):
"""Add defaults to this object, overwriting any which already exist"""
# Since we can't c... |
import subprocess
import re
import sysErrorLog
import syscmd
def git(self):
if self.get_host() not in self.config["opers"]:
self.errormsg = "[NOTICE]-[git] Unauthorized git reguest from {0}".format(self.get_host())
sysErrorLog.log( self )
return
try:
PIPE = subprocess.PIPE
process = subprocess.Popen(['git',... |
from django.apps import AppConfig
class DownloadsConfig(AppConfig):
name = 'downloads' |
import ctypes
from PyQt5 import Qt
class PropertyTableModel(Qt.QAbstractTableModel):
"""PropertyTableModel: Glue for making a Qt.TableView (or similar) in which the elements of a
SignalingList are rows whose columns contain the values of the element properties specified in
the property_names argument suppli... |
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "resumemaker.settings")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv) |
"""
Analytical template tags and filters.
"""
from __future__ import absolute_import
import logging
from django import template
from django.template import Node, TemplateSyntaxError
from importlib import import_module
from analytical.utils import AnalyticalException
TAG_LOCATIONS = ['head_top', 'head_bottom', 'body_top... |
import datetime
from south.db import db
from south.v2 import DataMigration
from django.db import models
class Migration(DataMigration):
def forwards(self, orm):
"Write your forwards methods here."
# Note: Remember to use orm['appname.ModelName'] rather than "from appname.models..."
for link ... |
from ._models_py3 import ActiveDirectoryObject
from ._models_py3 import GenerateCredentialsParameters
from ._models_py3 import GenerateCredentialsResult
from ._models_py3 import ProxyResource
from ._models_py3 import ScopeMap
from ._models_py3 import ScopeMapListResult
from ._models_py3 import ScopeMapUpdateParameters
... |
import _plotly_utils.basevalidators
class FamilyValidator(_plotly_utils.basevalidators.StringValidator):
def __init__(
self,
plotly_name="family",
parent_name="layout.scene.yaxis.title.font",
**kwargs
):
super(FamilyValidator, self).__init__(
plotly_name=plotl... |
import _plotly_utils.basevalidators
class ShowlegendValidator(_plotly_utils.basevalidators.BooleanValidator):
def __init__(self, plotly_name="showlegend", parent_name="splom", **kwargs):
super(ShowlegendValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
... |
from django.utils import timezone
from django.shortcuts import redirect
from django.views.generic import View, TemplateView
from django.shortcuts import render
from django.core.urlresolvers import reverse_lazy
from django.http import HttpResponseRedirect
from .models import BodyWeightWorkout, WeightExercise
from .forms... |
from ..Qt import QtGui, QtCore, QtWidgets
from .GraphicsView import GraphicsView
from ..graphicsItems.GradientEditorItem import GradientEditorItem
import weakref
import numpy as np
__all__ = ['GradientWidget']
class GradientWidget(GraphicsView):
"""
Widget displaying an editable color gradient. The user may add... |
import logging
import os
from unittest import mock
from django.test import TestCase, tag
from django.contrib.auth.models import User
from django.conf import settings
from feeds.models import Feed
from plugins.models import PluginMeta, Plugin
from plugins.models import ComputeResource
from plugins.models import PluginPa... |
import os
import sys
from optparse import OptionParser, NO_DEFAULT
import imp
import django
from django.core.management.base import BaseCommand, CommandError, handle_default_options
from django.utils.importlib import import_module
get_version = django.get_version
_commands = None
def find_commands(management_dir):
... |
import sys
import appdirs
from PyQt5.QtGui import QFontMetrics, QFont
from PyQt5.QtWidgets import QGridLayout, QLabel, QLineEdit, QSystemTrayIcon, QMenu, QDialog, QApplication
from balsa import get_logger, Balsa
import requests
from requests.exceptions import ConnectionError
from propmtime import __application_name__, ... |
../anti_password.py |
from django.conf.global_settings import TEMPLATE_CONTEXT_PROCESSORS
import os
PROJECT_ROOT = os.path.join(os.path.abspath(os.path.dirname(__file__)), '../')
DEBUG = True
TEMPLATE_DEBUG = DEBUG
ADMINS = (
# ('Your Name', 'your_email@example.com'),
)
MANAGERS = ADMINS
DATABASES = {
'default': {
'ENGINE': ... |
import cv2
import matplotlib.pyplot as plt
import numpy as np
import sys
from colormath.color_objects import sRGBColor, LabColor
from colormath.color_conversions import convert_color
from colormath.color_diff import delta_e_cie2000
from itertools import combinations
from sklearn.cluster import KMeans
def centroid_histo... |
"""
Created on 16 Mar 2017
@author: Bruno Beloff (bruno.beloff@southcoastscience.com)
"""
from collections import OrderedDict
from scs_core.data.json import JSONable
class Interval(JSONable):
"""
classdocs
"""
# ---------------------------------------------------------------------------------------------... |
import functools
from typing import Any, Callable, Dict, Generic, Optional, TypeVar
import warnings
from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport im... |
from typing import TYPE_CHECKING
import warnings
from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error
from azure.core.paging import ItemPaged
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import HttpRe... |
from sys import stderr
class Subscriber:
# Attributes that are expected to belong to each Subscriber
subscriber_info = ['email', 'name', 'picture', 'reception', 'sources',
'sub_date', 'last_update', 'mailing_list']
# Attributes describing the bouncing status of the Subscriber
boun... |
import sys
sys.path.append('../..')
import unittest
from math import pi, sqrt
import numpy
from numpy import array, ones
from numpy.fft import fft
import quantum
from quantum.algorithms import grover_invert, grover_search, qft, shor_factor
from quantum.gate_factory import hadamard_gate, phase_shift_gate
from quantum.qu... |
"""Example on how to get plaintext from html using python's beautiful soup."""
from bs4 import BeautifulSoup
def cleanMe(html):
"""Clean html into text only for-real."""
soup = BeautifulSoup(html, "lxml") # create a new bs4 object from html
for script in soup(["script", "style"]): # remove all javascript ... |
"""
Given an array of n integers where n > 1, nums,
return an array output such that output[i] is equal to the product of all the elements of nums except nums[i].
Solve it without division and in O(n).
For example, given [1,2,3,4], return [24,12,8,6].
Follow up:
Could you solve it with constant space complexity?
(Note:... |
"""
WSGI config for leavenproject project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.9/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETT... |
import json
from datetime import datetime
def json_serial(obj):
if isinstance(obj, datetime):
serial = obj.isoformat()
return serial
raise TypeError
def simple_task_definition(arn):
return arn.partition(':task-definition/')[-1]
def simple_container_instance(arn):
return arn.partition(':c... |
import sys
from io import StringIO
from . import cli
from . import StreamReporter, context_name, format_exception, make_readable
from .. import argv_forwarder
class TeamCityReporter(StreamReporter):
@classmethod
def locate(cls):
return (argv_forwarder.ArgvForwarder, cli.DotsReporter)
def setup_parse... |
class Solution(object):
def ltor(self,n):
if n<=2: return n
return 2*self.rtol(n/2)
def rtol(self,n):
if n<=2: return 1
# n is odd,it's the same do n/2 from left to right
if n%2:
return 2*self.ltor(n/2)
# n is even,it should be the possible 2*ltor-1
... |
"""Unit testing utilities for Review Bot."""
from __future__ import unicode_literals
from reviewbot.testing.testcases import TestCase
from reviewbot.testing.utils import get_test_dep_path
__all__ = [
'TestCase',
'get_test_dep_path',
] |
from flask import Flask, redirect, url_for, render_template, flash
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager, UserMixin, login_user, logout_user,\
current_user
from oauth import OAuthSignIn
app = Flask(__name__)
app.config['SECRET_KEY'] = 'top secret!'
app.config['SQLALCHEMY_DATAB... |
subreddit = 'fightporn'
t_channel = '@r_fightporn'
def send_post(submission, r2t):
return r2t.send_simple(submission) |
import sys
from cfg import config
from lib import *
from github import Github
import github.GithubException as GithubException
from github.GithubException import BadCredentialsException
token = config.get('github', 'token')
orgn = config.get('github', 'organization')
base_branch = config.get('branches', 'base')
main_br... |
from ..notebook_gisthub import NotebookGistHub
from ..gisthub import GistHub
from .test_gisthub import generate_gisthub
from nbx.tools import assert_items_equal
from nbx.nbmanager.tests.common import (
hub,
require_github,
make_notebookgist,
)
class TestNotebookGist:
def test_notebookgist(self):
... |
class role:
'A representation of a werewolf role'
def __init__(self, args = {}):
self.options = {
'alive': True,
'evil': False,
'health': 1,
'max_evil': False,
'parity': 1,
'role': 'Villager',
'vote_weight': 1
}
self.options.update(args) # overwrite with instantiation vars
def dum... |
__all__ = ['NList']
__doc__ = """This module provides class :class:`NList`, a multidimensional list.
Indexes and shapes used with NList must be tuples.
Example:
::
l = nlist.NList(shape=(2, 3))
l[1, 2] = 42
NList's shape can be an empty tuple meaning a zero-dimensional list that has
one element with index ().
N... |
from __future__ import division
import re
from .association import Association
from .entity import Entity
from .phantom import Phantom
from .diagram_link import DiagramLink
import itertools
from collections import defaultdict
from .grid import Grid
from .mocodo_error import MocodoError
compress_colons = re.compile(r"(?... |
import copy
import os
import re
import shutil
import subprocess
import sys
import unittest
from doxygen import State, parse_doxyfile, run, default_templates, default_wildcard, default_index_pages, default_config
_camelcase_to_snakecase = re.compile('((?<=[a-z0-9])[A-Z]|(?!^)[A-Z](?=[a-z]))')
def doxygen_version():
... |
from typing import Any, TYPE_CHECKING
from azure.core.configuration import Configuration
from azure.core.pipeline import policies
from azure.mgmt.core.policies import ARMChallengeAuthenticationPolicy, ARMHttpLoggingPolicy
from ._version import VERSION
if TYPE_CHECKING:
# pylint: disable=unused-import,ungrouped-impo... |
import requests
class OpenWeatherMap():
def __init__(self):
# This is the base URL for the API and will be common to all requests
self.api_url = 'http://api.openweathermap.org/data/2.5/'
def get_forecast(self, city='', country=''):
# Append the "forecast" path to the base API URL
url... |
def call(COMMENT, args):
print(str(COMMENT))
print('(' + str(args['player'].x) + ',' + str(args['player'].y) + ')') |
"""
MIT License
Copyright (c) 2017 - 2018 FrostLuma
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.