code stringlengths 1 199k |
|---|
from reportlab.lib.testutils import setOutDir,makeSuiteForClasses, outputfile, printLocation
setOutDir(__name__)
import sys
from xml.dom import minidom
from xml.sax._exceptions import SAXReaderNotAvailable
import unittest
from reportlab.graphics.shapes import *
from reportlab.graphics import renderSVG
def warnIgnoredRe... |
"""
Describes additional web UI properties of Cobbler fields defined in item_*.py.
Copyright 2009, Red Hat, Inc and Others
Michael DeHaan <michael.dehaan AT gmail>
This program 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 ... |
import logging
from helpers import unittest
import luigi.notifications
import luigi.worker
from luigi import Parameter, RemoteScheduler, Task
from luigi.worker import Worker
from mock import Mock
luigi.notifications.DEBUG = True
class DummyTask(Task):
param = Parameter()
def __init__(self, *args, **kwargs):
... |
NETBIOS_NS_PORT = 137
NETBIOS_SESSION_PORT = 139
NODE_B = 0x00
NODE_P = 0x01
NODE_M = 0x10
NODE_RESERVED = 0x11
TYPE_UNKNOWN = 0x01
TYPE_WORKSTATION = 0x00
TYPE_CLIENT = 0x03
TYPE_SERVER = 0x20
TYPE_DOMAIN_MASTER = 0x1B
TYPE_MASTER_BROWSER = 0x1D
TYPE_BROWSER = 0x1E
TYPE_NAMES = { TYPE_UNKNOWN: 'Unknown',
... |
from __future__ import with_statement
from random import randint, choice, sample
from nose.tools import assert_equal, assert_not_equal #@UnresolvedImport
from whoosh import fields, matching, query
from whoosh.compat import u
from whoosh.filedb.filestore import RamStorage
from whoosh.query import And, Term
from whoosh.... |
from gnuradio import gr, gr_unittest
import math
class test_filter_delay_fc (gr_unittest.TestCase):
def setUp (self):
self.tb = gr.top_block ()
def tearDown (self):
self.tb = None
def test_001_filter_delay_one_input (self):
# expected result
expected_result = ( ... |
"""
raven.scripts.runner
~~~~~~~~~~~~~~~~~~~~
:copyright: (c) 2012 by the Sentry Team, see AUTHORS for more details.
:license: BSD, see LICENSE for more details.
"""
from __future__ import absolute_import
from __future__ import print_function
import logging
import os
import sys
import time
from optparse import OptionPa... |
from openerp.osv import fields, orm
import openerp.addons.decimal_precision as dp
class PurchaseOrderLine(orm.Model):
_inherit = "purchase.order.line"
def _amount_line(self, cr, uid, ids, field_name, arg, context=None):
res = {}
cur_obj = self.pool['res.currency']
tax_obj = self.pool['ac... |
from __future__ import division, print_function, absolute_import
__all__ = ['expm','expm2','expm3','cosm','sinm','tanm','coshm','sinhm',
'tanhm','logm','funm','signm','sqrtm',
'expm_frechet', 'expm_cond', 'fractional_matrix_power']
from numpy import (Inf, dot, diag, exp, product, logical_not, cast... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['deprecated'],
'supported_by': 'community'}
DOCUMENTATION = '''
module: sf_volume_access_group_manager
deprecated:
removed_in: "2.11"
... |
"""Provides the task panel code for the Draft SelectPlane tool.
As it is right now this code only loads the task panel .ui file.
All logic on how to use the widgets is located in the GuiCommand class
itself.
On the other hand, the newer tools introduced in v0.19 like OrthoArray,
PolarArray, and CircularArray include th... |
'''
Cisco IOS only
Requires scp https://github.com/jbardin/scp.py
'''
from netmiko import ConnectHandler, SCPConn
from SECRET_DEVICE_CREDS import cisco_881
def main():
'''
SCP transfer cisco_logging.txt to network device
Use ssh_conn as ssh channel into network device
scp_conn must be closed after file ... |
import time
import random
from multiprocess import current_process as currentProcess, Process, freeze_support as freezeSupport
from multiprocess import Queue
def worker(input, output):
for func, args in iter(input.get, 'STOP'):
result = calculate(func, args)
output.put(result)
def calculate(func, ar... |
"""Utilities for OAuth.
Utilities for making it easier to work with OAuth 2.0
credentials.
"""
import os
import threading
from oauth2client import client
__author__ = 'jcgregorio@google.com (Joe Gregorio)'
class CredentialsFileSymbolicLinkError(Exception):
"""Credentials files must not be symbolic links."""
class S... |
"""
The class task_gen encapsulates the creation of task objects (low-level code)
The instances can have various parameters, but the creation of task nodes (Task.py)
is delayed. To achieve this, various methods are called from the method "apply"
The class task_gen contains lots of methods, and a configuration table:
* ... |
from __future__ import absolute_import
import code
import traceback
import signal
from types import FrameType
from typing import Optional
def interactive_debug(sig, frame):
# type: (int, FrameType) -> None
"""Interrupt running process, and provide a python prompt for
interactive debugging."""
d = {'_fra... |
from __future__ import unicode_literals
from guessit import UnicodeMixin, base_text_type, u
from guessit.fileutils import load_file_in_same_dir
import logging
__all__ = [ 'Country' ]
log = logging.getLogger(__name__)
_iso3166_contents = load_file_in_same_dir(__file__, 'ISO-3166-1_utf8.txt')
country_matrix = [ l.strip()... |
import glob, string, os, sys
from ElementTree import ElementTree, Element
NS_XHTML = "{http://www.w3.org/1999/xhtml}"
def tidy(file, new_inline_tags=None):
command = ["tidy", "-qn", "-asxml"]
if new_inline_tags:
command.append("--new-inline-tags")
command.append(string.join(new_inline_tags, ",")... |
"""
Small, simple and powerful template-engine for Python.
A template-engine for Python, which is very simple, easy to use, small,
fast, powerful, modular, extensible, well documented and pythonic.
See documentation for a list of features, template-syntax etc.
:Version: 0.3.0
:Requires: Python >=2.6 / 3.x
:Usage:
... |
from __future__ import print_function, division
from sympy import Integer
from sympy.core.compatibility import is_sequence
from threading import RLock
try:
from pyglet.gl import *
except ImportError:
raise ImportError("pyglet is required for plotting.\n "
"visit http://www.pyglet.org/")
fr... |
"""An implementation of the Web Site Process Bus.
This module is completely standalone, depending only on the stdlib.
Web Site Process Bus
--------------------
A Bus object is used to contain and manage site-wide behavior:
daemonization, HTTP server start/stop, process reload, signal handling,
drop privileges, PID file... |
"""The gradient of the tutorial zero_out op."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.python.framework import ops
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import sparse_ops
@ops.RegisterGradient("ZeroOut... |
"""
Provides access to HDFS using the :py:class:`HdfsTarget`, a subclass of :py:class:`~luigi.target.Target`.
"""
import luigi
import random
import warnings
from luigi.target import FileSystemTarget
from luigi.contrib.hdfs.config import tmppath
from luigi.contrib.hdfs import format as hdfs_format
from luigi.contrib.hdf... |
import unittest
from scrapy.responsetypes import responsetypes
from scrapy.http import Response, TextResponse, XmlResponse, HtmlResponse, Headers
class ResponseTypesTest(unittest.TestCase):
def test_from_filename(self):
mappings = [
('data.bin', Response),
('file.txt', TextResponse),... |
"""
categories: Core,Classes
description: Calling super() getter property in subclass will return a property object, not the value
cause: Unknown
workaround: Unknown
"""
class A:
@property
def p(self):
return {"a":10}
class AA(A):
@property
def p(self):
return super().p
a = AA()
print(a.... |
'''
mavlink python utility functions
Copyright Andrew Tridgell 2011
Released under GNU GPL version 3 or later
'''
import socket, math, struct, time, os, fnmatch, array, sys, errno
from math import *
from mavextra import *
if os.getenv('MAVLINK10'):
import mavlinkv10 as mavlink
else:
import mavlink
def evaluate_... |
"""
=============================================================
Receiver Operating Characteristic (ROC) with cross validation
=============================================================
Example of Receiver Operating Characteristic (ROC) metric to evaluate
classifier output quality using cross-validation.
ROC curves... |
import logging
import os
import re
from ctypes import CDLL, CFUNCTYPE, c_char_p, c_int
from ctypes.util import find_library
from django.contrib.gis.gdal.error import GDALException
from django.core.exceptions import ImproperlyConfigured
logger = logging.getLogger('django.contrib.gis')
try:
from django.conf import se... |
from __future__ import unicode_literals
import webnotes
from webnotes import msgprint, _
import json
import csv, cStringIO
from webnotes.utils import encode, cstr, cint, flt
def read_csv_content_from_uploaded_file(ignore_encoding=False):
if getattr(webnotes, "uploaded_file", None):
with open(webnotes.uploaded_file, ... |
import sys
sys.path.append('..')
from rhn import rpclib
gs = rpclib.GETServer("http://coyote.devel.redhat.com/DOWNLOAD")
gs.set_transport_flags(allow_partial_content=1)
fd = gs.a.b('a', 'b', 'c', offset=9, amount=1)
print fd.read()
print gs.get_response_headers()
print "Status", gs.get_response_status()
print "Reason",... |
from __future__ import unicode_literals
import frappe, random, erpnext
from frappe.utils.make_random import how_many
from frappe.desk import query_report
from erpnext.manufacturing.doctype.workstation.workstation import WorkstationHolidayError
from erpnext.manufacturing.doctype.production_order.test_production_order im... |
r"""
werkzeug.contrib.securecookie
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
This module implements a cookie that is not alterable from the client
because it adds a checksum the server checks for. You can use it as
session replacement if all you have is a user id or something to mark
a logged in user.
... |
import os
import sys
import difflib
import __builtin__
import re
import pydoc
import inspect
import keyword
import unittest
import xml.etree
import test.test_support
from collections import namedtuple
from test.script_helper import assert_python_ok
from test.test_support import (
TESTFN, rmtree, reap_children, capt... |
from __future__ import unicode_literals
import frappe
from frappe.model.document import Document
class QuotationLostReason(Document):
pass |
"""The data layer used during training to train a Fast R-CNN network.
RoIDataLayer implements a Caffe Python layer.
"""
import caffe
from fast_rcnn.config import cfg
from roi_data_layer.minibatch import get_minibatch
import numpy as np
import yaml
from multiprocessing import Process, Queue
class RoIDataLayer(caffe.Laye... |
import numpy as np
from bokeh.document import Document
from bokeh.models import ColumnDataSource, DataRange1d, Plot, LinearAxis, Grid
from bokeh.models.glyphs import MultiLine
from bokeh.plotting import show
N = 9
x = np.linspace(-2, 2, N)
y = x**2
xpts = np.array([-.09, -.12, .0, .12, .09])
ypts = np.array([-.1, .0... |
from django.conf.urls import url, include
from django.contrib import admin
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from oscar.app import application
admin.autodiscover()
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'', include(application.urls)),
url(r'^i18n/',... |
import copy
import gyp.input
import optparse
import os.path
import re
import shlex
import sys
import traceback
debug = {}
DEBUG_GENERAL = 'general'
DEBUG_VARIABLES = 'variables'
DEBUG_INCLUDES = 'includes'
def DebugOutput(mode, message):
if 'all' in gyp.debug.keys() or mode in gyp.debug.keys():
ctx = ('unknown', ... |
"""
Auxiliary transforms mainly to be used by Writer components.
This module is called "writer_aux" because otherwise there would be
conflicting imports like this one::
from docutils import writers
from docutils.transforms import writers
"""
__docformat__ = 'reStructuredText'
from docutils import nodes, languag... |
import unittest
from ctypes import *
import _ctypes_test
class Callbacks(unittest.TestCase):
functype = CFUNCTYPE
def callback(self, *args):
self.got_args = args
return args[-1]
def check_type(self, typ, arg):
PROTO = self.functype.__func__(typ, typ)
result = PROTO(self.callb... |
from kivy.uix.listview import ListView
from kivy.uix.floatlayout import FloatLayout
from kivy.clock import Clock
from kivy.adapters.listadapter import ListAdapter
from kivy.adapters.models import SelectableDataItem
from kivy.uix.listview import ListItemButton
from random import choice
from string import ascii_uppercase... |
import grpc
import route_guide_pb2 as route__guide__pb2
class RouteGuideStub(object):
"""Interface exported by the server.
"""
def __init__(self, channel):
"""Constructor.
Args:
channel: A grpc.Channel.
"""
self.GetFeature = channel.unary_unary(
'/routeguide.RouteGuide/GetFeature',
... |
"""
Test plugin used in L{twisted.test.test_plugin}.
"""
from zope.interface import classProvides
from twisted.plugin import IPlugin
from twisted.test.test_plugin import ITestPlugin
class FourthTestPlugin:
classProvides(ITestPlugin,
IPlugin)
def test1():
pass
test1 = staticmethod(t... |
import mod1
import mod2
print(mod1, mod2) |
"""TestSuite"""
import sys
from . import case
from . import util
__unittest = True
def _call_if_exists(parent, attr):
func = getattr(parent, attr, lambda: None)
func()
class BaseTestSuite(object):
"""A simple test suite that doesn't provide class or module shared fixtures.
"""
_cleanup = True
de... |
"""defines generic type conversion functions, as used in bind and result
processors.
They all share one common characteristic: None is passed through unchanged.
"""
import codecs
import re
import datetime
from . import util
def str_to_datetime_processor_factory(regexp, type_):
rmatch = regexp.match
# Even on py... |
from base64 import b64encode
from hashlib import sha1
import os
def FormatKey(key):
'''Normalize a key by making sure it has a .html extension, and convert any
'.'s to '_'s.
'''
if key.endswith('.html'):
key = key[:-len('.html')]
safe_key = key.replace('.', '_')
return '%s.html' % safe_key
def SanitizeA... |
from Converter import Converter
from Components.Element import cached
class Streaming(Converter):
@cached
def getText(self):
service = self.source.service
if service is None:
return "-NO SERVICE\n"
streaming = service.stream()
s = streaming and streaming.getStreamingData()
if s is None or not any(s):
... |
import unittest
from unittest.test.support import LoggingResult
class Test_FunctionTestCase(unittest.TestCase):
# "Return the number of tests represented by the this test object. For
# TestCase instances, this will always be 1"
def test_countTestCases(self):
test = unittest.FunctionTestCase(lambda: ... |
import os
import os.path
import shutil
import subprocess
import sys
import tempfile
from webkitpy.common.checkout.scm.detection import detect_scm_system
from webkitpy.common.system.executive import ScriptError
class BindingsTests:
def __init__(self, reset_results, generators, executive):
self.reset_results ... |
import os
import sys
from distutils.sysconfig import get_python_lib
from setuptools import find_packages, setup
overlay_warning = False
if "install" in sys.argv:
lib_paths = [get_python_lib()]
if lib_paths[0].startswith("/usr/lib/"):
# We have to try also with an explicit prefix of /usr/local in order t... |
"""LDAP sync related handlers."""
from django.db.models import signals
from django.dispatch import receiver
from modoboa.core import models as core_models
from modoboa.parameters import tools as param_tools
from . import lib
@receiver(signals.post_save, sender=core_models.User)
def sync_ldap_account(sender, instance, c... |
"""Alias related views."""
from django.core.urlresolvers import reverse
from django.db import IntegrityError
from django.shortcuts import render
from django.utils.translation import ugettext as _, ungettext
from django.views import generic
from django.contrib.auth import mixins as auth_mixins
from django.contrib.auth.d... |
"""Convert fimo.txt to a bed file"""
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
import os
import pandas as pd
from ..helpers import filename_extension
def fimo_to_sites(fimo_file):
"""Convert fimo.txt to bed file
fimi.txt columns:
#pattern na... |
"""Read a TSSpredator master table and caclulates the sizes of set
intersections
"""
__description__ = ""
__author__ = "Konrad Foerstner <konrad@foerstner.org>"
__copyright__ = "2014 by Konrad Foerstner <konrad@foerstner.org>"
__license__ = "ISC license"
__email__ = "konrad@foerstner.org"
__version__ = ""
from colle... |
import sys
from system.odyssey2 import Odyssey2
if len(sys.argv) != 3:
print("usage: run.py bios game")
sys.exit(100)
system = Odyssey2()
system.load_bios(sys.argv[1])
system.load_data(sys.argv[2])
system.run() |
import os
import re
import codecs
try:
from setuptools import setup, find_packages
except ImportError:
from distutils.core import setup
def get_metadata(package, field):
"""
Return package data as listed in `__{field}__` in `init.py`.
"""
init_py = codecs.open(os.path.join(package, '__init__.py'... |
from cachel.compat import iteritems
from cachel.base import _Expire
from cachel.wrappers import BaseCacheWrapper, agg_expire
__await__cache = __await__fn = __await__call = __async__call = __async__cache = None
class CacheWrapper(BaseCacheWrapper):
def __call__(__async__call, self, *args, **kwargs):
k = self... |
from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter
from pdfminer.pdfpage import PDFPage
from pt_law_parser.converter import LAOrganizer, LawConverter
def parse_document(file_name):
rsrcmgr = PDFResourceManager(caching=True)
fp = file(file_name, 'rb')
device = LawConverter(rsrcmgr, laparam... |
from django.test import TestCase
from django.contrib.auth.models import User
from sfmmanager.storage_utils import ResourceData, UserData
import os
class AuthUserTestCase(TestCase):
def setUp(self):
#create dummy user
self.user = User.objects.create_user("debug_user", "", "debug_user")
self.u... |
from django import forms
from crumpet.profiles import constants
from django.utils.translation import ugettext_lazy as _
class UserAccountForm(forms.Form):
exchange = forms.ChoiceField(
required=True,
label=_("Exchange"),
choices=constants.CRYPTO_EXCHANGES
)
api_key = forms.CharField(... |
def draw(number):
if number == 0:
return
print "*" * number
draw(number - 1)
print "#" * number
draw(5)
def reverse_draw(number, acc = 1):
if acc == number:
return
print "*" * acc
reverse_draw(number, acc + 1)
print "#" * acc
reverse_draw(5)
def ddraw(number):
m = 1
... |
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Blog',
fields=[
('id', models.AutoField(auto_created=True... |
def unflatten(flat_array):
dex = 0
result = []
while dex < len(flat_array):
current = flat_array[dex]
if current > 2:
result.append(flat_array[dex:dex + current])
dex += current
else:
result.append(current)
dex += 1
return result |
from flask import Blueprint
from .views import get_ranking, simulations
webscraping_blueprint = Blueprint('webscraping',__name__)
webscraping_blueprint.add_url_rule('/get_ranking',view_func=get_ranking)
webscraping_blueprint.add_url_rule('/simulations',view_func=simulations) |
from msrest.service_client import SDKClient
from msrest import Serializer, Deserializer
from msrestazure import AzureConfiguration
from .version import VERSION
from .operations.gateway_operations import GatewayOperations
from .operations.node_operations import NodeOperations
from .operations.session_operations import S... |
from ._batch_ai import BatchAI
from ._version import VERSION
__version__ = VERSION
__all__ = ['BatchAI']
try:
from ._patch import patch_sdk # type: ignore
patch_sdk()
except ImportError:
pass |
"""Example running MemN2N on a single bAbI task.
Download tasks from facebook.ai/babi """
from __future__ import absolute_import
from __future__ import print_function
from data_utils import load_task, vectorize_data
from sklearn import cross_validation, metrics
from memn2n import MemN2N
from itertools import chain
from... |
import hashlib
import requests
import os
import time
__author__ = 'Qubasa'
def GitHash(data):
sha1 = hashlib.sha1()
sha1.update("blob %u\0" % len(data))
sha1.update(data)
return sha1.hexdigest()
def CreateFile(filename):
if not os.path.isfile(filename):
f = open(filename, 'wb')
f.clo... |
from __future__ import division
from __future__ import print_function
import weakref
from typing import List
import numpy as np
import pyqtgraph as pg
from six.moves import range
from acq4 import getManager
from acq4.devices.Device import Device
from acq4.devices.OptomechDevice import OptomechDevice
from acq4.devices.S... |
from nose.tools import *
from dateutil.parser import parse as time_parse
import yawhois
class TestWhoisNicDzStatusAvailable(object):
def setUp(self):
fixture_path = "spec/fixtures/responses/whois.nic.dz/status_available.txt"
host = "whois.nic.dz"
part = yawhois.record.Part(op... |
"""
[2017-09-06] Challenge #330 [Intermediate] Check Writer
https://www.reddit.com/r/dailyprogrammer/comments/6yep7x/20170906_challenge_330_intermediate_check_writer/
Given a dollar amount between 0.00 and 999,999.00, create a program that will provide a worded representation of a
dollar amount on a check.
You will be ... |
import unittest
from jstypes import named_accessor_property, types
class NamedAccessorPropertyTest(unittest.TestCase):
def test_get_default_is_undefined(self):
prop = named_accessor_property.NamedAccessorProperty()
self.assertIsInstance(prop.get(), types.Undefined)
def test_set_default_is_undefi... |
from __future__ import unicode_literals
from django.core.exceptions import ValidationError
from django.test import TestCase
from accelerator.tests.factories import ProgramCycleFactory
class TestProgramCycle(TestCase):
def test_program_cycle_requires_default_application_type(self):
with self.assertRaises(Val... |
import os
import requests
import json
from flask import Flask, request, Response, redirect, send_file, json
import giphypop
from giphypop import translate
from slacker import Slacker
token = 'SLACK_TOKEN'
slack = Slacker(token)
app = Flask(__name__)
key = 'dc6zaTOxFJmzC' #Giphy public key
g = giphypop.Giphy(api_key=key... |
from . import sizedistribution
import matplotlib.pylab as plt
import numpy as np
import pandas as pd
from scipy import signal
from scipy import optimize
from ...tools import math_functions
def fit_normal_dist(sd, log=True, p0=[10, 180, 0.2], boundary_width = [0.1, 0.6]):
"""Fits a normal distribution to a """
i... |
"""create device name lat long enabled and otaa columns
Revision ID: 282e6b269222
Revises: 03fabc9f542b
Create Date: 2017-02-04 17:28:33.947208
"""
from alembic import op
import sqlalchemy as sa
revision = '282e6b269222'
down_revision = '03fabc9f542b'
branch_labels = None
depends_on = None
def upgrade():
op.add_col... |
"""
A simple test script and general scratch area.
"""
import numpy as np
from scipy import signal
import matplotlib.pyplot as plt
import scipy.linalg as LA
import control_plot, control_sim, control_design, control_optimize, control_eval, control_poles
"""
A = [ [0, 1, 0],
[0, -1, 1],
[0, 0, -4]]
... |
from __future__ import unicode_literals
import unittest
from calmjs.parse.asttypes import Node
from calmjs.parse.unparsers.base import logger
from calmjs.parse.unparsers.base import BaseUnparser
from calmjs.parse.unparsers.walker import Dispatcher
from calmjs.parse.handlers.core import token_handler_str_default
from ca... |
"""
mindhcollar.py
Contains a collar from a mindh database.
For more information see: https://github.com/cokrzys/mindh2jsondh
Copyright (C) 2015 cokrzys
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Soft... |
from __future__ import division
import numpy as np
__all__ = [
'defaultlearner',
'svm_simple',
'feature_selection_simple',
]
def defaultlearner(mode='medium', multi_strategy='1-vs-1', expanded=False):
'''
learner = defaultlearner(mode='medium')
Return the default classifier learner
This ... |
import sys,pprint
from pysideuic import compileUi
import maya.cmds as mc
import maya.mel as mel
import maya.OpenMaya as om
import pymel.core as pm
def pysdieConvert():
"""
@convert ui file to the python file
"""
uiPath = mc.fileDialog2(ff="*ui",dialogStyle=1,fileMode=1)[0]
pyPath = uiPath.replace(".ui","_ui.py")
... |
import sys
import time
barWidth = 40
class ProgressBar:
"""
Provides a simple progress bar class
"""
def __init__(self, nsteps, width=barWidth):
self._start = self._stop = time.time()
self._nsteps = nsteps
self._width = width
self._status = ""
def update(self, step, t... |
"""Formatting helpers."""
__verbose = False
__coloured = True
class Colour:
green = '\033[92m'
yellow = '\033[93m'
red = '\033[91m'
bold = '\033[1m'
end = '\033[0m'
def green(msg) -> str:
formatted = str(msg)
if __coloured:
formatted = Colour.green + formatted + Colour.end
return... |
import unittest
from langner.parser import parser
from langner.ast import Object
class SyntaxTests(unittest.TestCase):
def testEmpty(self):
self.check("")
def testBasic(self):
self.check('(x.a)->(new y);(x.a)->(new y);')
def testBinary(self):
self.check('(x || x.a)->(new y);')
... |
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('cosine', '0001_initial'),
]
operations = [
migrations.RemoveField(
model_name='cosinesimilarity_songtitle',
name='updated_at',
),... |
import unittest
from nanomsg import errors
from nanomsg.constants import Error
class ErrorsTest(unittest.TestCase):
def test_errors(self):
varz = vars(errors)
lookup_table = varz['_ERRORS']
for error in Error:
self.assertIn(error.name, errors.__all__)
self.assertIn(er... |
"""Support for the Netatmo camera lights."""
from __future__ import annotations
import logging
from typing import Any, cast
import pyatmo
from homeassistant.components.light import LightEntity
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant, callback
from homeassistant.... |
"""
Swaggy Jenkins
Jenkins API clients generated from Swagger / Open API specification # noqa: E501
The version of the OpenAPI document: 1.1.2-pre.0
Contact: blah@cliffano.com
Generated by: https://openapi-generator.tech
"""
import re # noqa: F401
import sys # noqa: F401
from swaggyjenkins.model_... |
import logging
import json
import tornado.web
from ..models.user import User
from backend.sys_database.database import create_db_object
paths = (r'auth/login_page.html',)
actions = ['login', 'logout'] #nie zmieniac kolejnosci. mozna nazwe
class AuthenticationHandler(tornado.web.RequestHandler):
def __init__(self,... |
"""
Based on http://www.djangosnippets.org/snippets/595/
by sopelkin
"""
from django import forms
from django.forms import widgets
from django.contrib.auth.models import User
from django.utils.translation import ugettext_lazy as _
class CommaSeparatedUserInput(widgets.Input):
input_type = 'text'
def render(self... |
'''
- Leetcode problem: 973
- Difficulty: Medium
- Brief problem description:
We have a list of points on the plane. Find the K closest points to the origin (0, 0).
(Here, the distance between two points on a plane is the Euclidean distance.)
You may return the answer in any order. The answer is guaranteed to be uniq... |
from ethereum.slogging import getLogger
from ethereum.utils import big_endian_to_int
from raiden.encoding import messages, signing
from raiden.encoding.format import buffer_for
from raiden.encoding.signing import recover_publickey
from raiden.utils import publickey_to_address, sha3, ishash, pex
from raiden.transfer.sta... |
import tensorflow as tf
from tensorflow.models.rnn import rnn, rnn_cell, seq2seq
from tensorflow.python.platform import gfile
import numpy as np
import sys
import os
import nltk
from six.moves import xrange
import models.chatbot
import util.hyperparamutils as hyper_params
import util.vocabutils as vocab_utils
_buckets ... |
from jsb.contrib import feedparser
from jsb.lib.version import getversion
from jsb.lib.plugins import plugs
from google.appengine.api import urlfetch
from google.appengine.api import xmpp
from google.appengine.ext import db
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_ap... |
import sys;
import math;
class EvalueParams:
def __init__(self, values=None):
if (values == None):
self.match = 0;
self.mismatch = 0;
self.gap_open = 0;
self.gap_extend = 0;
self.Lambda = 0;
self.K = 0;
self.H = 0;
self.Alpha = 0;
self.Beta = 0;
self.Theta = 0;
else:
self.match = v... |
import collections
import contextlib
import logging
import pygame
from pyradiator.app_state import ApplicationState
from pyradiator.command_line_args import get_configuration
from pyradiator.command_line_args import is_quiet_mode
from pyradiator.common import PrintText
from pyradiator.common import create_font
from pyr... |
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Deleting field 'Tank.com_tr'
db.delete_column(u'machine_tank', 'com_tr')
# Deleting field ... |
"""
Convert a non-negative integer to its english words representation. Given input is guaranteed to be less than 2^31 - 1.
For example,
123 -> "One Hundred Twenty Three"
12345 -> "Twelve Thousand Three Hundred Forty Five"
1234567 -> "One Million Two Hundred Thirty Four Thousand Five Hundred Sixty Seven"
"""
__author__... |
from setuptools import setup
setup(
name='daspos-umbrella',
version='0.4.0',
packages=['umbrella'],
url='https://github.com/crcresearch/daspos-umbrella',
license='MIT License',
author='Center for Research Computing, University of Notre Dame',
author_email='CRCSupport@nd.edu',
description... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.