content stringlengths 4 20k |
|---|
from __future__ import absolute_import
import re
xpath_tokenizer_re = re.compile(
"("
"'[^']*'|\"[^\"]*\"|"
"::|"
"//?|"
r"\.\.|"
r"\(\)|"
r"[/.*:\[\]\(\)@=])|"
r"((?:\{[^}]+\})?[^/\[\]\(\)@=\s]+)|"
r"\s+"
)
def xpath_tokenizer(pattern, namespaces=None):
default_namespace ... |
import requests
from allauth.socialaccount import app_settings
from allauth.socialaccount.providers.oauth2.views import (
OAuth2Adapter,
OAuth2CallbackView,
OAuth2LoginView,
)
from .provider import PinterestProvider
class PinterestOAuth2Adapter(OAuth2Adapter):
provider_id = PinterestProvider.id
... |
'''
Main calls the Looper once to loop on all rchk and then another looper to loop on all schk
Looper loops on all the files.
For each file it will create a TableList.
For each line in the file it will call the RuleParser
RuleParser will return an object including the SQL that needs to run to validate the rule
TableLis... |
""" Metrics for stories in Story Board (and others using this table) """
import logging
import MySQLdb
from vizgrimoire.metrics.metrics import Metrics
from vizgrimoire.metrics.metrics_filter import MetricFilters
from vizgrimoire.metrics.query_builder import ITSQuery
from vizgrimoire.ITS import ITS
from sets impor... |
'''dictmerge - merge dictionaries'''
# [ Imports ]
# [ -Python- ]
# [ -Project- ]
# [ Exceptions ]
class KeyConflictError(KeyError):
'''for use when two dictionaries have the same key, but not the same value'''
pass
# [ Helpers ]
def default_resolver(key, value_1, value_2):
'''
Return a merged dic... |
import numpy as np
from ase.calculators.emt import EMT
from ase import Atoms
a = 3.60
b = a / 2
cu = Atoms('Cu',
positions=[(0, 0, 0)],
cell=[(0, b, b),
(b, 0, b),
(b, b, 0)],
pbc=1,
calculator=EMT())
e0 = cu.get_potential_energy()
print e0
... |
# simple Rational number class
# assumes both gcd and lcm are already imported
# import sys
#sys.path.append( "/home/mark/Dropbox-Work/Projects-Geany/" )
#from frac import gcd, lcm
def gcd(a, b):
# Ensure that a > b, if it is not reverse a & b
if not a > b:
a, b = b, a
print("Initial fraction is... |
from App.Proxys import *
data = IKVMCController(
name = '',
controlParamsList = [
ControlParams( joint = 'root', kp = 1000.0, kd = 200.0, tauMax = 200.0, scale = ( 1.0, 1.0, 1.0 ) ),
ControlParams( joint = 'pelvis_lowerback', kp = 75.0, kd = 17.0, tauMax = 100.0, scale = ( 1.0, 1.0,... |
# -*- coding:ascii -*-
from mako import runtime, filters, cache
UNDEFINED = runtime.UNDEFINED
__M_dict_builtin = dict
__M_locals_builtin = locals
_magic_number = 9
_modified_time = 1396977096.969555
_enable_loop = True
_template_filename = 'C:\\app\\catalog\\templates/base.htm'
_template_uri = 'base.htm'
_source_encodi... |
from weboob.tools.browser import BasePage
from weboob.tools.misc import html2text
from weboob.tools.capabilities.thumbnail import Thumbnail
from datetime import datetime
import re
from .gallery import EHentaiGallery
__all__ = ['GalleryPage', 'ImagePage', 'IndexPage', 'HomePage', 'LoginPage']
class LoginPage(BasePag... |
#!/usr/bin/python
# package battingPackage
import os
import sys
var = os.path.abspath(os.path.dirname(__file__)+'../..')
sys.path.append(var)
from teamPackage import Pitcher
from teamPackage import Player
from random import randint
class Batting(object):
chanceOfBall = 0
chanceOfStrike = 0
chanceOfHit =... |
"""
This is the common settings file, intended to set sane defaults. If you have a
piece of configuration that's dependent on a set of feature flags being set,
then create a function that returns the calculated value based on the value of
MITX_FEATURES[...]. Modules that extend this one can change the feature
configura... |
'''
modified by Chongxuan Li (<EMAIL>)
'''
import numpy as np
import anglepy
import anglepy.ndict as ndict
from anglepy.models import GPUVAE_YZ_X
import sys, os
import color
import scipy.io as sio
def labelToMat(y):
label = np.unique(y)
newy = np.zeros((len(y), len(label)))
for i in range(len(y)):
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This file contains all of the probability distribution functions
"""
import math
import numpy as np
def dn_ddp(dp, n, gm, gsd):
"""Evaluate the number distribution as a lognormal PDF.
The PDF of a lognormal distribution is calculated using equation 8.34
fr... |
"""Test different accessory types: Lights."""
from collections import namedtuple
import pytest
from homeassistant.components.homekit.const import ATTR_VALUE
from homeassistant.components.light import (
ATTR_BRIGHTNESS,
ATTR_BRIGHTNESS_PCT,
ATTR_COLOR_TEMP,
ATTR_HS_COLOR,
DOMAIN,
SUPPORT_BRIGHT... |
MyName = "DeeDee" #contains my name
MyAge = 14.0 #contains my age
MyHeightInMeters = 1.7018 #contains my height in meters
LengthOf1SideOfSquareInMeters = 8 #contains length of 1 side of a sqaure in meters
LengthOfTriangleInMeters = 6 #contains length of a triangle in meters
HeightOfTriangleInMeters = 5 #contains height... |
"""
Object store tests.
"""
from twisted.internet.defer import inlineCallbacks, returnValue
import settings
from src.utils.test_utils import DottTestCase
from src.daemons.server.objects.exceptions import ObjectHasZoneMembers, NoSuchObject
#noinspection PyProtectedMember
class GeneralObjectStoreTests(DottTestCase):
... |
# -*- coding: utf-8 -*-
'''
Created on 2012-11-30 12:37
@summary: Main class for the TCP Client
@author: Martin Predki
'''
from TcpClientFactory import TcpClientFactory
from twisted.internet import reactor
from twisted.internet.endpoints import TCP4ClientEndpoint
import logging
class TcpClient(object):
'''
... |
from openerp.osv import orm, fields
from openerp.tools.translate import _
from openerp.addons.connector.session import ConnectorSession
from ..unit.import_synchronizer import create_doc_from_dms
import logging
_logger = logging.getLogger(__name__)
class ir_attachment_dms_wizard(orm.Model):
_name = 'ir.attachment.... |
import pytest
from mne import open_docs, grade_to_tris
from mne.epochs import add_channels_epochs
from mne.utils import (copy_function_doc_to_method_doc, copy_doc,
linkcode_resolve, deprecated, deprecated_alias)
import webbrowser
@pytest.mark.parametrize('obj', (grade_to_tris, add_channels_epo... |
#!/usr/bin/env python
""" nav_test.py - Version 1.1 2013-12-20
Command a robot to move autonomously among a number of goal locations defined in the map frame.
On each round, select a new random sequence of locations, then attempt to move to each location
in succession. Keep track of success rate, time el... |
#!get_street_lengths
###determines the length of each street
###using osm data.
import pickle
import numpy as np
from lxml import etree
## imports for finding distance between nodes
import geopy
from geopy import distance
## imports for checking weather node is within city bounds
from shapely.geometry import Polygon... |
# -*- coding: utf-8 -*-
from .. import models
from .generic import Manager, AllMixin, GetByIdMixin, SyncMixin
class FiltersManager(Manager, AllMixin, GetByIdMixin, SyncMixin):
state_name = 'filters'
object_type = 'filter'
def add(self, name, query, **kwargs):
"""
Creates a local filter o... |
from .client import TreeherderClient
class PerformanceTimeInterval(object):
'''
Valid time intervals for Perfherder series
'''
DAY = 86400
WEEK = 604800
TWO_WEEKS = 1209600
SIXTY_DAYS = 5184000
NINETY_DAYS = 7776000
ONE_YEAR = 31536000
@staticmethod
def all_valid_time_inte... |
class Queue(object):
"""
Common methods for queues
"""
def __init__(self):
self._queue = []
def __iter__(self):
for el in self._queue:
yield el
def __len__(self):
return len(self._queue)
@property
def first(self):
try:
return sel... |
"""Module for admin configuration for the events application."""
import logging
from django.contrib import admin
from django.contrib.gis.db import models as geomodels
from events.models import (
Event,
Session,
Location,
Organiser,
Sponsor,
Series,
)
from mapwidgets.widgets import GooglePointFie... |
"""
Namespace that defines fields common to all blocks used in the LMS
"""
from xblock.fields import Boolean, Scope, String, XBlockMixin, Dict
from xblock.validation import ValidationMessage
from xmodule.modulestore.inheritance import UserPartitionList
# Make '_' a no-op so we can scrape strings
_ = lambda text: text
... |
__author__ = 'Robert Meyer'
import os
from pypet import Trajectory
import matplotlib.pyplot as plt
def main():
# This time we don't need an environment since we just going to look
# at data in the trajectory
traj = Trajectory('FiringRate', add_time=False)
# Let's load the trajectory from the file
... |
import requests
import sys
from firecares.firestation.models import FireDepartment
from django.core.management.base import BaseCommand
from optparse import make_option
def chunks(l, n):
for i in xrange(0, len(l), n):
yield l[i:i + n]
class Command(BaseCommand):
help = 'Verifies that the thumbnails f... |
"""
Support definition for constrained parts.
Each set of lines defining support locations can be set
-
Provided by Wasp 0.5
Args:
DIR: Directions of the support locations as lines
GEO: OPTIONAL // Geometry of the part the support belongs to (useful for checking if the supports are correctly placed)... |
from openerp.osv import osv
from openerp.tools.translate import _
class MessagePostShowAll(osv.Model):
'''
With this object you can add an extensive log in your model like the
traditional message log don't does
You need do it the following way:
_name = "account.invoice"
_inherit = ['a... |
"""
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this ... |
from epiphany.instruction import Instruction
from epiphany.isa import decode
from epiphany.machine import RESET_ADDR
from epiphany.test.machine import new_state, StateChecker
import opcode_factory
import pytest
@pytest.mark.parametrize('is16bit', [True, False])
def test_infinite_loop(is16bit):
state = new_state(A... |
import copy
from django import forms
from django.contrib.contenttypes.models import ContentType
from django.core.exceptions import PermissionDenied, ObjectDoesNotExist
from django.db import models
from django.forms.models import modelform_factory
from django.http import Http404
from django.template import loader
from ... |
#!/usr/bin/python
"""Script to process the JSON feed of the Dutch IENC charts list and convert it to the XML catalog format
Part of the ChartCatalogs project
Copyright (c) 2019-2020 Marcel Verpaalen
Licensed under GPLv2 or, at your will later version
"""
import sys
from ChartCatalogs import Chart, RncChartCatalog
from... |
# coding: utf-8
from __future__ import absolute_import
from ...ruamel.yaml.emitter import Emitter
from ...ruamel.yaml.serializer import Serializer
from ...ruamel.yaml.representer import (
Representer,
SafeRepresenter,
BaseRepresenter,
RoundTripRepresenter,
)
from ...ruamel.yaml.resolver import Resolve... |
# -*- 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 field 'Feed.title'
db.add_column('feedme_feed', 'title',
self.gf('django.db.m... |
"""
Cache driver that uses xattr file tags and requires a filesystem
that has atimes set.
Assumptions
===========
1. Cache data directory exists on a filesytem that updates atime on
reads ('noatime' should NOT be set)
2. Cache data directory exists on a filesystem that supports xattrs.
This is optional, but hi... |
from django import template
from metashare.settings import MEDIA_URL
from metashare.repository.model_utils import get_resource_license_types
from replace import pretty_camel
register = template.Library()
@register.filter("licence_icon")
def licence_icon(licence):
if licence == "non-standard/Other_Licence/Terms":
... |
'''
Extract _("...") strings for translation and convert to Qt stringdefs so that
they can be picked up by Qt linguist.
'''
from __future__ import division,print_function,unicode_literals
from subprocess import Popen, PIPE
import operator
import os
import sys
OUT_CPP="qt/galaxycashstrings.cpp"
EMPTY=['""']
def parse_... |
import itk
import itk.support.types as itkt
from sys import argv
import warnings
from typing import Sequence, TypeVar, get_type_hints, get_args, get_origin, Union
try:
from numpy.typing import ArrayLike
except ImportError:
from numpy import ndarray as ArrayLike
input_filename = argv[1]
output_filename = argv[... |
# Programa que adiciona as ausências à shapefile que representa a amostra de validação (que corresponde a 30% das presenças). Tendo as presenças e ausências no mesmo tema vectorial, o Programa também extrai, do raster que se pretende validar, os valores das células que se intersectam com os pontos - GDAL
import os, sh... |
# -*- encoding:utf-8 -*-
"""
VWAP: Volume Weighted Average Price 成交量加权平均价
非标准传统意义vwap计算,即非使用高频的分钟k线和量进行计算,只是套用概念计算
日线级别的vwap
"""
from __future__ import division
from __future__ import print_function
from __future__ import absolute_import
from enum import Enum
import numpy as np
from ..TLineBu.ABuTLine i... |
# coding=utf-8
# 结构方程模型的参数估计
from __future__ import division, print_function, unicode_literals
from psy import sem, data
import numpy as np
data_ = data['ex5.11.dat']
beta = np.array([
[0, 0],
[1, 0]
])
gamma = np.array([
[1, 1],
[0, 0]
])
x = [0, 1, 2, 3, 4, 5]
lam_x = np.array([
[1, 0],
[... |
import proto # type: ignore
__protobuf__ = proto.module(
package="google.ads.googleads.v8.services",
marshal="google.ads.googleads.v8",
manifest={"GetAdGroupSimulationRequest",},
)
class GetAdGroupSimulationRequest(proto.Message):
r"""Request message for
[AdGroupSimulationService.GetAdGroupSimu... |
import time
from metadata import metadata
from payloads.payload import Payload
from utils import register_operation
class Logger(Payload):
def __init__(self, args):
Payload.__init__(self, args)
def run(self):
super(Logger, self).run()
def inject(self, file_path, file_metadata):
... |
def main(request, response):
response.headers.set("Content-Security-Policy", "connect-src http://www.w3.org")
response.headers.set("X-Content-Security-Policy", "connect-src http://www.w3.org")
response.headers.set("X-WebKit-CSP", "connect-src http://www.w3.org")
return """<!DOCTYPE html>
<!--
Copyright ... |
"""Analyzes a profile dump."""
import collections
def computeAverages(numerators, denominators):
"""Compute average own times."""
avg = {}
for k, v in numerators.items():
avg[k] = v * 1.0 / denominators[k]
return avg
class TreeNode(object):
"""Node in the profile tree."""
__slots__ = ('fullName',... |
"""Handler for serving serialized test cases for the reproduce tool."""
from flask import request
from datastore import data_handler
from datastore import data_types
from handlers import base_handler
from libs import access
from libs import handler
def _prepare_testcase_dict(testcase):
"""Prepare a dictionary con... |
import unittest
import common
import keepkeylib.ckd_public as bip32
class TestMsgGetaddress(common.KeepKeyTest):
def test_btc(self):
self.setup_mnemonic_nopin_nopassphrase()
self.assertEqual(self.client.get_address('Bitcoin', []), '1EfKbQupktEMXf4gujJ9kCFo83k1iMqwqK')
self.assertEqual(self... |
from __future__ import absolute_import, print_function
import six
from sentry.plugins import providers
class ProviderManager(object):
type = None
def __init__(self):
self._items = {}
def __iter__(self):
return iter(self._items)
def add(self, item, id):
if self.type and not... |
import json
import os
import re
import pytest
import yaml
from Pegasus.api.writable import _CustomEncoder
def _tojson(obj):
"""Returns dict representation of obj using writable._CustomEncoder"""
return json.loads(json.dumps(obj, cls=_CustomEncoder))
@pytest.fixture(scope="module")
def convert_yaml_schemas... |
"""Miscellaneous support code shared by some of the tool scripts.
This includes option parsing code, HTML formatting code, and a couple of
useful helpers.
"""
__version__ = '$Revision$'
import getopt
import os.path
import sys
class Options:
__short_args = "a:c:ho:"
__long_args = [
# script control... |
import sys
import os
filename_stopwords='stopwords.txt'
filename_joinwords='joinwords.txt'
filename_bijoinwords='bigramjoinwords.txt'
def main(argv):
print "INITIALIZING LAZINESS"
#extract arguments
if '-select' in argv:
select = argv[argv.index('-select')+1]
else:
print "INCLUDE SELECTION TO LIM... |
import json
import logging
from collections import OrderedDict
def load_xml(f):
try:
from lxml import etree
except ImportError:
import xml.etree.ElementTree as etree
elements = []
for event, element in etree.iterparse(f):
if element.tag in ('node', 'way', 'relation'):
... |
#!/usr/bin/python
from BaseHTTPServer import BaseHTTPRequestHandler,HTTPServer
from os import curdir, sep
import cgi
import json
import subprocess
import base64
import sys
import socket
PORT_NUMBER = 8000
USERNAME = 'user'
PASS = 'pass'
settings = {}
proc = {}
def writeSettings():
with open('settings.json', 'w+') a... |
from traits.api import on_trait_change
from traitsui.api import VGroup, View, Item, ModelView, CSVListEditor
class CUBADataTypeModelView(ModelView):
"""Wraps the CUBADataType node in a ModelView for easier representation
and access.
"""
traits_view = View(
VGroup(
Item(
... |
"""
mbed SDK
Copyright (c) 2011-2013 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... |
#!/usr/bin/env python
from Tkinter import *
import tkMessageBox
import tkFileDialog
from tkFont import Font
import pickle
import numpy
#from post_program import convert_fits
import Pmw
import pylab
import os
class view_directories(Frame):
"""
This file is part of Sprout.
Sprout is free software: you can r... |
from flask import jsonify, abort
from flask.ext.restful import Api, Resource, reqparse, fields, marshal
from app import api, models, db
from app.models import datetime_converter
import datetime
"""
The API routing and logic is done here, as an example, I created a
UserAPI, which works as an API resource serv... |
import sys
import subprocess
import json
import re
def print_line(message):
""" Non-buffered printing to stdout. """
sys.stdout.write(message + '\n')
sys.stdout.flush()
def read_line():
""" Interrupted respecting reader for stdin. """
# try reading a line, removing any extra whitespace
try:
... |
import random
import math
class GeneticNet:
"""
Gentic algorithm class
:param array nets: Array of neural networks
:Exemple:
>>> nets = []
>>> for i in range(10):
... nets.append(Net([2, 3, 3]))
>>> alg = GeneticNet(nets)
"""
def... |
from pony.orm import *
from datetime import datetime
from model.group import Group
from model.contact import Contact
from pymysql.converters import encoders, decoders, convert_mysql_timestamp
class ORMFixture:
db = Database()
class ORMGroup(db.Entity):
_table_ = 'group_list'
id = PrimaryKey(i... |
__author__ = 'Christoph Heindl'
__copyright__ = 'Copyright 2017, Profactor GmbH'
__license__ = 'BSD'
import glob
import os
import numpy as np
import re
import matplotlib.pyplot as plt
import matplotlib
from mpl_toolkits.axes_grid1 import make_axes_locatable
from sensor_correction.utils import mask_outliers
import se... |
import unittest
import numpy as np
from pgmpy.factors.distributions import GaussianDistribution as JGD
from pgmpy.sampling import LeapFrog, ModifiedEuler, GradLogPDFGaussian
class TestGradLogPDFGaussian(unittest.TestCase):
def setUp(self):
mean = np.array([1, 2, 3, 4])
covariance = np.array(
... |
#!/usr/bin/env python3
from lib import ResourceCollection, Repository
import re
import csv
import time
import datetime
csv_path = "/home/eka/Documents/EyeTracking/Marie/subjects/subjects"
csv_list = ResourceCollection(csv_path, ".csv")
opensesame_list = csv_list.find("^subject(a-zA-Z1-9-_)*")
# Creating subject fil... |
from jmessage import *
from jmessage import url
import json
class User(object):
def __init__(self,jmessage):
self.jmessage=jmessage;
def build_user(self, username=None, password=None, nickname=None, star=None, avatar=None, gender=None,
signature=None, region=None, address=None, mtime... |
# coding: utf-8
from django.db import models, migrations
from django.utils import timezone
class Migration(migrations.Migration):
dependencies = [
('sites', '0001_initial'),
('auth', '0006_require_contenttypes_0002'),
]
operations = [
migrations.CreateModel(
name='Us... |
import datetime
from constance.test import override_config
from django.contrib.auth.models import Group, Permission
from django.contrib.contenttypes.models import ContentType
from django.core.files.base import ContentFile
from django.db.utils import IntegrityError
from kuma.users.tests import user, UserTestCase
from ... |
# Caltech SURF 2013
# FILE: homology2.py
# MENTOR: Professor Yi Ni
# 07.26.13
from copy import deepcopy
from grid import *
# problem: TODO FIXME how to handle Ak, B???
# FIXME shortcut- amanion file - cancel (ignore???) all differentials that
# preserve i,j grading
graph = {0:[3],
1:[3,4,5,6],
2:... |
#!C:\Python27\python.exe
import sys, os
from PyQt4 import QtCore, QtGui
from docx import Document
from docx.shared import Cm, Inches, Pt
from docx.enum.text import WD_ALIGN_PARAGRAPH
from PIL import Image
from StringIO import StringIO
import dokumentasi_ui
Ui_Main = dokumentasi_ui.Ui_MainWindow
def main():
app =... |
#!/usr/bin/python
import serial
import sys
import threading
import readline
import re
import time
def calc_checksum(msg_string):
csum = 0
for ch in list(msg_string):
csum ^= ord(ch)
return csum
def process_msg(msg):
msg_groups = re.search("^\$(?P<payload_str>.*)*(?P<checksum_str>[0-9a-fA... |
# -*- coding: utf-8 -*-
"""
Integration tests for the :mod:`repoze.who`-powered authentication sub-system.
As sample-ecommerce grows and the authentication method changes, only these tests
should be updated.
"""
from __future__ import unicode_literals
from nose.tools import eq_, ok_
from sample_ecommerce.tests impo... |
#!/usr/bin/env python
from __future__ import print_function
import socket
import functools
import json
import os
import sys
from subprocess import check_output, CalledProcessError, check_call
from netaddr import IPAddress, IPNetwork, AddrFormatError
from pycalico import netns
from pycalico.ipam import IPAMClient, Sequ... |
import os
import libxml2
import stat
from utils import errorprint, _
from yum import repoMDObject
class MetadataIndex(object):
def __init__(self, outputdir, opts=None):
if opts is None:
opts = {}
self.opts = opts
self.outputdir = outputdir
repodatadir = self.outputdir... |
from django.db import models
from students.models import Class, Subject, Teacher, Student
from news.models import BaseAbstractPost
class Homework(models.Model):
topic = models.CharField(default='Homework', max_length=50)
subject = models.ForeignKey(Subject, on_delete=models.CASCADE)
clazz = models.Forei... |
from django.db import models
from django import forms
from django.contrib.auth.models import User, Group
from django.contrib.auth.forms import UserCreationForm
from Map.models import Map, System
from django.db.models.signals import post_save
import pytz
import datetime
# Create your models here.
class PlayTi... |
"""Support for mounting images with qemu-nbd."""
import os
import random
import re
import time
from oslo.config import cfg
from nova.i18n import _, _LE
from nova.openstack.common import log as logging
from nova import utils
from nova.virt.disk.mount import api
LOG = logging.getLogger(__name__)
nbd_opts = [
cfg... |
from rest_framework.response import Response
from rest_framework.pagination import PageNumberPagination
from rest_framework.settings import api_settings
# Written by http://stackoverflow.com/a/31401203 prawg (http://stackoverflow.com/users/4698253/prawg) (CC-BY-SA 3.0)
# modified by Tian Zhi Wang and Kyle Carlstrom
cl... |
import random
database = None
web_server = None
class AuthException(Exception):
pass
class UserNotFoundException(Exception):
pass
def create_database():
global database
database = { 'users':{} }
def destroy_database():
global database
database = None
def get_admin_client():
return Us... |
# 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):
# Adding field 'Hansard.wordoftheday'
db.add_column('hansards_hansard', 'wordoftheday', self.gf('django.db... |
# emacs: at the end of the file
# ex: set sts=4 ts=4 sw=4 et:
# ## ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### #
"""Stub file for a guaranteed safe import of duecredit constructs: if duecredit
is not available.
To use it, place it into your project codebase to be imported, e.g. copy as
... |
#!/usr/bin/env python
"""Convert gene prediction file with reference to counts format.
EXPERIMENTAL. This script converts the gene predictions given in a
gene prediction file together with a reference into to counts format.
It uses SNP data from variant call format files. The SNP data will be
merged with the refere... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
import copy
import unittest
import pyowm.commons.exceptions
from pyowm.alertapi30.condition import Condition
from pyowm.alertapi30.trigger import Trigger
from pyowm.alertapi30.enums import AlertChannelsEnum
from pyowm.alertapi30.alert import Alert
from pyowm.u... |
import os, uuid, sys, json
from ingesters_disseminators import DefaultEntryIngester, DefaultDisseminator, FeedDisseminator, BinaryIngester, SimpleZipIngester, METSDSpaceIngester
from negotiator import AcceptParameters, ContentType
from core import SwordServer, Authenticator, WebUI
from sss_logging import logging
ssslo... |
#!/usr/bin/env python
import sys
import re
def setup_python3():
# Taken from "distribute" setup.py
from distutils.filelist import FileList
from distutils import dir_util, file_util, util, log
from os.path import join, exists
tmp_src = join("build", "src")
if exists(tmp_src):
dir_util.... |
"""This example downloads HTML Tags for a given campaign and placement ID.
To create campaigns, run create_campaign.py. To create placements, run
create_placement.py.
Tags: placement.getPlacementTagData
"""
__author__ = '<EMAIL> (Joseph DiLallo)'
import os
import sys
sys.path.insert(0, os.path.join('..', '..', '..',... |
# -*- coding: utf-8 -*-
import os
import webapp2
import jinja2
import utils
JINJA_ENV = jinja2.Environment(
loader=jinja2.FileSystemLoader(os.path.dirname(__file__)),
autoescape=True)
class BaseHandler(webapp2.RequestHandler):
def render(self, template, **kw):
t = JINJA_ENV.g... |
#!/usr/bin/env python
import paho.mqtt.client as mqtt
import datetime
import time
from daemonize import Daemonize
pid = "/tmp/HUD.pid"
from random import randint
delay = 2
silence = 10
lastmsgat = time.time()
from microdotphat import set_col,write_string, set_decimal, set_mirror, set_rotate180, clear, show
def remov... |
"""
pyexcel.plugins.sources.db_sources
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Generic database sources
:copyright: (c) 2015-2020 by Onni Software Ltd.
:license: New BSD License
"""
from pyexcel.source import AbstractSource
from pyexcel._compact import PY2
from pyexcel.internal import PARSER, RE... |
from ..excel_comparsion_test import ExcelComparisonTest
from ...workbook import Workbook
class TestCompareXLSXFiles(ExcelComparisonTest):
"""
Test file created by XlsxWriter against a file created by Excel.
"""
def setUp(self):
self.maxDiff = None
filename = 'chart_combined08.xlsx'
... |
# jsb/plugs/common/url.py
#
#
""" maintain log of urls. """
## jsb imports
from jsb.utils.exception import handle_exception
from jsb.lib.callbacks import callbacks
from jsb.lib.commands import cmnds
from jsb.lib.examples import examples
from jsb.lib.persiststate import PlugState
## basic imports
import re
import o... |
import os
from twisted.internet import reactor
from flumotion.configure import configure
from flumotion.common import log, keycards, common, errors
from flumotion.job import job
from flumotion.twisted import credentials, fdserver
from flumotion.common.options import OptionParser
__version__ = "$Rev: 6125 $"
def ma... |
__author__ = 'mworden'
from mi.core.log import get_logger
log = get_logger()
from mi.idk.config import Config
import unittest
import os
from mi.dataset.driver.ctdmo_ghqr.sio.ctdmo_ghqr_ct_recovered_driver import parse
from mi.dataset.dataset_driver import ParticleDataHandler
class SampleTest(unittest.TestCase):
... |
import urlparse
import xbmcgui
import resources.lib.utils as utils
from resources.lib.backup import XbmcBackup
def get_params():
param = {}
if(len(sys.argv) > 1):
for i in sys.argv:
args = i
if(args.startswith('?')):
args = args[1:]
param.update(... |
from neutron.common import constants
from neutron.common import rpc_compat
from neutron.common import topics
from neutron.common import utils
from neutron import manager
from neutron.openstack.common import log as logging
from neutron.plugins.common import constants as service_constants
LOG = logging.getLogger(__name... |
# -*- coding: utf-8 -*-
"""
Created on Tue Apr 25 15:00:15 2017
@author: Isola
"""
from pylab import *
import pandas as pd
#import numpy as np
from scipy.interpolate import lagrange #导入拉格朗日插值函数
#plt.plot() 折线图
#plt.hist() 直方图
#plt.bar() 柱状图
#plt.scatter() 散点图
#plt.pie() 饼图
#plt.boxplot() 箱线图
StealUserdiStribute =... |
NULL_STRING = "<NULL>"
class RouteMethod: # pylint: disable=too-few-public-methods
"""
Route methods are a FAB concept around ModelView and RestModelView
classes in FAB. Derivatives can define `include_route_method` and
`exclude_route_methods` class attribute as a set of methods that
will or won'... |
from woo.core import *; from woo.dem import *
import woo, woo.pack, woo.timing
import os.path, sys
from minieigen import *
import math
import numpy as np
periodic=False
outName='timings.txt'
r=.1
if len(sys.argv)==1:
tag,N,steps='',20,1000
else:
if len(sys.argv)!=4: raise RuntimeError("Exactly 3 argument must be give... |
#!/usr/bin/env python
# CreateInstance.py
#
# This class was intended to demonstrate an exercise using the Python AWS SDK
# (boto), however it will probably be extended to do much more over time,
# especially as I continue to test additional infrastructure.
#
# This class (CreateInstance) has some wrapper functions a... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.