code stringlengths 1 199k |
|---|
import inspect
import textwrap
import timeit
import unittest
import bcrypt
from cloudhands.common.schema import BcryptedPassword
class BcryptTests(unittest.TestCase):
@staticmethod
def setup():
import bcrypt
password = "Q1w2E3r4T5y6"
hash = bcrypt.hashpw(password, bcrypt.gensalt(12))
... |
from django.conf import settings
def admin_media_prefix(request):
'''
Starting from django 1.4, the static files belonging to django admin follow
the standard conventions.
'''
return {'ADMIN_MEDIA_PREFIX': settings.STATIC_URL + 'admin/' } |
import tests.periodicities.period_test as per
per.buildModel((30 , 'BH' , 400)); |
"""Utility functions to collect the defined driver types and driver.
Drivers and driver types are looked for in all modules presents in clib and
visa. Drivers should be declared in a module variable DRIVERS and driver types
in one named DRIVER_TYPES. Both should be dictionary of name: class. Driver
types are generic dr... |
from __future__ import absolute_import
from bifrost.libbifrost import _bf, _check
from bifrost.ndarray import asarray
from bifrost import telemetry
telemetry.track_module()
def quantize(src, dst, scale=1.):
src_bf = asarray(src).as_BFarray()
dst_bf = asarray(dst).as_BFarray()
_check(_bf.bfQuantize(src_bf, d... |
import unittest
import numpy as np
from lib.binary import iterate_binary_dataset
class BinaryTests(unittest.TestCase):
def test_data_set_consistency(self):
"""...Test binary datasets have the expected shape
"""
for name, x, y, n_observations, n_features in \
iterate_binary_da... |
from __future__ import absolute_import, division, print_function
from builtins import range
import math
import sys
import time
import pp
def isprime(n):
"""Returns True if n is prime and False otherwise"""
if not isinstance(n, int):
raise TypeError("argument passed to is_prime is not of 'int' type")
... |
import re
import urllib
import urllib2
import httplib
import socket
import unicodedata
from xml.etree import ElementTree
__author__ = "Michael Stephens <mstephens@sunlightfoundation.com>"
__copyright__ = "Copyright (c) 2011 Sunlight Labs"
__license__ = "BSD"
__version__ = '0.4.1'
TIMEOUT = 15
class NimspApiError(Except... |
"""
:func:`~pandas.eval` source string parsing functions
"""
from io import StringIO
from keyword import iskeyword
import token
import tokenize
from typing import Iterator, Tuple
BACKTICK_QUOTED_STRING = 100
def create_valid_python_identifier(name: str) -> str:
"""
Create valid Python identifiers from any strin... |
"""
Picarto.TV API Documentation
The Picarto.TV API documentation Note, for fixed access tokens, the header that needs to be sent is of the format: `Authorization: Bearer yourTokenHere` This can be generated at https://oauth.picarto.tv/ For chat API, see https://docs.picarto.tv/chat/chat.proto - contact via ... |
import os
from google.appengine.ext import webapp
from google.appengine.ext.webapp import template
from google.appengine.ext import db
from google.appengine.api import users
from google.appengine.api import memcache
from config import DIR, VERSION
from models import MBook, DictLog
from utils.parsexml import MarXML
from... |
from .arguments import *
__all__ = (
'QueryArgument', 'BooleanQueryArgument', 'NullBooleanQueryArgument',
'CharQueryArgument', 'EmailQueryArgument', 'IntegerQueryArgument',
'RegexQueryArgument', 'SlugQueryArgument', 'URLQueryArgument',
'DecimalQueryArgument', 'FloatQueryArgument',)
class QueryArgument(A... |
def extractRancer(item):
"""
"""
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not (chp or vol) or 'preview' in item['title'].lower():
return None
if 'The Strongest Magical Beast' in item['tags'] and 'Chapter Release' in item['tags'] and (chp or vol):
return buildReleaseMessageWi... |
from __future__ import unicode_literals
from django.db import models, migrations
from django.db.models.fields import CharField
import jobs.models
class LowerCaseCharField(CharField):
"""
Defines a charfield which automatically converts all inputs to
lowercase and saves.
"""
def pre_save(self, model_... |
import re, os
from genshi import Markup
from trac.core import *
from trac.config import Option
from trac.db.api import IDatabaseConnector, _parse_db_str
from trac.db.util import ConnectionWrapper, IterableCursor
from trac.util import get_pkginfo
from trac.util.compat import close_fds
from trac.util.text import empty, e... |
from gi.repository import Gtk
from gi.repository import Gdk
class TemplateWindow:
def __init__(self):
self.gtkwin = Gtk.Window()
self.gtkwin.set_position(Gtk.WindowPosition.CENTER)
self.gtkwin.connect("destroy", self.on_destroy)
self.gtkwin.connect('key-release-event', self.on_key_release)
self.is_fullscreen... |
import os
import sys
extensions = []
templates_path = ['_templates']
source_suffix = '.rst'
master_doc = 'index'
project = u'EasyPMP'
copyright = u"2015, Sergio Jardim"
version = '0.1'
release = '0.1'
exclude_patterns = ['_build']
pygments_style = 'sphinx'
html_theme = 'default'
html_static_path = ['_static']
htmlhelp_... |
"""Windows implementations. Requires pywin32."""
import os
import win32api
import win32con
import win32event
import win32service
import win32serviceutil
from magicbus import base, plugins
class Win32Bus(base.Bus):
"""A Bus implementation for Win32.
Instead of time.sleep, this bus blocks using native win32event ... |
"""
bgp.py
Created by Thomas Mangin on 2014-06-22.
Copyright (c) 2014-2015 Exa Networks. All rights reserved.
"""
from exabgp.configuration.engine.registry import Raised
from exabgp.configuration.engine.section import Section
syntax_bmp = """\
bmp {
lots here
}
"""
class RaisedBMP (Raised):
syntax = syntax_bmp
class ... |
from __future__ import unicode_literals
import bitfield.models
from django.db import migrations
import django.db.models.manager
class Migration(migrations.Migration):
"""
BEGIN;
--
-- Alter field flags on project
--
COMMIT;
"""
# This flag is used to mark that a migration shouldn't be au... |
"""Calculate irreducible representation from eigenvectors."""
from typing import Union
import numpy as np
from phonopy.harmonic.derivative_dynmat import DerivativeOfDynamicalMatrix
from phonopy.harmonic.dynamical_matrix import DynamicalMatrix, DynamicalMatrixNAC
from phonopy.harmonic.force_constants import similarity_t... |
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('django_th', '__first__'),
]
operations = [
migrations.CreateModel(
name='Wallabag',
fields=[
('id', models.AutoFi... |
from __future__ import absolute_import, division, print_function
import pytest
import numpy as np
from matplotlib.ticker import AutoLocator, MaxNLocator, LogLocator
from matplotlib.ticker import LogFormatterMathtext, ScalarFormatter, FuncFormatter
from mock import MagicMock
from timeit import timeit
from functools impo... |
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('merch', '0003_doorregistermerchpluginmodel_autofulfill'),
]
operations = [
migrations.AddField(
model_name='merchorder',
name='data',
field=models.JSONField(... |
"""
Copyright (c) 2013 Rodrigo Baravalle
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
notice, this list of conditions and the following... |
"""Git implementation of _version.py."""
import errno
import os
import re
import subprocess
import sys
def get_keywords():
"""Get the keywords needed to look up the version information."""
# these strings will be replaced by git during git-archive.
# setup.py/versioneer.py will grep for the variable names, ... |
from django.conf.urls.defaults import *
from django.contrib import admin
admin.autodiscover()
handler500 = 'djangotoolbox.errorviews.server_error'
urlpatterns = patterns('',
('^_ah/warmup$', 'djangoappengine.views.warmup'),
(r'^admin/', include(admin.site.urls)),
url(r'^$','blog.views.index',name="blog_inde... |
from functools import partial
from corehq.form_processor.interfaces.dbaccessors import CaseAccessors
from dimagi.utils.dates import force_to_datetime
import fluff
from corehq.fluff.calculators.case import CasePropertyFilter
from custom.world_vision import WORLD_VISION_DOMAINS
from corehq.apps.users.models import CommCa... |
from django.contrib.auth.models import User
from django.db import models
from django.contrib.contenttypes import generic
from django.contrib.contenttypes.models import ContentType
from django.db.models.signals import pre_save, post_save, pre_delete, post_delete
from django.core.cache import cache
from django.dispatch i... |
import time
from kivy.core.window import Window
from kivy.core.image import Image
from kivy.graphics import Rectangle
res_dir = './'
class FilePathsMap:
def __init__(self):
self.space = res_dir + 'resources/images/map/space.gif'
self.block = res_dir + 'resources/images/map/block.jpg'
self.ma... |
import logging
import ROOT
def is_ROOT_null_pointer(tobject):
try:
tobject.GetName()
return False
except ReferenceError:
return True
def get_entries_in_tree_in_file(path, tree_name, raises=False):
##
file_ = ROOT.TFile.Open(path)
if is_ROOT_null_pointer(file_) or file_.IsZomb... |
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Deleting model 'ActionClusterVersion'
db.delete_table(u'actionclusters_actionclusterversion')
... |
from __future__ import absolute_import
import os.path
try:
import pkg_resources
except ImportError:
# pkg_resource is not available on Google App Engine
pkg_resources = None
from .exceptions import InvalidGitRepository
__all__ = ('fetch_git_sha', 'fetch_package_version')
def fetch_git_sha(path, head=None):
... |
import numpy as np
test_angles = [360, 358, 2, 0]
def mean_angle(angles):
sum = 0;
for angle in angles:
sum += angle
return (float(sum) / len(angles))
def unit_vector(deg):
"""
Returns unit vector in form (x, y) from angle in degrees
"""
rad = np.deg2rad(deg)
return (np.cos(rad), np.sin(rad))
def me... |
import george
import unittest
import numpy as np
import scipy.linalg as spla
from robo.models.gaussian_process import GaussianProcess
from robo.priors.default_priors import TophatPrior
class TestGaussianProcess(unittest.TestCase):
def setUp(self):
self.X = np.random.rand(10, 2)
self.y = np.sinc(self... |
import interfaces
import aliaser
import composition
import events
import locking
import _zodict
import _node
from node.utils import (
Zodict,
ReverseMapping,
AttributeAccess,
)
from node.bbb import (
Node,
AttributedNode,
LifecycleNode,
)
from node.composition import Composition
import sys
sys.m... |
from httpca_web import app
def run():
pass |
import tests.periodicities.period_test as per
per.buildModel((5 , 'S' , 200)); |
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'VersionSeries'
db.create_table(u'core_versionseries', (
(u'id', self.gf(... |
from django.contrib import admin
from helios.store.models import *
from helios.store.forms import MyCategoryAdminForm
from helios.conf import settings
if settings.IS_MULTILINGUAL:
import multilingual
admin_info = {'class': multilingual.ModelAdmin, 'suffix': '_en'}
else:
admin_info = {'class': admin.ModelAdm... |
''' Bokeh Application Handler to look for Bokeh server lifecycle callbacks
in a specified Python module.
'''
import logging # isort:skip
log = logging.getLogger(__name__)
import codecs
import os
from ...util.callback_manager import _check_callback
from .code_runner import CodeRunner
from .lifecycle import LifecycleHand... |
from __future__ import division
from math import log, ceil, floor
import os
import re
from subprocess import Popen, PIPE
import sys
from tempfile import TemporaryFile
from warnings import warn
try:
import audioop
except ImportError:
import pyaudioop as audioop
if sys.version_info >= (3, 0):
basestring = str... |
'''
add.py: wrapper for "add" of a key to a json file for Singularity Hub command line tool.
This function takes input arguments (not environment variables) of the following:
--key: should be the key to lookup from the json file
--value: the value to add to the key
--file: should be the json file to read
Copyr... |
"""
This is part of shot detector.
Produced by w495 at 2017.05.04 04:18:27
"""
from __future__ import absolute_import, division, print_function
import logging
from .base_stat_swfilter import BaseStatSWFilter
class MeanSWFilter(BaseStatSWFilter):
"""
...
"""
__logger = logging.getLogger(__nam... |
__version__=''' $Id: dodyssey.py 3959 2012-09-27 14:39:39Z robin $ '''
__doc__=''
import sys, copy, os
from reportlab.platypus import *
_NEW_PARA=os.environ.get('NEW_PARA','0')[0] in ('y','Y','1')
_REDCAP=int(os.environ.get('REDCAP','0'))
_CALLBACK=os.environ.get('CALLBACK','0')[0] in ('y','Y','1')
if _NEW_PARA:
de... |
"""
Copyright (c) 2014-2016, GhostBSD. 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. Redistribution's of source code must retain the above copyright
notice, this list of conditions and the followi... |
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding M2M table for field belongs_to on 'Participant'
m2m_table_name = db.shorten_name(u'public_project_participant_belongs_to')
... |
__author__ = 'Bohdan Mushkevych'
from synergy.db.error import DuplicateKeyError
from synergy.db.model.job import Job
from synergy.system import time_helper
from synergy.system.time_qualifier import QUALIFIER_HOURLY
from tests.base_fixtures import create_unit_of_work
TEST_PRESET_TIMEPERIOD = '2013010122'
TEST_ACTUAL_TIM... |
from nose.tools import eq_, with_setup, assert_raises
import util
import urllib2
import sy.net
def teardown():
util.tmppath.teardown()
util.teardown_urllib_mock()
def test_http_download():
mock = util.MockHTTPHandler()
util.setup_urllib_mock(mock)
p = util.tmppath()
sy.net.download('http://www',... |
from django.test import TestCase
import os
from django.test.utils import override_settings
from casexml.apps.case.tests.util import delete_all_xforms, delete_all_cases
from corehq.apps.receiverwrapper.util import submit_form_locally
from corehq.form_processor.interfaces.dbaccessors import CaseAccessors
@override_settin... |
__author__ = 'Justin S Bayer, bayer.justin@googlemail.com'
from setuptools import setup, find_packages
setup(
name="PyBrain",
version="0.3",
description="PyBrain is the Swiss army knife for neural networking.",
license="BSD",
keywords="Neural Networks Machine Learning",
url="http://pybrain.org",... |
from datetime import date
import json
import math
import pprint
import os
import re
import sys
sys.path.append('..')
import angle_format
template_table_autogen_cpp = """// GENERATED FILE - DO NOT EDIT.
// Generated by {script_name} using data from {input_file_name}
//
// Copyright {copyright_year} The ANGLE Project Aut... |
"""
Test that base hrefs are added to each entry.
"""
from tiddlyweb.serializer import Serializer
from tiddlyweb.model.tiddler import Tiddler
from tiddlyweb.config import config
import tiddlywebwiki
def setup_module(module):
tiddlywebwiki.init(config)
module.serializer = Serializer('tiddlywebplugins.atom.feed',... |
import numpy as np
from numpy.testing import assert_almost_equal
from numpy.testing import assert_allclose
from scipy.optimize import newton
from scipy.special import logit
from sklearn.utils import assert_all_finite
from sklearn.utils.fixes import sp_version, parse_version
import pytest
from sklearn.ensemble._hist_gra... |
from __future__ import absolute_import
from django.db import transaction, DatabaseError
from django_atomic_celery import task
from contextlib import closing
try:
import simplejson as json
except ImportError:
import json
from .validation import get_schema_prefix, ijson
from .urls import inspect_url, remove_url_f... |
""""
Take event file and create multiple new event files separated by CCD
command from CIAO: dmcopy filtered_event.fits[EVENTS][ccd_id=N] out.fits clobber=yes
Make sure CIAO is running before running this script
"""
import argparse
import os
import subprocess
import astropy.io.fits as pyfits
from chandra_suli.run_comma... |
from blaze.expr import symbol, summary
from datashape import dshape
def test_reduction_dshape():
x = symbol('x', '5 * 3 * float32')
assert x.sum().dshape == dshape('float64')
assert x.sum(axis=0).dshape == dshape('3 * float64')
assert x.sum(axis=1).dshape == dshape('5 * float64')
assert x.sum(axis=(... |
import json
from django.http import HttpResponse
from django.core.context_processors import csrf
from django.shortcuts import render_to_response, redirect
from django.contrib.auth.models import User
from django.conf import settings
from models import CollectionItem
'''
[
{
"data": "title",//required fie... |
"""
Handle the password database, encryption, and decryption. The database is a binary format with the following spec:
Database file
=============
Offset Type Description
-----------------------------------
0 byte* 8-byte signature: C7 64 A2 F3 AF DE 56 CD
8 byte* 16-byte ini... |
import unittest
from errorpro import commands
import sympy
from errorpro.dimensions.dimensions import Dimension
from errorpro.exceptions import DimensionError
from sympy import Symbol, S
from errorpro.si import system as si
import numpy as np
from errorpro import fit_scipy
from errorpro.project import Project
class Ass... |
import sys
class FullTraceback:
def __init__(self, tb_frame, tb_lineno, tb_next):
self.tb_frame = tb_frame
self.tb_lineno = tb_lineno
self.tb_next = tb_next
def current_stack(skip=0):
p_frame = None
try:
1 / 0
except ZeroDivisionError:
p_frame = sys.exc_info()[2].... |
"""Run tests in parallel."""
from __future__ import print_function
import argparse
import ast
import collections
import glob
import itertools
import json
import multiprocessing
import os
import os.path
import pipes
import platform
import random
import re
import socket
import subprocess
import sys
import tempfile
import... |
from __future__ import print_function, division
from itertools import chain, product
import six
import networkx as nx
from networkx.algorithms.bipartite import projected_graph
from py3compat import izip, irange
from order_util import deterministic_topological_sort, coo_matrix_to_bipartite,\
get_i... |
import unicodedata
import re
from optparse import make_option
from django.core.management.base import BaseCommand, CommandError
from django.contrib.auth.models import User, Group
from eve_api.app_defines import API_STATUS_OK
from sso.tasks import update_user_access
class Command(BaseCommand):
help = ("Assigns a gro... |
import sys, urllib2, json, time, subprocess, os, commands,signal, argparse
sys.path.insert(0, 'srch2lib')
import test_lib
port = '8087'
numberOfFacetFields= 3;
def checkResult(query, responseJsonAll,resultValue, facetResultValue):
responseJson = responseJsonAll['results']
isPass=1
if len(responseJson) == l... |
def get_vertices(patch_ids, vertex_list):
"""
Extracts the relevant vertices for a single patch from the vertex list.
:param patch_ids: list of vertex ids of current patch
:param vertex_list: list of all vertices
:return: list of vertices of the current patch in lexicographical order
"""
vertices = []
for v_id ... |
import tensorflow as tf
def while_loop(cond, body, loop_vars, parallel_iterations=10, back_prop=True, swap_memory=False, name=None):
def cond2(*ls): return cond(ls)
def body2(*ls): return body(ls)
return tf.while_loop(cond2, body2, loop_vars, parallel_iterations, back_prop, swap_memory, name) |
import re
from datetime import timedelta
from mock import patch
from django.core import management
from django.test import TestCase
from django.test.utils import override_settings
from django.utils.timezone import now
import requests
from .factories import ConsumedProxyGrantingTicketFactory
from .factories import Consu... |
import logging
import fmcapi
import time
def test__ftddevicehapairs(fmc):
logging.info(
'Test FTDDeviceHAPairs. After an HA Pair is created, all API calls to "devicerecords" objects should '
"be directed at the currently active device not the ha pair"
)
failover1 = fmcapi.PhysicalInterfaces(... |
"""
This script downloads synchronization data from a remote server,
deletes local xforms and submissions, and loads the data
"""
import bz2
import sys
import tarfile
import urllib2
import httplib
import cStringIO
from urlparse import urlparse
from optparse import make_option
from django.core.management.base import Lab... |
from django.apps import AppConfig
class MailerConfig(AppConfig):
name = 'mailer'
verbose_name = 'Sana Protocol Builder - Email Module'
def ready(self):
pass |
"""
Classes and utilities to manage the registration and execution of migrations in
a refugee install
"""
from fnmatch import filter as file_filter
from imp import find_module, load_module
from os import makedirs, walk
from os.path import join as pjoin
from sqlalchemy import create_engine
from migration import (
Di... |
from setuptools import setup
setup(
name='sulley',
packages=['sulley'],
version='0.1.0b0',
description=('With Sulley, you can build SMS bots in just'
' a few lines of code. Powered by Twilio & Plivo,'
' Sulley requires very minimal configuration and '
'... |
"""
test template for nosetests
"""
from nose.tools import *
from isaw.images import flickr, package
import logging
import os
import shutil
logging.basicConfig(level=logging.DEBUG)
def test_instantiate_package():
f = flickr.Flickr()
def test_authentication_pass():
"""
ensure we can pass key and secret via t... |
import time, datetime
RECURSIVE_RELATIONSHIP_CONSTANT = 'self'
__all__ = ['Field', 'AttributeField', 'CounterField', 'AutoCounterField', \
'ListField', 'BooleanField', 'TimeField', 'DateTimeField', \
'BitField', 'SetField', 'ReferenceField', 'CounterField']
class Field(object):
def __init__(... |
"""
cpsdirector.application
=======================
ConPaaS director: application support.
:copyright: (C) 2013 by Contrail Consortium.
"""
from flask import Blueprint
from flask import jsonify, request, g
import simplejson, sys, traceback
import ConfigParser
from netaddr import IPNetwork
from threading... |
from openapi_core.templating.responses.exceptions import ResponseNotFound
class ResponseFinder:
def __init__(self, responses):
self.responses = responses
def find(self, http_status="default"):
if http_status in self.responses:
return self.responses / http_status
# try range
... |
import math
from django.utils.translation import ugettext as _
from django.db.models.aggregates import Count
from plugins.models import Plugin, PluginVersion
from taxonomy.models import TaxonomyMap, TaxonomyTerm
LOGARITHMIC, LINEAR = 1, 2
def get_tag_counts():
tags = {}
taxonomy_term_ids = TaxonomyMap.objects.filter(... |
import io
import json
import os
import unittest
from . import coverage
from .fhirdate import FHIRDate
class CoverageTests(unittest.TestCase):
def instantiate_from(self, filename):
datadir = os.environ.get('FHIR_UNITTEST_DATADIR') or ''
with io.open(os.path.join(datadir, filename), 'r', encoding='utf... |
"""Test the Go OS Plugin."""
from __future__ import print_function
import os
import time
import lldb
from lldbsuite.test.decorators import *
from lldbsuite.test.lldbtest import *
from lldbsuite.test import lldbutil
class TestGoASTContext(TestBase):
mydir = TestBase.compute_mydir(__file__)
@add_test_categories([... |
import factory
import factory.django
from machina.core.db.models import get_model
from machina.test.factories.auth import UserFactory
from machina.test.factories.conversation import TopicFactory
from machina.test.factories.forum import ForumFactory
ForumReadTrack = get_model('forum_tracking', 'ForumReadTrack')
TopicRea... |
from devilry.devilry_import_v2database import v2dump_directoryparser
class V2PointToGradeMapDirectoryParser(v2dump_directoryparser.V2DumpDirectoryParser):
def get_app_label(self):
return 'core'
def get_model_name_lowercase(self):
return 'pointtogrademap' |
from django import forms
from django.contrib import messages
from django.http import HttpResponseRedirect
from django.urls import reverse
from django.utils.translation import gettext
from django.utils.translation import gettext_lazy as _
from wakawaka.models import Revision
class WikiPageForm(forms.Form):
content =... |
"""AppInfo tools.
Library for working with AppInfo records in memory, store and load from
configuration files.
"""
import logging
import os
import re
import string
import sys
import wsgiref.util
if os.environ.get('APPENGINE_RUNTIME') == 'python27':
from google.appengine.api import pagespeedinfo
from google.appengin... |
import os.path as op
import shutil
from optparse import OptionParser
import sfepy
from sfepy.base.base import *
from sfepy.base.conf import ProblemConf, get_standard_keywords
from sfepy.applications import SimpleApp
def print_terms():
import sfepy.terms as t
tt = t.term_table
ct = t.cache_table
print 'T... |
from __future__ import annotations
import os
import xml.etree.ElementTree as ET
from xia2.Driver.DriverFactory import DriverFactory
def BestStrategy(DriverType=None):
DriverInstance = DriverFactory.Driver(DriverType)
class BestStrategyWrapper(DriverInstance.__class__):
def __init__(self):
Dr... |
import copy
from combat.enums import DamageType
from components.game_object import GameObject
class Item(GameObject):
NAME = "item"
"""
What is an item?
It made out of a material, it has a type, it can be used.
It has stats, it can be destroyed, displayed, held.
It can have a rarity, a level, va... |
from systemofrecord import app
from systemofrecord.controllers import load_title_controller, store_title_controller
from flask import request
import json
@app.route('/titles/<object_id>', methods=['GET'])
def get_object(object_id):
return load_title_controller.load_object(object_id)
@app.route('/titles/<object_id>'... |
import frappe
from frappe.model.document import Document
class Milestone(Document):
pass
def on_doctype_update():
frappe.db.add_index("Milestone", ["reference_type", "reference_name"]) |
import subprocess
import sys
import pytest
from setuptools_scm import get_version
from setuptools_scm.git import parse
from setuptools_scm.utils import do
from setuptools_scm.utils import do_ex
def test_pkginfo_noscmroot(tmpdir, monkeypatch):
"""if we are indeed a sdist, the root does not apply"""
monkeypatch.d... |
from django.shortcuts import render
from django.http import HttpResponse, HttpResponseNotFound
from events.models import EventsIndexPage
def event_data(request):
future = request.GET.get('future', 'False')
try:
if future.lower() == 'true':
data = EventsIndexPage.objects.get().events(future=T... |
import pyPdf
import optparse
from pyPdf import PdfFileReader
def printMeta(fileName):
pdfFile = PdfFileReader(file(fileName, 'rb'))
docInfo = pdfFile.getDocumentInfo()
print '[*] PDF MetaData For: ' + str(fileName)
for metaItem in docInfo:
print '[+] ' + metaItem + ':' + docInfo[metaItem]
def ma... |
from ddt import data, ddt
from rest_framework import status, test
from waldur_core.structure.tests import fixtures as structure_fixtures
from waldur_mastermind.invoices import models
from waldur_mastermind.invoices.tests import factories
@ddt
class PaymentRetrieveTest(test.APITransactionTestCase):
def setUp(self):
... |
def test(something):
pass |
import os
from . import base
class DF(base.ThreadedPollText):
"""
Disk Free Widget
By default the widget only displays if the space is less than warn_space
"""
defaults = [
('partition', '/', 'the partition to check space'),
('warn_color', 'ff0000', 'Warning color'),
('warn_s... |
"""
homeassistant.components.input_boolean
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Component to keep track of user controlled booleans for within automation.
For more details about this component, please refer to the documentation
at https://home-assistant.io/components/input_boolean/
"""
import logging
from homeassista... |
"""
Birth death process and reconstructed process for trees
"""
from math import exp
import random
from rasmus import util, stats, treelib
def prob_birth_death1(ngenes, t, birth, death):
"""
Returns the probability that one lineage leaves 'ngenes' genes
after time 't'
"""
# special cases
if bir... |
from django import forms
from django.utils.translation import ugettext_lazy as _
from django.utils.translation import pgettext_lazy
from oscar.core.compat import get_user_model
from oscar.apps.customer.forms import generate_username
from oscar.apps.customer.forms import EmailUserCreationForm as CoreEmailUserCreationFor... |
from som.primitives.primitives import Primitives
from som.vm.globals import nilObject
from som.vmobjects.abstract_object import AbstractObject
from som.vmobjects.array_strategy import Array
from som.vmobjects.method_ast import AstMethod
from som.vmobjects.primitive import AstPrimitive as Primitive
def _hold... |
import ipaddress
from CommonServerPython import *
def cidr_network_addresses_greater_from_const(ip_cidr: str, min_num_addresses: str) -> bool:
""" Decide if num_adddresses const is greater than availble addresses in IPv4 or IPv6 cidr
Args:
ip_cidr(str): IP/CIDR, e.g. 192.168.0.0/24, 2002::1234:abcd:ffff... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.