content stringlengths 4 20k |
|---|
class Particle(object):
def __init__(self, sprite):
self.gravity = PVector(0, 0.1)
self.lifespan = 255
self.velocity = PVector()
partSize = random(10, 60)
self.part = createShape()
self.part.beginShape(QUAD)
self.part.noStroke()
self.part.texture(spri... |
# encoding: utf-8
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Deleting field 'Address.longtitude'
db.delete_column('easy_maps_address', 'longtitude')
def backwar... |
{
'name': 'Peru Localization Chart Account',
'version': '1.0',
'description': """
Peruvian accounting chart and tax localization. According the PCGE 2010.
========================================================================
Plan contable peruano e impuestos de acuerdo a disposiciones vigentes de la
SUN... |
from pycbc.filter import correlate
from pycbc.filter.matchedfilter import BatchCorrelator, Correlator
from pycbc.types import zeros, complex64, complex128, Array
from time import time
from numpy.random import uniform
niter = 2000
for N in [2**10, 2**15, 2**18]:
a = zeros(N, dtype=complex64)
a.data += uniform(... |
"""
Tests of the LMS XBlock Mixin
"""
import ddt
from xblock.validation import ValidationMessage
from xmodule.modulestore import ModuleStoreEnum
from xmodule.modulestore.tests.factories import CourseFactory, ToyCourseFactory, ItemFactory
from xmodule.modulestore.tests.django_utils import ModuleStoreTestCase, TEST_DATA... |
import sys
import warnings
from contextlib import contextmanager
from typing import Generator
from typing import Optional
from typing import TYPE_CHECKING
import pytest
from _pytest.config import apply_warning_filters
from _pytest.config import Config
from _pytest.config import parse_warning_filter
from _pytest.main i... |
from libcloud.common.types import LibcloudError
from libcloud.common.aws import SignedAWSConnection, DEFAULT_SIGNATURE_VERSION
from libcloud.storage.drivers.s3 import BaseS3Connection, S3Connection
from libcloud.storage.drivers.s3 import S3StorageDriver, API_VERSION
__all__ = [
'S3RGWStorageDriver',
'S3RGWOuts... |
# These tests do not currently do much to verify the correct implementation
# of the openid/oauth protocols, they just exercise the major code paths
# and ensure that it doesn't blow up (e.g. with unicode/bytes issues in
# python 3)
from __future__ import absolute_import, division, print_function, with_statement
from... |
"""
This module collects helper functions and classes that "span" multiple levels
of MVC. In other words, these functions/classes introduce controlled coupling
for convenience's sake.
"""
import warnings
from django.core import urlresolvers
from django.db.models.base import ModelBase
from django.db.models.manager imp... |
# -*- coding: utf-8 -*-
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 model 'Usuario'
db.create_table(u'skeleton_usuario', (
(u'id', self.gf('django.db.model... |
import ctypes
import socket
import sys
if sys.platform == 'win32':
import wmi
from nova.i18n import _
from nova.virt.hyperv import constants
class HostUtils(object):
_HOST_FORCED_REBOOT = 6
_HOST_FORCED_SHUTDOWN = 12
_DEFAULT_VM_GENERATION = constants.IMAGE_PROP_VM_GEN_1
def __init__(self):
... |
import sys, traceback
import mal_readline
import mal_types as types
import reader, printer
from env import Env
import core
# read
def READ(str):
return reader.read_str(str)
# eval
def eval_ast(ast, env):
if types._symbol_Q(ast):
return env.get(ast)
elif types._list_Q(ast):
return types._li... |
import argparse
import json
import sys
import pkg_resources
import pbr.version
def _get_metadata(package_name):
try:
return json.loads(
pkg_resources.get_distribution(
package_name).get_metadata('pbr.json'))
except pkg_resources.DistributionNotFound:
raise Excepti... |
from openerp.osv import fields, orm, expression
from openerp.tools.translate import _
class res_partner(orm.Model):
_inherit = 'res.partner'
def _type_selection(self, cr, uid, context=None):
return [
('standalone', _('Standalone Contact')),
('attached', _('Attached to existing... |
import sys
from services.spawn import MobileTemplate
from services.spawn import WeaponTemplate
from resources.datatables import WeaponType
from resources.datatables import Difficulty
from resources.datatables import Options
from java.util import Vector
def addTemplate(core):
mobileTemplate = MobileTemplate()
mobi... |
"""Ce fichier définit le contexte-éditeur 'flag'."""
from . import Editeur
class Flag(Editeur):
"""Contexte-éditeur flag.
Ce contexte permet de changer la valeur True ou False d'un attribut.
"""
nom = "editeur:base:flag"
def entrer(self):
"""Quand on entre dans le contexte"""
... |
# -*- coding: utf-8 -*-
from ..Qt import QtGui, QtCore
from .. import functions as functions
__all__ = ['ColorButton']
class ColorButton(QtGui.QPushButton):
"""
**Bases:** QtGui.QPushButton
Button displaying a color and allowing the user to select a new color.
====================== ========... |
# A simple FTP client.
#
# The information to write this program was gathered from RFC 959,
# but this is not a complete implementation! Yet it shows how a simple
# FTP client can be built, and you are welcome to extend it to suit
# it to your needs...
#
# How it works (assuming you've read the RFC):
#
# User commands... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
try:
from msrestazure.azure_exceptions import CloudError
except:
# This is handled ... |
import json
import math
import physics
import random
import time
from ClientAPI import BaseContext, readable
@readable('location', 'rotation', 'velocity', 'universe', 'radius', 'mass', 'events')
class Entity:
class Context(BaseContext):
def __init__(self, instance=None, serial=None):
if instance:
s... |
import re
from django.conf import settings
from django.contrib.gis.db.backends.base.operations import \
BaseSpatialOperations
from django.contrib.gis.db.backends.utils import SpatialOperator
from django.contrib.gis.gdal import GDALRaster
from django.contrib.gis.geometry.backend import Geometry
from django.contrib.... |
"""Additional help about gsutil's interaction with Cloud Storage APIs."""
from gslib.help_provider import HelpProvider
_DETAILED_HELP_TEXT = ("""
<B>OVERVIEW</B>
Google Cloud Storage offers two APIs: an XML and a JSON API. Gsutil can
interact with both APIs. By default, gsutil versions starting with 4.0
interac... |
if __name__ == "__main__":
import sys
sys.path.append('../plugin/python/')
import unittest2 as unittest
import vdebug.dbgp
import xml.etree.ElementTree as ET
class ContextPropertyDefaultTest(unittest.TestCase):
def __get_context_property(self,xml_string):
xml = ET.fromstring(xml_string)
fir... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
__author__ = 'wufulin'
class Model(object):
products = {
'milk': {'price': 1.50, 'quantity': 10},
'eggs': {'price': 0.20, 'quantity': 100},
'cheese': {'price': 2.00, 'quantity': 10}
}
class View(object):
def product_list(self, product_li... |
from sos.plugins import Plugin, UbuntuPlugin
class Maas(Plugin, UbuntuPlugin):
""" MAAS Plugin
"""
plugin_name = 'maas'
def setup(self):
self.add_copy_specs(["/etc/squid-deb-proxy",
"/etc/maas",
"/var/lib/maas",
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Standard menu (abstract class)
Only here for gathering the widgets which are common to "standard" menus :
top buttons looking like if there was a classical pull-down menu
"""
# Import: std
import sys
# Import: PyCEGUI
import PyCEGUI
# Import: Menu... |
"""
Test automatic layout of multiple viewboxes using Grid.
"""
import sys
from vispy import scene
from vispy import app
import numpy as np
canvas = scene.SceneCanvas(keys='interactive')
canvas.size = 600, 600
canvas.show()
grid = canvas.central_widget.add_grid()
N = 10000
lines = []
for i in range(10):
lines.... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from itertools import chain
from django.utils.itercompat import is_iterable
class Tags(object):
"""
Built-in tags for internal checks.
"""
admin = 'admin'
compatibility = 'compatibility'
models = 'models'
security = 'securit... |
"""
Tests for certificate app views used by the support team.
"""
import json
from uuid import uuid4
import ddt
import six
from django.conf import settings
from django.test.utils import override_settings
from django.urls import reverse
from mock import patch
from opaque_keys.edx.keys import CourseKey
from xmodule.mo... |
from unittest import mock
import pytest
from pyspark.sql.readwriter import DataFrameReader, DataFrameWriter
from airflow.providers.apache.spark.hooks.spark_jdbc_script import (
SPARK_READ_FROM_JDBC,
SPARK_WRITE_TO_JDBC,
_create_spark_session,
_parse_arguments,
_run_spark,
spark_read_from_jdbc,... |
import report_payslip
import report_payslip_details
import report_contribution_register
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: |
#pylint: disable=dangerous-default-value
import git
import logging
import re
from unittest.mock import MagicMock
from enum import Enum
from requests.exceptions import HTTPError
from urllib.parse import urlsplit, quote
from assigner.backends.base import (
BackendBase,
RepoBase,
RepoError,
StudentRepoBa... |
from twisted.trial.unittest import TestCase
from twisted.python.failure import Failure
from scrapy.http import Request, Response
from scrapy.spiders import Spider
from scrapy.core.downloader.middleware import DownloaderMiddlewareManager
from scrapy.utils.test import get_crawler
from scrapy.utils.python import to_bytes... |
"""Test the SQL API."""
import pytest
from PyQt5.QtSql import QSqlError
from qutebrowser.misc import sql
pytestmark = pytest.mark.usefixtures('init_sql')
@pytest.mark.parametrize('klass', [sql.KnownError, sql.BugError])
def test_sqlerror(klass):
text = "Hello World"
err = klass(text)
assert str(err) ... |
from kivy.app import App
from kivy.uix.floatlayout import FloatLayout
from kivy.lang import Builder
from kivy.resources import resource_find
from kivy.clock import Clock
import timeit
Builder.load_string('''
<PerfApp>:
value: 0
but: but.__self__
slider: slider
text_input: text_input
BoxLayout:
... |
from odoo import _, api, models
from odoo.exceptions import UserError
from odoo.tools.float_utils import float_compare
class StockPicking(models.Model):
"""Adds picking split without done state."""
_inherit = "stock.picking"
@api.multi
def split_process(self):
"""Use to trigger the wizard fr... |
"""Very simple example using a pair of Lennard-Jones particles.
This script has several pieces to pay attention to:
- Importing the pieces from wepy to run a WExplore simulation.
- Definition of a distance metric for this system and process.
- Definition of the components used in the simulation: resampler,
boundary... |
from mock import patch
from pip.vcs.git import Git
from tests.test_pip import (reset_env, run_pip,
_create_test_package)
def test_get_tag_revs_should_return_tag_name_and_commit_pair():
env = reset_env()
version_pkg_path = _create_test_package(env)
env.run('git', 'tag', '0.1', c... |
# -*- coding: utf-8 -*-
"""
Django-machina
==============
Django-machina is a Django forum engine for building powerful community driven websites.
"""
from __future__ import unicode_literals
import os
__version__ = '0.6.dev'
MACHINA_VANILLA_APPS = [
'machina',
'machina.apps.forum',
'machi... |
"""
Represents an EC2 Spot Instance Datafeed Subscription
"""
from boto.ec2.ec2object import EC2Object
from boto.ec2.spotinstancerequest import SpotInstanceStateFault
class SpotDatafeedSubscription(EC2Object):
def __init__(self, connection=None, owner_id=None,
bucket=None, prefix=None, state=Non... |
#!/usr/bin/env python
__all__ = ['find_parameters']
import os, sys, traceback, getpass, time, re
from threading import Thread
from subprocess import *
if sys.version_info[0] < 3:
from Queue import Queue
else:
from queue import Queue
telnet_workers = []
ssh_workers = []
nr_local_worker = 1
class GridOption:
def _... |
"""
Nello.io lock platform.
For more details about this platform, please refer to the documentation
https://home-assistant.io/components/lock.nello/
"""
from itertools import filterfalse
import logging
import voluptuous as vol
import homeassistant.helpers.config_validation as cv
from homeassistant.components.lock im... |
'''
largely adapts: https://github.com/aymericdamien/TensorFlow-Examples/blob/master/examples/2_BasicModels/linear_regression.py
goal is to show linear dependency between number of variables in SELECT statement and execution time
'''
from __future__ import print_function
from bio_select_variables import *
import te... |
from __future__ import absolute_import, print_function, unicode_literals
from builtins import dict, str
from indra.assemblers.figaro import FigaroAssembler
from indra.statements import Concept, Event, Influence
def test_assemble_influence():
stmt = Influence(Event(Concept('rainfall')),
Event(... |
import os
import socket
import signal
import logging
class Tunnel(object):
def __init__(self):
self.outfd = None
self.errfd = None
self.pid = None
def open(self, connhost, connuser, connport, gaddr, gport, gsocket):
if self.outfd is not None:
return -1
# B... |
"""
mbed SDK
Copyright (c) 2014-2016 ARM Limited
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in wr... |
import re
from datetime import timedelta, datetime
from dj.utils import api_func_anonymous
from django.db import connection
from django.db.models import Count, Sum
from django.shortcuts import render
from .loggs import logger
import backend.dates
from backend import api_helper, model_manager, jobs
from backend.models ... |
import logging
import binascii
from vivisect.const import VASET_ADDRESS, VASET_STRING
logger = logging.getLogger(__name__)
"""Locate the basic use of known crypto constants"""
dh_group1 = binascii.unhexlify("FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74020BBEA63B139B22514A08798E3404DDEF9519B3CD3... |
import string, getopt, os, sys
#-------------------------------------------------------------------------------------------
def read_config(fname):
res = {}
buf = open(fname).readlines()
for line in buf:
workingLine = string.strip(line)
if workingLine:
if workingLine[... |
from models import Channel, Video
import re
import requests
from django.utils import timezone
from os import environ
import logging
logging.basicConfig()
channels = {
"livestream": re.compile("http://api.new.livestream.com/accounts/(\d+)"),
"youtube": re.compile("https://www.youtube.com/channel/(.*)")
}
def ... |
import calendar
from datetime import (
date,
datetime,
timedelta,
tzinfo,
)
from email.utils import (
formatdate,
mktime_tz,
parsedate_tz,
)
import time
from webob.compat import (
integer_types,
long,
native_,
text_type,
)
__all__ = [
'UTC', 'timedelta_to... |
from django.core.urlresolvers import reverse
from django.utils.translation import ugettext_lazy as _
from horizon import exceptions
from horizon import forms
from horizon import messages
from openstack_dashboard import api
class CreateKeyValuePair(forms.SelfHandlingForm):
# this if for creating a spec key-value... |
"""This script provides methods for clobbering build directories."""
import argparse
import os
import shutil
import sys
def extract_gn_build_commands(build_ninja_file):
"""Extracts from a build.ninja the commands to run GN.
The commands to run GN are the gn rule and build.ninja build step at the
top of the bu... |
import datetime
import logging
import json
from south.db import db
from south.v2 import DataMigration
from django.db import models
from desktop.lib.django_db_util import remove_content_type
from jobsub.models import JobDesign, OozieJavaAction, OozieStreamingAction, OozieDesign
LOG = logging.getLogger(__name__)
clas... |
{
'name': 'Website Mail',
'category': 'Hidden',
'summary': 'Website Module for Mail',
'version': '0.1',
'description': """Glue module holding mail improvements for website.""",
'author': 'OpenERP SA',
'depends': ['website', 'mail', 'email_template'],
'data': [
'views/snippets.xml... |
from __future__ import absolute_import
from flask import jsonify
from ..helper import bind_render
from . import bp_copyright
from ..views import (IndexView, PrefixView, ListPackagesView, ErrorHandler,
Ping, PackageVersionsView)
from .views import LicenseView, ChecksumLicenseView, SearchFileView
... |
import unittest
import tempfile
import shutil
import os
import numpy as np
from mantid.simpleapi import HB3AAdjustSampleNorm, HB3AFindPeaks, HB3AIntegratePeaks, IntegratePeaksMD, mtd
class HB3AIntegratePeaksTest(unittest.TestCase):
_files = "HB3A_exp0724_scan0182.nxs,HB3A_exp0724_scan0183.nxs"
@classmethod
... |
from django import forms
from django.contrib import admin
from .models import (
Author, BinaryTree, CapoFamiglia, Chapter, ChildModel1, ChildModel2,
Consigliere, EditablePKBook, ExtraTerrestrial, Fashionista, Holder,
Holder2, Holder3, Holder4, Inner, Inner2, Inner3, Inner4Stacked,
Inner4Tabular, NonAut... |
import datetime
from openerp.exceptions import AccessError
##############################################################################
#
# OLD API
#
##############################################################################
from openerp.osv import osv, fields
class Alpha(osv.Model):
_name = 'test_new_a... |
# coding: utf-8
from datetime import datetime
from scrapy.contrib.spiders import SitemapSpider
from scrapy.selector import Selector
from helloscrapy.items import NewsItem
class BBCSpider(SitemapSpider):
name = 'bbc'
allowed_domains = ['www.bbc.co.uk']
sitemap_urls = [
# ここにはrobots.txtのURLを指定しても... |
"""empty message
Revision ID: 748c6aef5e2b
Revises: 1c820e1886db
Create Date: 2017-09-02 13:39:02.273778
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '748c6aef5e2b'
down_revision = '1c820e1886db'
branch_labels = None
depends_on = None
def upgrade():
# ... |
"""The edit module allows you to edit a text blob without leaving the shell.
When a user needs to edit a blob of text and you don't want to save to
some location, tell them about it, and have the user re-upload the file, this
module can be used to do a quick inline edit.
It will inspect the environment variable EDITO... |
# $Id$
import inc_sip as sip
import inc_sdp as sdp
# Several PUBLISH failure scenarios that should be handled automatically
pjsua = "--null-audio --id=sip:127.0.0.1:$PORT --registrar sip:127.0.0.1:$PORT " + \
"--realm=python --user=username --password=password " + \
"--auto-update-nat=0 --publish"
#pjsua = "--null... |
from __future__ import absolute_import
from django.db import IntegrityError, transaction
from rest_framework import serializers, status
from rest_framework.response import Response
from sentry.api.base import DocSection
from sentry.api.bases.organization import OrganizationEndpoint, OrganizationPermission
from sentry... |
#Brandon Lee
#14010627X
#10/31/14
#Assignment 7
"""
countLetters() - Pseudocode
Import libraries: import os
function definition: def countLetters(fileName, fileContent):
create list with all l... |
import win32service
import win32serviceutil
import win32event
class PySvc(win32serviceutil.ServiceFramework):
# you can NET START/STOP the service by the following name
_svc_name_ = "xml_file_copy"
# this text shows up as the service name in the Service
# Control Manager (SCM)
_svc_display_name_ = ... |
"""This module includes tests of the code object representation.
>>> def f(x):
... def g(y):
... return x + y
... return g
...
>>> dump(f.func_code)
name: f
argcount: 1
names: ()
varnames: ('x', 'g')
cellvars: ('x',)
freevars: ()
nlocals: 2
flags: 3
consts: ('None', '<code object g>')
>>> dump(f(4).f... |
import discord
import random
async def poll(cmd, message, args):
if not args:
out_content = discord.Embed(type='rich', color=0xDB0000,
title='❗ Missing Arguments.')
await message.channel.send(None, embed=out_content)
return
all_qry = ' '.join(args)
... |
"""Classes and functions for building TensorFlow graphs.
## Core graph data structures
@@Graph
@@Operation
@@Tensor
## Tensor types
@@DType
@@as_dtype
## Utility functions
@@device
@@container
@@name_scope
@@control_dependencies
@@convert_to_tensor
@@convert_to_tensor_or_indexed_slices
@@convert_to_tensor_or_spar... |
"""
EditorElement is responsible for a block of field. Used by iDevice Editor
"""
import logging
from exe.webui import common
from exe.webui.element import Element
log = logging.getLogger(__name__)
# ===========================================================================
class EditorElement(Element):
"""
... |
import mock
from cassandra.cqlengine import columns
from cassandra.cqlengine.connection import NOT_SET
from cassandra.cqlengine.management import drop_table, sync_table
from cassandra.cqlengine.models import Model
from cassandra.cqlengine.query import BatchQuery, DMLQuery
from tests.integration.cqlengine.base import B... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'network'}
import re
from copy import deepcopy
from ansible.module_utils._text import to_text
from ansi... |
from pyprint.NullPrinter import NullPrinter
from coalib.misc import Constants
from coalib.output.printers.LogPrinter import LogPrinter
from pkg_resources import VersionConflict
def get_exitcode(exception, log_printer=None):
log_printer = (LogPrinter(NullPrinter()) if log_printer is None
else ... |
#!/usr/bin/env python
"""
This sample script demonstrates the use of the pre-read control (see RFC 4527).
Originally contributed by Andreas Hasenack <<EMAIL>>
Requires module pyasn1 (see http://pyasn1.sourceforge.net/)
"""
import ldap
from pyasn1.type import univ
from pyasn1.codec.der import encoder
from ldap.contro... |
import logging
from django.db.models import signals, Q
from decorators import logtime
from models import Article, Tag
log = logging.getLogger('articles.listeners')
@logtime
def apply_new_tag(sender, instance, created, using='default', **kwargs):
"""Applies new tags to existing articles that are marked for auto-... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
from gevent import monkey, spawn
monkey.patch_all() # NOQA
import logging
import os
import sys
import importlib
from oncall import utils, db
logger = logging.getLogger()
def setup_logger():
logging.getLogger('requests').setLevel(logging.WARNING)
formatter = log... |
"""
Functions that can are used to modify XBlock fragments for use in the LMS and Studio
"""
import datetime
import json
import logging
import static_replace
import uuid
import markupsafe
from django.conf import settings
from django.utils.timezone import UTC
from edxmako.shortcuts import render_to_string
from xblock.... |
import numpy as np
from pandas import DatetimeIndex, Index, date_range, factorize
import pandas._testing as tm
class TestDatetimeIndexFactorize:
def test_factorize(self):
idx1 = DatetimeIndex(
["2014-01", "2014-01", "2014-02", "2014-02", "2014-03", "2014-03"]
)
exp_arr = np.a... |
"""
Base file upload handler classes, and the built-in concrete subclasses
"""
from __future__ import unicode_literals
from io import BytesIO
from django.conf import settings
from django.core.files.uploadedfile import TemporaryUploadedFile, InMemoryUploadedFile
from django.utils.encoding import python_2_unicode_comp... |
{
'name': 'Absence Policy',
'version': '1.0',
'category': 'Generic Modules/Human Resources',
'description': """
Define Absence Policies
========================
Define properties of an absence policy, such as:
* Type (paid, unpaid)
* Rate (multiplier of base wage)
""",
'author': "Michael... |
"""Tests to determine connection quality."""
__author__ = '<EMAIL> (Thomas Stromberg)'
import time
import nameserver
import providers
import sys_nameservers
import util
EXPECTED_CONGESTION_DURATION = 40.0
CONGESTION_OFFSET_MULTIPLIER = 1
MAX_CONGESTION_MULTIPLIER = 6
class OfflineConnection(Exception):
def __i... |
import logging
from django.conf import settings
from django.core.mail import mail_admins
from celery.task import task
log = logging.getLogger('kuma.search.tasks')
@task
def prepare_index(index_pk):
"""
Prepare a new index for indexing documents into.
:arg index_pk: The `Index` ID to create an elastic... |
import unittest
import test_lib as test
import sys, os.path
sys.path.append(os.path.abspath('..'))
from sickbeard import show_name_helpers, scene_exceptions, common, name_cache
import sickbeard
from sickbeard import db
from sickbeard.databases import cache_db
from sickbeard.tv import TVShow as Show
c... |
import itertools
from math import cos, sin
from involute import CreateExternalGear, rotate
def makeGear(m, Z, angle):
w = SVGWireBuilder()
CreateExternalGear(w, m, Z, angle)
return '\n'.join(w.svg)
class SVGWireBuilder(object):
def __init__(self):
self.theta = 0.0
self.pos = None
... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import time
from ansible.plugins.strategies import StrategyBase
try:
from __main__ import display
except ImportError:
from ansible.utils.display import Display
display = Display()
class StrategyModule(StrategyBase):
... |
"""Enables rendering OpenStreetMap data in a SlippyMapper map."""
def defaultStyler(feature, graphics):
if feature['type'] == 'way':
graphics.noFill()
graphics.stroke(255, 0, 0)
return True
elif feature['type'] == 'node':
# graphics.stroke(255)
# graphics.fill(255)
... |
#!/usr/bin/python -u
#
# this tests the Expand() API of the xmlTextReader interface
# this extract the Dragon bibliography entries from the XML specification
#
import libxml2
import StringIO
import sys
# Memory debug specific
libxml2.debugMemory(1)
expect="""<bibl id="Aho" key="Aho/Ullman">Aho, Alfred V.,
Ravi Sethi... |
"""
roslib is largely deprecated starting in the ROS Fuerte release.
roslib has a very important role in all Python code written for ROS:
it contains the L{load_manifest()} method, which updates the
PYTHONPATH based on a set of ROS Package manifest.xml files.
Beyond the important load_manifest() call, most of the res... |
# -*- coding: utf-8 -*-
r"""
Navier-Stokes equations for incompressible fluid flow in 2D.
Find :math:`\ul{u}`, :math:`p` such that:
.. math::
\int_{\Omega} \nu\ \nabla \ul{v} : \nabla \ul{u}
+ \int_{\Omega} ((\ul{u} \cdot \nabla) \ul{u}) \cdot \ul{v}
- \int_{\Omega} p\ \nabla \cdot \ul{v}
= 0
\;, ... |
try:
from thread import get_ident as _get_ident
except ImportError:
try:
from dummy_thread import get_ident as _get_ident
except ImportError:
from _dummy_thread import get_ident as _get_ident
try:
from _abcoll import KeysView, ValuesView, ItemsView
except ImportError:
pass
class O... |
"""
Copyright (c) 2012-2013 RockStor, Inc. <http://rockstor.com>
This file is part of RockStor.
RockStor is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published
by the Free Software Foundation; either version 2 of the License,
or (at your option) any la... |
'''
// Copyright (c) 2014 Anonymized. All rights reserved.
//
// Code submitted as supplementary material for manuscript:
// "Dependency Recurrent Neural Language Models for Sentence Completion"
// Do not redistribute.
Created on Aug 4, 2014
Take a corpus the JSON format obtained from Stanford and convert it to this... |
import sys
import time
from django.db.backends.creation import BaseDatabaseCreation
TEST_DATABASE_PREFIX = 'test_'
PASSWORD = 'Im_a_lumberjack'
class DatabaseCreation(BaseDatabaseCreation):
# This dictionary maps Field objects to their associated Oracle column
# types, as strings. Column-type strings can cont... |
"""Top-level presubmit script for linux.
See http://dev.chromium.org/developers/how-tos/depottools/presubmit-scripts
for more details on the presubmit API built into depot_tools.
"""
def CommonChecks(input_api, output_api):
import sys
def join(*args):
return input_api.os_path.join(input_api.PresubmitLocalPat... |
from __future__ import unicode_literals
from django.http import Http404
from django.shortcuts import get_list_or_404, get_object_or_404
from django.test import TestCase
from .models import Article, Author
class GetObjectOr404Tests(TestCase):
def test_get_object_or_404(self):
a1 = Author.objects.create(n... |
import workitem
from openerp.workflow.helpers import Session
from openerp.workflow.helpers import Record
from openerp.workflow.workitem import WorkflowItem
class WorkflowInstance(object):
def __init__(self, session, record, values):
assert isinstance(session, Session)
assert isinstance(record, Reco... |
""" monkeypatching and mocking functionality. """
import os, sys
from py.builtin import _basestring
def pytest_funcarg__monkeypatch(request):
"""The returned ``monkeypatch`` funcarg provides these
helper methods to modify objects, dictionaries or os.environ::
monkeypatch.setattr(obj, name, value, ra... |
"""Contains metaclasses used to create protocol service and service stub
classes from ServiceDescriptor objects at runtime.
The GeneratedServiceType and GeneratedServiceStubType metaclasses are used to
inject all useful functionality into the classes output by the protocol
compiler at compile-time.
"""
__auth... |
#################################################################
# Program: Toolib
"""
"""
__author__ = "Oleg Noga"
__date__ = "$Date: 2008/05/19 16:36:00 $"
__version__ = "$Revision: 1.21 $"
# $Source: D:/HOME/cvs/toolib/wx/tree/Tree.py,v $
#
#################################################################
import... |
"""
This file is part of HexACO.
HexACO is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
HexACO is distributed in t... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.