code stringlengths 1 199k |
|---|
from django.conf import settings
LAST_FEEDS_COUNT = getattr(settings, 'LAST_FEEDS_COUNT', 10) |
'''
Mixins for using Mappers with Publisher
'''
from django.core.exceptions import ValidationError
from nap import http
from nap.utils import flatten_errors
class MapperListMixin(object):
def list_get_default(self, request, action, object_id):
'''
Replace the default list handler with one that retur... |
import sys
import os
try:
import sphinx_rtd_theme
has_rtd = True
except ImportError:
has_rtd = False
sys.path.insert(0, os.path.abspath('../'))
extensions = [
'sphinx.ext.autodoc',
'sphinx.ext.todo',
'sphinx.ext.coverage',
'sphinx.ext.viewcode',
]
templates_path = ['_templates']
source_suffi... |
class Kernel(object):
def apply(self, **kwargs):
raise NotImplementedError("Not implemented")
class QuadraticKernel(Kernel):
def apply(self, X, Y, x):
ret = np.dot(X.T, x)
ret += 1
ret = np.power(ret, 2)
d, T = x.shape
ret = np.multiply(ret, np.repeat(Y[:, np.newa... |
import contextlib
import copy
import os.path as op
from types import GeneratorType
import numpy as np
from .baseline import rescale
from .cov import Covariance
from .evoked import _get_peak
from .filter import resample
from .io.constants import FIFF
from .surface import (read_surface, _get_ico_surface, mesh_edges,
... |
"""Testing the pipeline on simulated histories""" |
import os
import shutil
import unittest
import tempfile
from bento._config \
import \
IPKG_PATH
from bento.core.node \
import \
create_root_with_source_tree
from bento.core.package \
import \
PackageDescription
from bento.core \
import \
PackageMetadata
from bento.core.pk... |
"""
jinja2.testsuite.filters
~~~~~~~~~~~~~~~~~~~~~~~~
Tests for the jinja filters.
:copyright: (c) 2010 by the Jinja Team.
:license: BSD, see LICENSE for more details.
"""
import pytest
from jinja2 import Markup, Environment
from jinja2._compat import text_type, implements_to_string
@pytest.mark.fil... |
from os.path import join, basename
from functools import partial
from json import dumps
from future.utils import viewitems
from moi import r_client
from qiita_core.util import execute_as_transaction
from qiita_core.qiita_settings import qiita_config
from qiita_pet.handlers.api_proxy.util import check_access, check_fp
f... |
from actions.action import BaseAction
from models.email import EmailReport, VALID_STATUSES
class ClassifyReportAction(BaseAction):
action_id = 'classify_report'
name = "Classify Report"
description = "Classifies a report automatically"
options = {
"classification": {
"name": "Classif... |
from .check_digit_number import CheckDigitNumber
class LuhnNumber (CheckDigitNumber):
def generate_from_int (self, n):
total = 0
while n > 0:
total += self.__add_two_digits(n % 100)
n //= 100
return (9 * total) % 10
def __add_two_digits (self, n):
return (... |
default_app_config = 'mymoney.apps.banktransactions.apps.BankTransactionConfig' |
"""
attribute/__init__.py
Created by Thomas Mangin on 2009-11-05.
Copyright (c) 2009-2015 Exa Networks. All rights reserved.
"""
import collections
from struct import unpack
from exabgp.util.od import od
from exabgp.configuration.environment import environment
from exabgp.bgp.message.update.attribute.attribute import A... |
""" This module is used to build a "Package", a collection of files
within a Panda3D Multifile, which can be easily be downloaded and/or
patched onto a client machine, for the purpose of running a large
application. """
__all__ = ["Packager", "PackagerError", "OutsideOfPackageError", "ArgumentError"]
from panda3d.core ... |
from __future__ import unicode_literals, print_function
import pytest
from oar.lib import db
from oar.kao.job import insert_job
from oar.kao.kao import main
import oar.lib.tools # for monkeypatching
@pytest.yield_fixture(scope='function', autouse=True)
def minimal_db_initialization(request):
with db.session(epheme... |
from __future__ import absolute_import, unicode_literals
from django.apps import apps
from celery.utils.log import get_task_logger
from djcelery_transactions import task
from tracpro.orgs_ext.tasks import OrgTask
from tracpro.contacts.utils import sync_push_contact
logger = get_task_logger(__name__)
@task
def push_cont... |
from django.conf import settings
from django.test import override_settings, SimpleTestCase
from django.utils.six.moves.urllib.parse import urljoin
from .utils import render, setup
@override_settings(MEDIA_URL="/media/", STATIC_URL="/static/")
class StaticTagTests(SimpleTestCase):
@setup({'static-prefixtag01': '{% l... |
import re
import six
from .compat \
import \
OrderedDict
from .errors \
import \
DepSolverError, InvalidVersion
from .constraints \
import \
Any, Equal, GEQ, GT, LEQ, LT, Not
from .version \
import \
_LOOSE_VERSION_RE
_DEFAULT_SCANNER = re.Scanner([
(r"[a-zA-Z_]\w*", ... |
from distutils.core import setup
from setuptools import find_packages
setup(
name = 'admin_bootstrap',
version = '0.7.0',
description = 'Django admin templates that are compatible with Twitter Bootstrap version 2.1.0',
author = 'Dan... |
r"""
.. dialect:: mssql+pyodbc
:name: PyODBC
:dbapi: pyodbc
:connectstring: mssql+pyodbc://<username>:<password>@<dsnname>
:url: http://pypi.python.org/pypi/pyodbc/
Connecting to PyODBC
--------------------
The URL here is to be translated to PyODBC connection strings, as
detailed in `ConnectionStrings ... |
"""
sentry.models.accessgroup
~~~~~~~~~~~~~~~~~~~~~~~~~
:copyright: (c) 2010-2013 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
from django.conf import settings
from django.db import models
from django.utils import timezone
from sentry.constants import MEMBER_TYPES, ... |
import pyaf.Bench.TS_datasets as tsds
import tests.artificial.process_artificial_dataset as art
art.process_dataset(N = 1024 , FREQ = 'D', seed = 0, trendtype = "Lag1Trend", cycle_length = 12, transform = "Integration", sigma = 0.0, exog_count = 0, ar_order = 0); |
from django.db.models.fields import related
from django.utils.functional import cached_property
from ..utils import override_attr
def create_many_related_manager(superclass, rel):
opts = rel.through._meta
class ManyRelatedManager(superclass):
def add(self, *objs):
with override_attr(opts, 'a... |
from __future__ import print_function
from builtins import input
import matplotlib
matplotlib.use("TkAgg")
import pylab, numpy
pylab.ion() # makes plot interactive
fig=pylab.figure() # makes a figure instance
ax=fig.add_subplot(111) # Axes instance
t=numpy.arange(0,1,.01)
s=numpy.sin(2*numpy.pi*t)
c=numpy.cos(2*numpy.p... |
from matplotlib import use
use('Agg')
import matplotlib.pyplot as plot
import numpy as np
plot.rcParams.update({'font.size': 16.1})
def plot_data(img_name, file_name, xlabel, yRange = None):
figure = plot.figure()
axis = figure.add_subplot(1, 1, 1)
A = []
B = []
C = []
E = []
F = []
N = [""]
file = op... |
import pylab
import sys, os
from math import *
import matplotlib
COLORS = 'rbgcmyk'
MARKERS = 'oxvs+D1'
LINES = ['-', '--', '-.', ':']
"""Args: (defaults at end of each line)
bg: background color - 'white'
figsize: figure size - (10,10)
plotstrs: array of plot strings - ['%s-o' % c for c in COLORS][:ndi... |
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
from django.core.files.storage import default_storage
import pickle
try:
from hashlib import md5 as md5_constructor
except ImportError:
from django.utils.hashcompat import md5_constructor
class Migration(Sc... |
import binascii
import copy
import datetime
import re
from django.db.backends.base.schema import BaseDatabaseSchemaEditor
from django.db.utils import DatabaseError
from django.utils.text import force_text
class DatabaseSchemaEditor(BaseDatabaseSchemaEditor):
sql_create_column = "ALTER TABLE %(table)s ADD %(column)s... |
try:
import numpy
import scipy
except ImportError:
raise ImportError("py-sdm requires numpy and scipy to be installed")
# Don't do this in the setup() requirements, because otherwise pip and
# friends get too eager about updating numpy/scipy.
try:
from setuptools import setup
except ImportError:... |
"""Command Line Interface to opyd objects"""
from __future__ import print_function
import time
import functools
import sys
from contextlib import contextmanager, closing
from StringIO import StringIO
import collections
from IPython.utils.coloransi import TermColors as tc
from epics import caget, caput
from ..controls.p... |
from setuptools import setup, find_packages
from codecs import open
from os import path
__version__ = '0.0.4'
here = path.abspath(path.dirname(__file__))
with open(path.join(here, 'README.md'), encoding='utf-8') as f:
long_description = f.read()
with open(path.join(here, 'requirements.txt'), encoding='utf-8') as f:... |
import sys
from weakref import WeakKeyDictionary
from atom.api import Typed
from enaml.widgets.notebook import ProxyNotebook
from .QtCore import Qt, QEvent, Signal
from .QtGui import QTabWidget, QTabBar, QResizeEvent, QApplication
from .qt_constraints_widget import QtConstraintsWidget
from .qt_page import QtPage
TAB_PO... |
import stix
import stix.utils
import stix.bindings.stix_common as common_binding
class KillChain(stix.Entity):
_binding = common_binding
_namespace = 'http://stix.mitre.org/common-1'
_binding_class = _binding.KillChainType
def __init__(self, id_=None, name=None):
self.id_ = id_
self.name... |
from __future__ import absolute_import
from hs_core.models import *
from resource_aggregation.models import *
from ga_resources.utils import json_or_jsonp
from django.contrib.auth.decorators import login_required
from django.shortcuts import render
from django.contrib.auth.models import User, Group
from django.utils.ti... |
import os
import sys
import subprocess
from setuptools import setup, Extension
from setuptools.command.build_ext import build_ext
__version__ = '0.3.6'
PLAT_TO_CMAKE = {
"win32": "Win32",
"win-amd64": "x64",
"win-arm32": "ARM",
"win-arm64": "ARM64",
}
class CMakeExtension(Extension):
def __init__(se... |
from jinja2 import Markup
class momentjs(object):
def __init__(self, timestamp):
self.timestamp = timestamp
def render(self, format):
return Markup("<script>\ndocument.write(moment(\"%s\").%s);\n</script>" % (self.timestamp.strftime("%Y-%m-%dT%H:%M:%S Z"), format))
def format(self, fmt):
... |
"""Writes a build_config file.
The build_config file for a target is a json file containing information about
how to build that target based on the target's dependencies. This includes
things like: the javac classpath, the list of android resources dependencies,
etc. It also includes the information needed to create th... |
"""
=====================================
Time-frequency beamforming using LCMV
=====================================
Compute LCMV source power [1]_ in a grid of time-frequency windows and
display results.
References
----------
.. [1] Dalal et al. Five-dimensional neuroimaging: Localization of the
time-frequency... |
from data_importers.management.commands import BaseXpressDemocracyClubCsvImporter
class Command(BaseXpressDemocracyClubCsvImporter):
council_id = "WYO"
addresses_name = "2021-03-18T18:04:57.973413/Bucks_dedupe.tsv"
stations_name = "2021-03-18T18:04:57.973413/Bucks_dedupe.tsv"
elections = ["2021-05-06"]
... |
"""An elsapy module that contains decorators and other utilities to make the
project more maintainable.
"""
import pandas as pd
from . import log_util
logger = log_util.get_logger(__name__)
def recast_df(df):
'''Recasts a data frame so that it has proper date fields and a more
useful data structure for URLs'''
... |
from django.conf.urls import re_path
from . import views
urlpatterns = (
re_path(r'^$', views.registration, name="registration"),
re_path(r'^contact/add/$', views.contact, name="registration_contact_add"),
re_path(r'^contact/bulk_add/$', views.contact_bulk_add, name="registration_bulk_add"),
re_path(r'^... |
from __future__ import division
from menpo.transform import AlignmentSimilarity
from menpo.model.pdm import PDM, OrthoPDM
from menpo.fit.gradientdescent import RegularizedLandmarkMeanShift
from menpo.fit.gradientdescent.residual import SSD
from menpo.fitmultilevel.base import MultilevelFitter
from menpo.fitmultilevel.f... |
from django.db import models
from django.db.models.loading import get_model
from django.contrib.contenttypes.models import ContentType
from polymorphic import PolymorphicModel
from entropy.mixins import (
TextMixin, EnabledMixin, SlugMixin, TitleMixin
)
from attrs.mixins import GenericAttrMixin
from templates.mixin... |
import os
import re
import requests
import socket
import urllib2
from collections import defaultdict, Counter, deque
from checks import AgentCheck
from config import _is_affirmative
from utils.dockerutil import DockerUtil, MountException
from utils.kubeutil import KubeUtil
from utils.platform import Platform
from utils... |
"""
Define common options used in describing objects.
"""
import cx_OptionParser
import os
ARRAY_SIZE = cx_OptionParser.Option("--array-size", type = "int",
metavar = "N", help = "array size is <n> rows")
AS_OF_SCN = cx_OptionParser.Option("--as-of-scn", type="int", metavar = "SCN",
help = "system chang... |
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 'Target'
db.create_table('uniapply_target', (
('id', self.gf('django.db.models.fields.AutoField')(primary_ke... |
from urllib.request import urlopen
from rdflib import Graph, Literal
from rdflib.namespace import DC, RDF
from util import str2id
from ns import ns_division, ns_property, ns_type
def main():
graph = Graph()
URL = 'http://www.electionsquebec.qc.ca/documents/donnees-ouvertes/Liste_circonscriptions.txt'
with u... |
def extractJiamintranslationCom(item):
'''
Parser for 'jiamintranslation.com'
'''
if 'Calligraphy' in item['tags']:
return None
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not (chp or vol) or "preview" in item['title'].lower():
return None
tagmap = [
('HAWRR', 'Quick ... |
from django.http import JsonResponse, HttpResponseBadRequest
from django.utils.translation import gettext_lazy as _
from django.core.exceptions import ObjectDoesNotExist
from django.contrib.auth.models import User
from django.contrib.sites.shortcuts import get_current_site
from django.utils.functional import SimpleLazy... |
from kitsune.messages.utils import unread_count_for
def unread_message_count(request):
"""Adds the unread private messages count to the context.
* Returns 0 for anonymous users.
* Returns 0 if waffle flag is off.
"""
count = 0
if hasattr(request, "user") and request.user.is_authenticated:
... |
import sys, os
extensions = []
templates_path = ['_templates']
source_suffix = '.rst'
master_doc = 'index'
project = u'compo'
copyright = u'2014, Matthew Levandowski'
version = '0.1'
release = '0.1'
exclude_patterns = ['_build']
pygments_style = 'sphinx'
html_theme = 'default'
html_static_path = ['_static']
htmlhelp_ba... |
""" Python library for interacting with the Influence Explorer Text API.
"""
__author__ = "Dan Drinkard <ddrinkard@sunlightfoundation.com"
__version__ = "0.1.0"
__copyright__ = "Copyright (c) 2011 Sunlight Labs"
__license__ = "BSD"
import urllib, urllib2
try:
import json
except ImportError:
import simplejson as... |
"""Views for the admin_tools_zinnia demo"""
from django.conf import settings
from django.template import loader
from django.template import Context
from django.http import HttpResponseServerError
def server_error(request, template_name='500.html'):
"""
500 error handler.
Templates: `500.html`
Context:
... |
import tests.model_control.test_ozone_custom_models_enabled as testmod
testmod.build_model( ['Anscombe'] , ['LinearTrend'] , ['Seasonal_Second'] , ['MLP'] ); |
from argparse import ArgumentParser
from os import mkdir
from os.path import isfile, exists, join as pjoin
from numpy import array, delete
from biom.util import biom_open
from biom.parse import parse_biom_table
from americangut.generate_otu_signifigance_tables import (
calculate_abundance, calculate_tax_rank_1, con... |
import builders
import unittest
class BuildersTest(unittest.TestCase):
def test_path_from_name(self):
tests = {
'test': 'test',
'Mac 10.6 (dbg)(1)': 'Mac_10_6__dbg__1_',
'(.) ': '____',
}
for name, expected in tests.items():
self.assertEqual(ex... |
import numpy as np
from pandas import DataFrame
import pandas._testing as tm
def test_head_tail(float_frame):
tm.assert_frame_equal(float_frame.head(), float_frame[:5])
tm.assert_frame_equal(float_frame.tail(), float_frame[-5:])
tm.assert_frame_equal(float_frame.head(0), float_frame[0:0])
tm.assert_fram... |
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "eukalypse_now.settings")
#standalone hack
#sys.path.append(os.path.join(os.path.dirname(__file__), os.pardir))
from django.core.management import execute_from_command_line
execute_from_command_line(sys.a... |
from __future__ import division
import os
import time
import sys
import argparse
import numpy as np
import tables
from astropy.table import Table
import logging
import warnings
from Chandra.Time import DateTime
import agasc
from kadi import events
from Ska.engarchive import fetch, fetch_sci
import mica.archive.obspar
f... |
from setuptools import setup
from sudoku import __author__
from sudoku import __email__
from sudoku import __program__
from sudoku import __url__
from sudoku import __version__
setup(
author=__author__,
author_email=__email__,
dependency_links=[],
install_requires=[],
name=__program__,
packages=... |
"""
This class draws a relation icon.
"""
from datafinder.gui.admin.datamodel_iconview.prototype_icon import PrototypeIcon
from datafinder.gui.admin.datamodel_iconview.partial_relation_icon import PartialRelationIcon
__version__ = "$Revision-Id:$"
class RelationIcon(PrototypeIcon):
"""
Relation icon to be shown... |
import os
from setuptools import setup
files = ["pyprocess/*"]
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name = "pyprocess",
version = "0.0.4",
author = "Daniel Mondaca",
author_email = "dnielm@gmail.com",
description = ("process name managment.")... |
"""Mock single-user server for testing
basic HTTP Server that echos URLs back,
and allow retrieval of sys.argv.
Handlers and their purpose include:
- EchoHandler: echoing URLs back
- ArgsHandler: allowing retrieval of `sys.argv`
- ArgsHandler: allowing retrieval of `os.environ`
Copied from JupyterHub test suite.
"""
im... |
import hassapi as hass
class MiniMote(hass.Hass):
def initialize(self):
self.listen_event(self.zwave_event, "zwave.scene_activated", entity_id=self.args["device"])
def zwave_event(self, event_name, data, kwargs):
# self.verbose_log("Event: {}, data = {}, args = {}".format(event_name, data, kwarg... |
from collections import namedtuple
class SingleTestPath(namedtuple("TestPath", "root relfile func sub")):
"""Where to find a single test."""
def __new__(cls, root, relfile, func, sub=None):
self = super(SingleTestPath, cls).__new__(
cls,
str(root) if root else None,
s... |
from worldengine.simulations.basic import find_threshold_f
from noise import snoise2 # http://nullege.com/codes/search/noise.snoise2
import numpy
class TemperatureSimulation(object):
@staticmethod
def is_applicable(world):
return not world.has_temperature()
def execute(self, world, seed):
e... |
from sfa.util.xrn import Xrn
from sfa.util.method import Method
from sfa.trust.credential import Credential
from sfa.storage.parameter import Parameter, Mixed
class Remove(Method):
"""
Remove an object from the registry. If the object represents a PLC object,
then the PLC records will also be removed.
@... |
from django.apps import AppConfig
class ProposalsConfig(AppConfig):
name = "pyconcz_2017.proposals"
verbose_name = "Conference Proposals"
def ready(self):
# Register proposal forms
from pyconcz_2017.proposals.config import proposals
from pyconcz_2017.proposals.pyconcz2016_config impo... |
from datetime import datetime
import inspect
import requests
import sys
from threading import Thread
import time
import traceback
import csv
from decimal import Decimal
from bitcoin import COIN
from i18n import _
from util import PrintError, ThreadJob
from util import format_satoshis
CCY_PRECISIONS = {'BHD': 3, 'BIF': ... |
import re
import string
from faker.utils.distribution import choices_distribution, choices_distribution_unique
_re_hash = re.compile(r'#')
_re_perc = re.compile(r'%')
_re_excl = re.compile(r'!')
_re_at = re.compile(r'@')
_re_qm = re.compile(r'\?')
_re_cir = re.compile(r'\^')
class BaseProvider(object):
__provider__... |
import subprocess
import os
import sys
if len(sys.argv) < 4:
print '\nUsage: aws_ebs_create_IOPS [size in GB] [IOPS] [zone] "Description in double quotes" [snapshot ID]\n'
print '\nSpecify size of EBS volume to be created (in GB) with IOPS. Be careful! Cost structure is different than gp2 EBS volumes. Along with avai... |
import sys
try:
import cPickle as pickle
except ImportError:
import pickle as pickle
import codecs
import six
class CMapConverter(object):
def __init__(self, enc2codec={}):
self.enc2codec = enc2codec
self.code2cid = {} # {'cmapname': ...}
self.is_vertical = {}
self.cid2unichr... |
def main(inputVCFFile,crossType,inputParent1Loc = '',inputParent2Loc = ''):
import os.path
#check that file exits
if os.path.isfile(inputVCFFile) == False:
print('Specified File does not exist: ' + inputVCFFile)
return
#check that the crossType is valid
if not(crossType == 'f2 backcross' or crossType ... |
import _plotly_utils.basevalidators
class TitleValidator(_plotly_utils.basevalidators.TitleValidator):
def __init__(
self, plotly_name="title", parent_name="layout.polar.radialaxis", **kwargs
):
super(TitleValidator, self).__init__(
plotly_name=plotly_name,
parent_name=pa... |
import hashlib
from rhc.database.dao import DAO
class nullcipher(object):
def encrypt(self, v):
return v
def decrypt(self, v):
return v
CRYPT = nullcipher()
class DAOE(DAO):
ENCRYPT_FIELDS = ()
@staticmethod
def makesha(value):
return hashlib.sha256(value).digest()
def on... |
"""
Written by Daniel M. Aukes and CONTRIBUTORS
Email: danaukes<at>asu.edu.
Please see LICENSE for full license.
"""
import popupcad
import shapely.geometry
import numpy
import qt.QtCore as qc
import qt.QtGui as qg
import numpy.linalg
try: #Hack to ensure Python 2 & 3 support
import itertools.izip as zip
except Imp... |
import settings
import helpers
import sys
import os
import glob
import random
import pandas
import ntpath
import cv2
import numpy
from typing import List, Tuple
from keras.optimizers import Adam, SGD
from keras.layers import Input, Convolution2D, MaxPooling2D, UpSampling2D, merge, Convolution3D, MaxPooling3D, UpSamplin... |
import click
import logging
import boto.dynamodb2
from flotilla.cli.options import *
from flotilla.db import DynamoDbTables
from flotilla.client import FlotillaClientDynamo
logger = logging.getLogger('flotilla')
@click.group()
def user_cmd(): # pragma: no cover
pass
@user_cmd.command(help='Configure a user.')
@cli... |
from swgpy.object import *
def create(kernel):
result = Creature()
result.template = "object/creature/npc/base/shared_zabrak_base_female.iff"
result.attribute_template_id = 9
result.stfName("npc_name","zabrak_base_female")
#### BEGIN MODIFICATIONS ####
#### END MODIFICATIONS ####
return result |
import direct.directbase.DirectStart
from World import World
self.world = World()
run() |
import unittest
import os
from test.aiml_tests.client import TestClient
from programy.config.brain import BrainFileConfiguration
class SurveyTestsClient(TestClient):
def __init__(self):
TestClient.__init__(self, debug=True)
def load_configuration(self, arguments):
super(SurveyTestsClient, self).... |
from .copy_source import CopySource
class PhoenixSource(CopySource):
"""A copy activity Phoenix server source.
:param additional_properties: Unmatched properties from the message are
deserialized this collection
:type additional_properties: dict[str, object]
:param source_retry_count: Source retry ... |
import requests
from django.utils import timezone
from django.core.urlresolvers import reverse
from django.test import TestCase
from django.contrib.auth.models import User
from django.test.client import Client
from cabotapp.models import (
GraphiteStatusCheck, JenkinsStatusCheck,
HttpStatusCheck, Service, Statu... |
with open('hello.txt') as f:
data = f.read()
print(data)
f.closed |
"""
Copyright (c) 2009, Stefan van der Walt <stefan@sun.ac.za>
This module was originally based on code from
http://swiftcoder.wordpress.com/2008/12/19/simple-glsl-wrapper-for-pyglet/
which is
Copyright (c) 2008, Tristam MacDonald
Permission is hereby granted, free of charge, to any person or organization
obtaining a c... |
from pyramid.interfaces import PHASE2_CONFIG
from contentbase import LOCATION_ROOT
from contentbase.upgrader import default_upgrade_finalizer
LATE = 10
def includeme(config):
config.scan()
def callback():
""" add_upgrade for all item types
"""
migrator = config.registry['migrator']
... |
import wave, sunau, sndhdr
from audioop import tomono, lin2lin, ratecv
import struct
if struct.pack("h", 1) == "\000\001":
big_endian = 1
else:
big_endian = 0
class BaseReader:
_cvt = lambda s, x: x
_freqCvt = { 8000: 160, 16000: 320, 32000: 640, 64000: 1280 }
def __init__(self, fp):
self.fp... |
from distutils.core import setup
from setuptools import find_packages
options = {'apk': {'debug': None,
'requirements': 'python2,flask,pyjnius',
'android-api': 19,
'ndk-dir': '/home/asandy/android/crystax-ndk-10.3.2',
'dist-name': 'testapp_flas... |
from io import StringIO
import pytest
from doit.exceptions import InvalidCommand
from doit.dependency import DbmDB, Dependency
from doit.cmd_ignore import Ignore
from .conftest import tasks_sample, CmdFactory
class TestCmdIgnore(object):
@pytest.fixture
def tasks(self, request):
return tasks_sample()
... |
import pandas as pd
import numpy as np
import utilities as ut
import transform_records as tr
import time as tm
rawData = pd.read_csv('../../BANES_Historic_Car_Park_Occupancy.csv')
rawData.head(10)
t = tm.time()
OccupancyDF = tr.refine(rawData, 1.1)
elapsed = tm.time() - t
OccupancyDF['Date'] = OccupancyDF['LastUpdate']... |
import re
import numpy as np
def parse_phonopy_conf(filename):
with open(filename, "r") as f:
return _parse_phonopy_conf_strings(f.readlines())
def _parse_phonopy_conf_strings(lines):
lines = _remove_comments(lines)
lines = _parse_continuation_lines(lines)
d = _create_dictionary(lines)
retur... |
from swgpy.object import *
def create(kernel):
result = Creature()
result.template = "object/mobile/shared_space_comm_rebel_transport_06.iff"
result.attribute_template_id = 9
result.stfName("npc_name","zabrak_base_female")
#### BEGIN MODIFICATIONS ####
#### END MODIFICATIONS ####
return result |
# Copyright (c) 2015 Tencent Inc.
# Distributed under the MIT license
# (See accompanying file LICENSE or copy at http://opensource.org/licenses/MIT)
#
# Project: Cloud Image Migration Tool
# Filename: civ2_uploader.py
# Version: 2.0
# Author: Jamis Hoo
# E-mail: hoojamis@gmail.com
# Date: Sep 7, 20... |
import unittest
import hail as hl
from .helpers import startTestHailContext, stopTestHailContext, skip_unless_spark_backend, fails_local_backend
setUpModule = startTestHailContext
tearDownModule = stopTestHailContext
class Tests(unittest.TestCase):
@skip_unless_spark_backend()
def test_init_hail_context_twice(s... |
default_app_config = "account.apps.AccountConfig" |
from PyQt5.QtCore import Qt
from PyQt5 import QtCore, QtGui, QtWidgets
"""from PyQt4.QtCore import QRegExp, Qt
from PyQt4.QtGui import QGridLayout, QDialog, QCheckBox, QPushButton, QLabel, QTextDocument, QLineEdit
"""
import re
class FindReplaceDialog(QtWidgets.QDialog):
def __init__(self, parent = None):
super(F... |
from PySide.QtGui import *
import sys
from MBase import *
animation_thread = MAnimationThread()
value_animator = MValueAnimator(0, 100, 10000, 60)
class Demo:
def __init__(self, va):
self.frame = 1
self.va = va
def run_on_thread(self):
try:
print("Frame", self.frame, self.va.... |
from swgpy.object import *
def create(kernel):
result = Creature()
result.template = "object/mobile/shared_dressed_ewok_m_11.iff"
result.attribute_template_id = 9
result.stfName("npc_name","ewok_base_male")
#### BEGIN MODIFICATIONS ####
#### END MODIFICATIONS ####
return result |
import time
import logging
import threading
from datetime import timedelta
from rx import config
from rx.core import Scheduler
from rx.internal import PriorityQueue
from .schedulerbase import SchedulerBase
from .scheduleditem import ScheduledItem
log = logging.getLogger('Rx')
class Trampoline(object):
@classmethod
... |
RUN = 'nothing' |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.