code stringlengths 1 199k |
|---|
'output dimensionalities for each column'
import csv
import sys
import re
import math
from collections import defaultdict
def get_words( text ):
text = text.replace( "'", "" )
text = re.sub( r'\W+', ' ', text )
text = text.lower()
text = text.split()
words = []
for w in text:
if w in words:
continue
words.... |
import pyqtgraph as pg
from pyqtgraph.Qt import QtGui, QtCore
import numpy as np
import csv, gzip, os
from pyqtgraph import Point
class GlassDB:
"""
Database of dispersion coefficients for Schott glasses
+ Corning 7980
"""
def __init__(self, fileName='schott_glasses.csv'):
path = os.path.di... |
import logging
from urllib.parse import urljoin
import lxml.etree # noqa: S410
import requests
from django.conf import settings as django_settings
from django.utils import timezone
logger = logging.getLogger(__name__)
class ClientError(Exception):
pass
class ResponseParseError(ClientError):
pass
class Response... |
from PyQt4 import QtCore
import acq4.Manager
import acq4.util.imageAnalysis as imageAnalysis
run = True
man = acq4.Manager.getManager()
cam = man.getDevice('Camera')
frames = []
def collect(frame):
global frames
frames.append(frame)
cam.sigNewFrame.connect(collect)
def measure():
if len(frames) == 0:
... |
"""Create oauthclient tables."""
import sqlalchemy as sa
import sqlalchemy_utils
from alembic import op
from sqlalchemy.engine.reflection import Inspector
revision = '97bbc733896c'
down_revision = '44ab9963e8cf'
branch_labels = ()
depends_on = '9848d0149abd'
def upgrade():
"""Upgrade database."""
op.create_tabl... |
from thumbor.loaders import http_loader
from tornado.concurrent import return_future
from urllib import unquote
def _normalize_url(url):
url = http_loader.quote_url(unquote(url))
if url.startswith('http:'):
url = url.replace('http:', 'https:', 1)
return url if url.startswith('https://') else 'https:... |
from swgpy.object import *
def create(kernel):
result = Static()
result.template = "object/static/item/shared_armor_composite_helmet.iff"
result.attribute_template_id = -1
result.stfName("obj_n","unknown_object")
#### BEGIN MODIFICATIONS ####
#### END MODIFICATIONS ####
return result |
__revision__ = "__FILE__ __REVISION__ __DATE__ __DEVELOPER__"
"""
Test setting the $P4COMSTR variable.
"""
import os.path
import TestSCons
_python_ = TestSCons._python_
test = TestSCons.TestSCons()
test.subdir('Perforce', ['Perforce', 'sub'], 'sub')
sub_Perforce = os.path.join('sub', 'Perforce')
sub_SConscript = os.pat... |
from __future__ import unicode_literals
import time
import string
import json
import config
import helper
import busses
def log_message(msg):
#log format: time type message
time_str = str(time.time())
line = time_str[:time_str.find(".")]
line = line.rjust(10, str(" "))
line += " "
busses.status_... |
import os
import time
import numpy as np
import matplotlib
matplotlib.use('GTKAgg')
from matplotlib import pyplot as plt
from koheron import connect
from drivers import Spectrum
from drivers import Laser
host = os.getenv('HOST','192.168.1.100')
client = connect(host, name='spectrum')
driver = Spectrum(client)
laser = L... |
__version__ = '0.8.1'
__author__ = "Massimiliano Pippi & Federico Frenguelli"
VERSION = __version__ # synonym |
"""Show file statistics by extension."""
import os
import sys
class Stats:
def __init__(self):
self.stats = {}
def statargs(self, args):
for arg in args:
if os.path.isdir(arg):
self.statdir(arg)
elif os.path.isfile(arg):
self.statfile(arg)
... |
import os
import pygtk
pygtk.require('2.0')
import gtk
from gtkcodebuffer import CodeBuffer, SyntaxLoader
class Ui(object):
"""
The user interface. This dialog is the LaTeX input window and includes
widgets to display compilation logs and a preview. It uses GTK2 which
must be installed an importable.
... |
from __future__ import unicode_literals
from frappe.model.document import Document
class WebPageBlock(Document):
pass |
import cloudrobotics.message as message
APP_ID = 'SbrApiServices'
PROCESSING_ID = 'RbAppConversationApi'
class ConversationMessage(message.CRFXMessage):
def __init__(self, visitor, visitor_id, talkByMe, type):
super(ConversationMessage, self).__init__()
self.header['RoutingType'] = message.ROUTING_T... |
import time
import random
from random import randint
from library import Joystick
import RPi.GPIO as GPIO # remove!!!
from emotions import angry, happy, confused
from library import LEDDisplay
from library import factory
from library import reset_all_hw
global_LegMotor = 70
def remote_func(hw, ns):
print("Remote")
d... |
import sys
import os
cwd = os.getcwd()
project_root = os.path.dirname(cwd)
sys.path.insert(0, project_root)
import pywim
extensions = ['sphinx.ext.autodoc', 'sphinx.ext.viewcode']
templates_path = ['_templates']
source_suffix = '.rst'
master_doc = 'index'
project = u'PyWIM'
copyright = u"2016, Ivan Ogasawara"
version =... |
__all__ = []
import pkgutil
import inspect
for loader, name, is_pkg in pkgutil.walk_packages(__path__):
module = loader.find_module(name).load_module(name)
for name, value in inspect.getmembers(module):
if name.startswith('__'):
continue
globals()[name] = value
__all__.append... |
import csv
filename = "/tmp/QueryPipelineStatistics.csv"
times = []
with open(filename) as f:
reader = csv.reader(f)
header = next(reader)
assert header == ['query',
'rows',
'matches',
'quadwords',
'cachelines',
... |
from django.conf import settings
from django.conf.urls.defaults import patterns, url
from django.core.exceptions import ObjectDoesNotExist, MultipleObjectsReturned
from django.core.urlresolvers import NoReverseMatch, reverse, resolve, Resolver404
from django.db.models.sql.constants import QUERY_TERMS, LOOKUP_SEP
from d... |
import os
import re
from opsbro.collector import Collector
class Dmidecode(Collector):
def launch(self):
logger = self.logger
logger.debug('getDmidecode: start')
res = {}
# Maybe we are in linux and we can directly read the
linux_dmi_path = '/sys/class/dmi/id/'
if os.... |
import sys
if len(sys.argv) == 1:
print("Syntax: %s <GenAsmWriter.inc> <Output-GenAsmWriter.inc> <Output-GenRegisterName.inc> <arch>" %sys.argv[0])
sys.exit(1)
arch = sys.argv[4]
f = open(sys.argv[1])
lines = f.readlines()
f.close()
f1 = open(sys.argv[2], 'w+')
f2 = open(sys.argv[3], 'w+')
f1.write("/* Capstone... |
import logging, os
logging.basicConfig(level=logging.INFO)
from deepy.networks import RecursiveAutoEncoder
from deepy.trainers import SGDTrainer, LearningRateAnnealer
from util import get_data, VECTOR_SIZE
model_path = os.path.join(os.path.dirname(__file__), "models", "rae1.gz")
if __name__ == '__main__':
model = R... |
"""Example of server-side computations used in global forest change analysis.
In this example we will focus on server side computation using NDVI and EVI
data. This both metrics are computed bands created by third party companies
or directly taken by the satellites.
NDVI and EVI are two metrics used in global forest ch... |
"""Keccak family of cryptographic hash algorithms.
`Keccak`_ is the winning algorithm of the SHA-3 competition organized by NIST.
What eventually became SHA-3 is a variant incompatible to Keccak,
even though the security principles and margins remain the same.
If you are interested in writing SHA-3 compliant code, you ... |
from typing import Dict
import tempfile
from dxlclient.client_config import DxlClientConfig
from dxlclient.client import DxlClient
from dxlclient.broker import Broker
from dxlclient.message import Event
import demistomock as demisto
from CommonServerPython import *
from CommonServerUserPython import *
INTEGRATION_NAME ... |
"""Tests for wheel binary packages and .dist-info."""
import os
import pytest
from mock import patch, Mock
from pip._vendor import pkg_resources
from pip import pep425tags, wheel
from pip.exceptions import InvalidWheelFilename, UnsupportedWheel
from pip.utils import unpack_file
def test_get_entrypoints(tmpdir):
wit... |
import BoostBuild
t = BoostBuild.Tester(pass_toolset=0, ignore_toolset_requirements=False)
t.write('jamroot.jam', '''
import toolset ;
import errors ;
rule test-rule ( properties * )
{
return <define>TEST_INDIRECT_CONDITIONAL ;
}
toolset.add-requirements
<define>TEST_MACRO
<conditional>@test-rule
<link>shared:<... |
import os
import sys
from Bio import SeqIO
f = open(sys.argv[1], 'rU')
out = open(sys.argv[2], 'w')
for records in SeqIO.parse(f, 'fastq'):
SeqIO.write(records, out, 'fasta') |
'''
The MIT License (MIT)
GrovePi for the Raspberry Pi: an open source platform for connecting Grove Sensors to the Raspberry Pi.
Copyright (C) 2015 Dexter Industries
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to de... |
import argparse
import asyncio
import gc
import os.path
import pathlib
import socket
import ssl
PRINT = 0
async def echo_server(loop, address, unix):
if unix:
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
else:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.sets... |
from headers.BeaEnginePython import *
from nose.tools import *
class TestSuite:
def test(self):
# EVEX.256.66.0F3A.W0 25 /r ib
# vpternlogd ymm1{k1}{z}, ymm2, ymm3/m256/m32bcst, imm8
myEVEX = EVEX('EVEX.256.66.0F3A.W0')
Buffer = bytes.fromhex('{}252011'.format(myEVEX.prefix()))
... |
import flask
from donut import auth_utils
from donut.modules.account import blueprint, helpers
@blueprint.route("/request")
def request_account():
"""Provides a form to request an account."""
return flask.render_template("request_account.html")
@blueprint.route("/request/submit", methods=["POST"])
def request_a... |
from re import sub
from itertools import islice
'''
如何调整字符串的文本格式
'''
with open("./log.log","r") as f:
for line in islice(f,0,None):
#print sub("(\d{4})-(\d{2})-(\d{2})",r"\2/\3/\1",line)
# 可以为每个匹配组起一个别名
print sub("(?P<year>\d{4})-(?P<month>\d{2})-(?P<day>\d{2})",r"\g<month>/\g<day>/\g<>",lin... |
'''
The MIT License (MIT)
GrovePi for the Raspberry Pi: an open source platform for connecting Grove Sensors to the Raspberry Pi.
Copyright (C) 2015 Dexter Industries
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to de... |
import glob, os, sys
import sipconfig
from PyQt4 import pyqtconfig
def get_diana_version():
depends = filter(lambda line: line.startswith("Depends:"),
open("debian/control").readlines())
for line in depends:
pieces = line.split()
for piece in pieces:
name_pieces ... |
from datetime import datetime
from flask import current_app
from flask.cli import with_appcontext
from invenio_db import db
from hepdata.cli import fix
from hepdata.ext.elasticsearch.api import index_record_ids, push_data_keywords
from hepdata.modules.submission.models import HEPSubmission, DataSubmission
from hepdata.... |
"""
Small event module
=======================
"""
import numpy as np
import logging
logger = logging.getLogger(__name__)
from ...utils.decorators import face_lookup
from ...geometry.sheet_geometry import SheetGeometry
from ...topology.sheet_topology import cell_division
from .actions import (
exchange,
remove,... |
from flask import request, jsonify
from sql_classes import UrlList, Acl, UserGroup, User, Role
def _node_base_and_rest(path):
"""
Returns a tuple: (the substring of a path after the last nodeSeparator, the preceding path before it)
If 'base' includes its own baseSeparator - return only a string after it
... |
"""
gateway tests - Users
Copyright 2009 Glencoe Software, Inc. All rights reserved.
Use is subject to license terms supplied in LICENSE.txt
"""
import unittest
import omero
import gatewaytest.library as lib
from omero.gateway.scripts import dbhelpers
class UserTest (lib.GTest):
def testUsers (self):
... |
"""Standard input/out/err support.
API Stability: semi-stable
Future Plans: support for stderr, perhaps
Maintainer: U{Itamar Shtull-Trauring<mailto:twisted@itamarst.org>}
"""
import sys, os, select, errno
import abstract, fdesc, protocol
from main import CONNECTION_LOST
_stdio_in_use = 0
class StandardIOWriter(abstract... |
import copy
import Queue
import os
import socket
import struct
import subprocess
import sys
import threading
import time
import unittest
import dns
import dns.message
import libnacl
import libnacl.utils
class DNSDistTest(unittest.TestCase):
"""
Set up a dnsdist instance and responder threads.
Queries sent t... |
from opus_core.variables.variable import Variable
from variable_functions import my_attribute_label
from urbansim.length_constants import UrbanSimLength, UrbanSimLengthConstants
from numpy import array
class is_near_arterial(Variable):
"""Boolean indicating if this gridcell is near an arterial, as specified by the ... |
import random
from collections import namedtuple
import dateparser
import pytest
from cfme import test_requirements
from cfme.containers.image import Image
from cfme.containers.provider import ContainersProvider
from cfme.containers.provider import ContainersTestItem
from cfme.utils.appliance.implementations.ui import ... |
"""
.. currentmodule:: __init__.py
.. moduleauthor:: Pat Daburu <pat@daburu.net>
Provide a brief description of the module.
""" |
from stopeight import analyzer
version=analyzer.version
from stopeight.util.editor.data import ScribbleData
def legal_segments(data):
from stopeight.matrix import Vectors
from stopeight.analyzer import legal_segments
return legal_segments(Vectors(data)).__array__().view(ScribbleData)
legal_segments.__annota... |
from django.contrib.auth.models import User
from django.db import models
from django.db.models.signals import post_save
from django.dispatch import receiver
from django.utils.translation import ugettext as _
class Application(models.Model):
client_id = models.CharField(_('Client ID'), max_length=40, blank=False, pr... |
import math
import os
import sys
import xml.etree.ElementTree as ETree
import tabulate
from mdutils.mdutils import MdUtils
DEFAULT_INI = {'global': {'unusedholes': 'yes',
'onebitenum': 'no'}}
def sortRegisterAndFillHoles(regName,
fieldNameList,
... |
from scriptLattes import *
from geradorDePaginasWeb import *
import re
class OutroTipoDeProducaoBibliografica:
item = None # dado bruto
idMembro = None
relevante = None
autores = None
titulo = None
ano = None
natureza = None # tipo de producao
chave = None
def __init__(self, idMembro, partesDoItem='', relevant... |
"""This test module contains tests for the migration system."""
import os
import subprocess
import unittest
REPO_PATH = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", ".."))
class TestAlembic(unittest.TestCase):
"""This test class contains tests pertaining to alembic."""
def test_alembic_history(... |
import pybedtools
import os
testdir = os.path.dirname(__file__)
test_tempdir = os.path.join(os.path.abspath(testdir), 'tmp')
unwriteable = os.path.join(os.path.abspath(testdir), 'unwriteable')
def setup():
if not os.path.exists(test_tempdir):
os.system('mkdir -p %s' % test_tempdir)
pybedtools.set_tempdi... |
__all__ = ["LinkBox"]
import logging
_LOG = logging.getLogger(".widgets.linkbox")
from gi.repository import GObject
from gi.repository import Gtk
class LinkBox(Gtk.HBox):
def __init__(self, link, button):
GObject.GObject.__init__(self)
self.set_spacing(6)
self.pack_start(link, False, True, 0... |
"""Unit tests for the ranking engine."""
__revision__ = "$Id$"
from invenio.importutils import lazy_import
from invenio.testutils import make_test_suite, run_test_suite, InvenioTestCase
bibrank_tag_based_indexer = lazy_import('invenio.bibrank_tag_based_indexer')
split_ranges = lazy_import('invenio.bibrank:split_ranges'... |
def spaceship_building(cans):
total_cans = 0
for week in range(1,53):
total_cans = total_cans + cans
print('Week %s = %s cans' % (week, total_cans))
spaceship_building(2)
spaceship_building(13) |
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('emailer', '0007_auto_20150509_1922'),
]
operations = [
migrations.AlterField(
model_name='email',
name='recipient',
f... |
import MySQLdb
class DatabaseHandler:
def __init__(self):
pass
def is_delete(self, tableName):
reservedTableNameList = ["mantis_user_table", "mantis_tokens_table", "mantis_config_table"]
isDeleteFlag = 1
for name in reservedTableNameList:
isIdentical = cmp(tableName, ... |
from __future__ import print_function
import time
import bugzilla
URL = "partner-bugzilla.redhat.com"
bzapi = bugzilla.Bugzilla(URL)
query = bzapi.build_query(
product="Fedora",
component="python-bugzilla")
query["status"] = "CLOSED"
t1 = time.time()
bugs = bzapi.query(query)
t2 = time.time()
print("Found %d bu... |
from ....const import GRAMPS_LOCALE as glocale
_ = glocale.translation.gettext
from .. import HasGrampsId
class HasIdOf(HasGrampsId):
"""Rule that checks for a person with a specific GRAMPS ID"""
name = _('Person with <Id>')
description = _("Matches person with a specified Gramps ID") |
import string
import socket
import base64
import sys
class message:
def __init__(self, name="generate" ):
if name == "generate":
self.name=socket.gethostname()
else:
self.name=name
self.type="gc"
self.decoded=""
def set ( self, content=" " ):
base... |
import sys
import re
import codecs
from collections import Counter
filename = sys.argv[1]
with codecs.open(filename, encoding='utf-8') as f:
text = f.read()
m = re.findall(r'^#{2,3} .*$', text, re.MULTILINE)
def title(s):
return re.sub(r'#+ ', '', s)
def fragment(s):
return '#' + re.sub(r'[^a-z-]', '', re.s... |
"""
pygments.plugin
~~~~~~~~~~~~~~~
Pygments setuptools plugin interface. The methods defined
here also work if setuptools isn't installed but they just
return nothing.
lexer plugins::
[pygments.lexers]
yourlexer = yourmodule:YourLexer
formatter plugins::
[pygments.fo... |
import logging
from borgmatic.borg.flags import make_flags, make_flags_from_arguments
from borgmatic.execute import execute_command
logger = logging.getLogger(__name__)
BORG_EXCLUDE_CHECKPOINTS_GLOB = '*[0123456789]'
def resolve_archive_name(repository, archive, storage_config, local_path='borg', remote_path=None):
... |
import sys
import time
import optparse
from email.Charset import Charset
from mailman import MailList
from mailman import Utils
from mailman.app.requests import handle_request
from mailman.configuration import config
from mailman.core.i18n import _
from mailman.email.message import UserNotification
from mailman.initial... |
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 'InstanceApplication.network'
db.add_column('apply_instanceapplication', 'network', self.gf('django.db.models.fields.rel... |
"""
Test shows
"""
from __future__ import print_function, unicode_literals
import os
import sys
import unittest
sys.path.insert(1, os.path.abspath(os.path.join(os.path.dirname(__file__), '../../../lib')))
sys.path.insert(1, os.path.abspath(os.path.join(os.path.dirname(__file__), '../../..')))
import sickbeard
import si... |
{
'"update" is an optional expression like "field1=\'newvalue\'". You cannot update or delete the results of a JOIN': '"update" is an optional expression like "field1=\'newvalue\'". You cannot update or delete the results of a JOIN',
'%Y-%m-%d': '%Y.%m.%d.',
'%Y-%m-%d %H:%M:%S': '%Y.%m.%d. %H:%M:%S',
'%s rows deleted':... |
"""Convert HTML page to Word 97 document
This script is used during the build process of "Dive Into Python"
(http://diveintopython.org/) to create the downloadable Word 97 version
of the book (http://diveintopython.org/diveintopython.doc)
Looks for 2 arguments on the command line. The first argument is the input (HTML... |
"""
Simple roster implementation. Can be used though for different tasks like
mass-renaming of contacts.
"""
from protocol import JID, Iq, Presence, Node, NodeProcessed, NS_MUC_USER, NS_ROSTER
from plugin import PlugIn
import logging
log = logging.getLogger('nbxmpp.roster_nb')
class NonBlockingRoster(PlugIn):
"""
... |
from django.contrib import admin
from django.utils.translation import ugettext as _
from .models import AbuseReport, SearchTermRecord
admin.site.register(AbuseReport)
class SearchTermAdmin(admin.ModelAdmin):
list_display = ('__unicode__', 'ip_address', 'get_user_full_name', )
search_fields = ('term', )
def ... |
"""
================================================================================
Logscaled Histogram
================================================================================
| Calculates a logarithmically spaced histogram for a data map.
| Written By: Matthew Stadelman
| Date Written: 2016/03/07
| Last Modi... |
from ..daltools.util.full import init
Z = [8., 1., 1.]
Rc = init([0.00000000, 0.00000000, 0.48860959])
Dtot = [0, 0, -0.76539388]
Daa = init([
[ 0.00000000, 0.00000000, -0.28357300],
[ 0.15342658, 0.00000000, 0.12734703],
[-0.15342658, 0.00000000, 0.12734703],
])
QUc = init([-7.31176220, 0., 0., -5.4324... |
import inctest
error = 0
try:
a = inctest.A()
except:
print "didn't find A"
print "therefore, I didn't include 'testdir/subdir1/hello.i'"
error = 1
pass
try:
b = inctest.B()
except:
print "didn't find B"
print "therefore, I didn't include 'testdir/subdir2/hello.i'"
error = 1
pass
if error == 1:
raise ... |
from __future__ import absolute_import, print_function, division
from mitmproxy import exceptions
import pprint
def _get_name(itm):
return getattr(itm, "name", itm.__class__.__name__)
class Addons(object):
def __init__(self, master):
self.chain = []
self.master = master
master.options.ch... |
import os # os.system for clearing screen and simple gam calls
import subprocess # subprocess.Popen is to capture gam output (needed for user info in particular)
import MySQLdb # MySQLdb is to get data from relevant tables
import csv # CSV is used to read output of drive commands that supply data in C... |
r"""
********************************************
**espressopp.integrator.LangevinThermostat**
********************************************
.. function:: espressopp.integrator.LangevinThermostat(system)
:param system:
:type system:
"""
from espressopp.esutil import cxxinit
from espressopp import pmi
from espressopp... |
import argparse
import os
import subprocess
import tempfile
ACTIVE_DISTROS = ("xenial", "artful", "bionic")
def main():
parser = argparse.ArgumentParser()
parser.add_argument("day", help="The day of the results, with format yyyymmdd")
args = parser.parse_args()
install_autopkgtest_results_formatter()
... |
import gtk
class ExtensionFeatures:
SYSTEM_WIDE = 0
class MountManagerExtension:
"""Base class for mount manager extensions.
Mount manager has only one instance and is created on program startup.
Methods defined in this class are called automatically by the mount manager
so you need to implement them.
"""
# feat... |
import random
from google.appengine.api import memcache
from google.appengine.ext import ndb
SHARD_KEY_TEMPLATE = 'shard-{}-{:d}'
class GeneralCounterShardConfig(ndb.Model):
num_shards = ndb.IntegerProperty(default=20)
@classmethod
def all_keys(cls, name):
config = cls.get_or_insert(name)
sh... |
class Serializer(object):
schemaless = True
encapsulate = True
registry = {}
def __init__(self, query_params, pretty=False, **kwargs):
self.pretty = pretty
self._query_params = query_params
self._fileName = None
self._lastModified = None
self._extra_args = kwargs
... |
"""Data models for referral system."""
from __future__ import unicode_literals
from builtins import map
from django.db import models
from django.core.urlresolvers import reverse
from pttrack.models import (ReferralType, ReferralLocation, Note,
ContactMethod, CompletableMixin,)
from followup.... |
'''Test the analysis.signal module.'''
from __future__ import absolute_import, print_function, division
import pytest
import numpy as np
import gridcells.analysis.signal as asignal
from gridcells.analysis.signal import (local_extrema, local_maxima,
local_minima, ExtremumTypes,
... |
"""Add timetable related tables
Revision ID: 33a1d6f25951
Revises: 225d0750c216
Create Date: 2015-11-25 14:05:51.856236
"""
import sqlalchemy as sa
from alembic import op
from indico.core.db.sqlalchemy import PyIntEnum, UTCDateTime
from indico.modules.events.timetable.models.entries import TimetableEntryType
revision =... |
import constants, sys
from charsetgroupprober import CharSetGroupProber
from sbcharsetprober import SingleByteCharSetProber
from langcyrillicmodel import Win1251CyrillicModel, Koi8rModel, Latin5CyrillicModel, MacCyrillicModel, Ibm866Model, Ibm855Model
from langgreekmodel import Latin7GreekModel, Win1253GreekModel
from ... |
from typing import Any, Dict, Set
from snapcraft import project
from snapcraft.internal.project_loader import grammar
from snapcraft.internal import pluginhandler, repo
from ._package_transformer import package_transformer
class PartGrammarProcessor:
"""Process part properties that support grammar.
Stage packag... |
from __future__ import unicode_literals
import unittest
class TestEInvoiceRequestLog(unittest.TestCase):
pass |
import pytest
from umodbus.server.serial import AbstractSerialServer
@pytest.fixture
def abstract_serial_server():
return AbstractSerialServer()
def test_abstract_serial_server_get_meta_data(abstract_serial_server):
""" Test if meta data is correctly extracted from request. """
assert abstract_serial_server... |
panel_file = open('panels.txt','r')
name_file = open('testName.txt','r')
sample_type_file = open("sampleType.txt")
test_panel_results = open("output/testPanelResults.txt", 'w')
panel = []
type = []
test_names = []
def get_split_names( name ):
split_name_list = name.split("/")
for i in range(0, len(split_name_li... |
from __future__ import unicode_literals
from django import forms
from django.utils.translation import ugettext_lazy as _
from shoop.admin.form_part import FormPart, TemplatedFormDef
from shoop.core.models import Shop
from shoop.discount_pricing.models import DiscountedProductPrice
class DiscountPricingForm(forms.Form):... |
import base64
import netsvc
from osv import osv
from osv import fields
from tools.translate import _
import tools
def _reopen(self, wizard_id, res_model, res_id):
return {'type': 'ir.actions.act_window',
'view_mode': 'form',
'view_type': 'form',
'res_id': wizard_id,
'... |
from __future__ import absolute_import, unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('schedules', '0005_auto_20171010_1722'),
]
operations = [
migrations.CreateModel(
name='ScheduleExperience',
fiel... |
from openerp.addons.financial.tests.financial_test_classes import \
FinancialTestCase
class ManualFinancialProcess(FinancialTestCase):
def setUp(self):
self.financial_model = self.env['financial.move']
super(ManualFinancialProcess, self).setUp()
def test_01_check_return_views(self):
... |
from django import forms
from django.utils.translation import ugettext_lazy as _
from shuup.core.models import Category
from shuup.xtheme import TemplatedPlugin
from shuup.xtheme.plugins.forms import GenericPluginForm, TranslatableField
class CategoryLinksConfigForm(GenericPluginForm):
"""
A configuration form ... |
from .base import BaseHandler
class TestRoute(BaseHandler):
def get(self, file):
return self.render(str(file) + '.jade', show_h1=1) |
import sys
import time
import sys
num = 1000
print_granularity = 1000
count = 0
first = True
start = 0
gran_start = 0
min = 0
max = 0
avg = 0
sum = 0
total = 0
def set_print_granularity(p):
global print_granularity
print_granularity = p
print("%s: print granularity = %s" % (sys.argv[0], print_granularity))
def loop_... |
from openerp import models, fields, api
class StockPicking(models.Model):
_inherit = 'stock.picking'
carrier_price = fields.Float(string="Shipping Cost", readonly=True)
delivery_type = fields.Selection(related='carrier_id.delivery_type', readonly=True)
@api.multi
def do_transfer(self):
res =... |
import decimal
import pytest
from django.conf import settings
from shuup.core.models import Shipment, ShippingStatus, StockBehavior
from shuup.testing.factories import (
add_product_to_order, create_empty_order, create_product,
get_default_shop, get_default_supplier
)
from shuup.utils.excs import Problem
@pytes... |
"""
Test cases to cover Accounts-related behaviors of the User API application
"""
import datetime
import hashlib
import json
from copy import deepcopy
from unittest import mock
import ddt
import pytz
from django.conf import settings
from django.test.testcases import TransactionTestCase
from django.test.utils import ov... |
def _checkInput(index):
if index < 0:
raise ValueError("Indice negativo non supportato [{}]".format(index))
elif type(index) != int:
raise TypeError("Inserire un intero [tipo input {}]".format(type(index).__name__))
def fib_from_string(index):
_checkInput(index)
serie = "0 1 1 2 3 5 8".r... |
"""
Braitenberg Vehicle2b
The more light sensed on the left side the faster the right motor moves.
The more light sensed on the right side the faster the left motor moves.
This causes the robot to turn towards a light source.
"""
from pyrobot.brain import Brain, avg
class Vehicle(Brain):
def setup(self):
self.... |
import pygtk
pygtk.require('2.0')
import pynotify
import sys
if __name__ == '__main__':
if not pynotify.init("XY"):
sys.exit(1)
n = pynotify.Notification("X, Y Test",
"This notification should point to 150, 10")
n.set_hint("x", 150)
n.set_hint("y", 10)
if not n.... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.