code stringlengths 1 199k |
|---|
from .features import Dictionary, RegexMatches, Stemmed, Stopwords
name = "dutch"
try:
import enchant
dictionary = enchant.Dict("nl")
except enchant.errors.DictNotFoundError:
raise ImportError("No enchant-compatible dictionary found for 'nl'. " +
"Consider installing 'myspell-nl'.")
d... |
from carepoint import Carepoint
from sqlalchemy import (Column,
Integer,
Boolean,
ForeignKey,
)
class FdbPemMogc(Carepoint.BASE):
__tablename__ = 'fdrpemogc'
__dbname__ = 'cph'
gcn_seqno = Column(
Integer... |
from .sanic import Sanic
from .blueprints import Blueprint
__version__ = '0.1.9'
__all__ = ['Sanic', 'Blueprint'] |
import time
import os
from itertools import product
import numpy as np
from sklearn.cross_validation import KFold
import theano
from theano import tensor as T
import lasagne
from params import nnet_params_dict, feats_train_folder
def set_trace():
from IPython.core.debugger import Pdb
import sys
Pdb(color_sc... |
import os
import types
import binascii
from django.db import models
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from django.utils.functional import cached_property
try:
from django.utils.encoding import smart_text
except ImportError:
from django.utils.encoding import... |
def crawl_folder(folder):
import os
os_objects = []
seen = set([folder])
for os_object_name in os.listdir(folder):
full_path = os.path.normpath(os.path.join(folder, os_object_name))
if not full_path in seen:
os_objects.append((full_path, os_object_name,))
seen.add... |
import io
from pytest import fixture
class _FakeOutputFile(io.StringIO):
def close(self):
self.contents = self.getvalue()
super().close()
@fixture
def fake_output_file():
return _FakeOutputFile()
type_example_values = {
"none": (None,),
"callable": (lambda: None,),
"bool": (True, Fal... |
"""A setuptools based setup module.
See:
https://packaging.python.org/en/latest/distributing.html
https://github.com/pypa/sampleproject
"""
from setuptools import setup, find_packages
from codecs import open
from os import path
here = path.abspath(path.dirname(__file__))
from sqrlserver import __version__
with open(pat... |
"""Regression tests."""
from __future__ import print_function
from __future__ import unicode_literals
from tabulate import tabulate, _text_type, _long_type, TableFormat, Line, DataRow
from common import assert_equal, assert_in, skip
def test_ansi_color_in_table_cells():
"Regression: ANSI color in table cells (issue... |
import json
with open("birthdays.json", "r") as damnJson:
birthDays = json.load(damnJson)
print("We know the birth days of: ")
for i in birthDays:
print(i)
print("\nWould you like to add or retrieve a birth day?")
lol = input().strip().lower()
if lol == "add":
person = input("Who's the lucky one? ")
date = input("W... |
"""
Tests whether we can compute a consistent gradient of some functional
based on the forward model with respect to the bottom friction
via firedrake_adjoint.
Stephan Kramer 25-05-16
"""
import pytest
from thetis import *
from firedrake_adjoint import *
op2.init(log_level=INFO)
velocity_u = 2.0
def basic_setup():
... |
import codecs
import os
import re
import sys
from setuptools import setup, find_packages
from setuptools.command.test import test as TestCommand
here = os.path.abspath(os.path.dirname(__file__))
class PyTest(TestCommand):
def finalize_options(self):
TestCommand.finalize_options(self)
self.test_args ... |
from .context import CorpusContext
from .audio import AudioContext
from .importable import ImportContext
from .lexical import LexicalContext
from .pause import PauseContext
from .utterance import UtteranceContext
from .structured import StructuredContext
from .syllabic import SyllabicContext
from .spoken import SpokenC... |
import datetime
import json
import logging
import pprint
import dateutil.parser
import sqlalchemy
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import (relationship, scoped_session, sessionmaker,
validates)
import fbd.tools
def default_json_serializer(obj):
... |
from django.http import HttpResponse
from django.views.generic import TemplateView, DetailView
from django.views.generic.edit import FormView
from .forms import DonationForm
from .models import CardType
import json
class PagoView(FormView):
form_class = DonationForm
template_name = 'pago.html'
success_url =... |
"""Setup/installation tests for this package."""
from ade25.assetmanager.testing import IntegrationTestCase
from plone import api
class TestInstall(IntegrationTestCase):
"""Test installation of ade25.assetmanager into Plone."""
def setUp(self):
"""Custom shared utility setup for tests."""
self.p... |
from lit.main import main
import os
if __name__ == '__main__':
if not os.path.exists(".cache/core.Item"):
print("Note that first run may take quite a while .cache/core.* is populated...")
main() |
s = input().rstrip()
print(s[:4],s[4:]) |
import math
import unicodedata as uda
from binascii import unhexlify, hexlify
from torba.rpc.jsonrpc import RPCError
from torba.server.hash import hash_to_hex_str
from torba.server.session import ElectrumX
from torba.server import util
from lbry.schema.result import Outputs
from lbry.schema.url import URL
from lbry.wal... |
import click
import newsfeeds
import random
import sys
from config import GlobalConfig
def mixer(full_story_list, sample_number):
"""Selects a random sample of stories from the full list to display to the user.
Number of stories is set in config.py
Todo: Add argument support for number of stories to display... |
from mymodule import *
sayhi() |
from PyQt5 import Qt
from ..shared_resources import UNIQUE_QGRAPHICSITEM_TYPE
class PointItem(Qt.QGraphicsRectItem):
# Omitting .type() or failing to return a unique causes PyQt to return a wrapper of the wrong type when retrieving an instance of this item as a base
# class pointer from C++. For example, if th... |
import serial
import sys
from time import sleep
def move(dir):
print dir
ser.write(dir) # write a string
ser.sendBreak(0.25)
ser.flush()
sleep(1)
def ResetCoords():
dir = 'r'
print dir
ser.write(dir) # write a string
ser.sendBreak(0.25)
ser.flush()
sleep(1)
def DrawRect(dim):
print ""
print "Dr... |
"""TreeNode operation to find next node."""
import threading
from src.core import tree
from src.ops import abstract
class NextNodeOp(abstract.AbstractOp):
"""Finds next TreeNode instance in the tree in in-order traversal."""
def do(self, root, args):
"""Implements NextNodeOp.
See http://www.geeksforgeeks.or... |
"""
homeassistant.components.media_player.chromecast
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Provides functionality to interact with Cast devices on the network.
WARNING: This platform is currently not working due to a changed Cast API
"""
import logging
from homeassistant.const import (
STATE_PLAYING, STA... |
"""Order a block storage replica volume."""
import click
import SoftLayer
from SoftLayer.CLI import environment
from SoftLayer.CLI import exceptions
CONTEXT_SETTINGS = {'token_normalize_func': lambda x: x.upper()}
@click.command(context_settings=CONTEXT_SETTINGS)
@click.argument('volume_id')
@click.option('--snapshot-s... |
import time
import rlp
import trie
import db
import utils
import processblock
import transactions
import logging
import copy
import sys
from repoze.lru import lru_cache
logger = logging.getLogger()
INITIAL_DIFFICULTY = 2 ** 17
GENESIS_PREVHASH = '\00' * 32
GENESIS_COINBASE = "0" * 40
GENESIS_NONCE = utils.sha3(chr(42))... |
from .stackapi import StackAPI
from .stackapi import StackAPIError |
from django.conf import settings
from django.core import mail
from django.test import RequestFactory
from django.test import TestCase
from django.contrib.sites.models import Site
from contact_form.forms import ContactForm
class ContactFormTests(TestCase):
def test_request_required(self):
"""
Can't i... |
'''
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
Jetduino for the Jetson TK1/TX1: an open source platform for connecting
Grove Sensors to the Jetson embedded supercomputers.
Copyright (C) 2016 NeuroRo... |
"""Common profiles are defined here to be easily used within a project using --profile {name}"""
from typing import Any, Dict
black = {
"multi_line_output": 3,
"include_trailing_comma": True,
"force_grid_wrap": 0,
"use_parentheses": True,
"ensure_newline_before_comments": True,
"line_length": 88... |
from django.core.exceptions import ValidationError
from amweekly.slack.tests.factories import SlashCommandFactory
import pytest
pytest.mark.unit
def test_slash_command_raises_with_invalid_token(settings):
settings.SLACK_TOKENS = ''
with pytest.raises(ValidationError):
SlashCommandFactory() |
from collections import namedtuple
Payload = namedtuple('Payload', ['iden', 'body', 'send_date', 'sender'])
class Handler(object):
@staticmethod
def config():
return
def __init__(self, logger):
self.logger = logger
def create_translator():
return
def create_listener(task):
... |
__author__ = 'leif'
import os
import socket
import logging
import logging.config
import logging.handlers
from autocomplete_trie import AutocompleteTrie
from ifind.search.engines.whooshtrec import Whooshtrec
from experiment_setup import ExperimentSetup
work_dir = os.getcwd()
my_whoosh_doc_index_dir = os.path.join(work_d... |
import unittest
from .context import json_stable_stringify_python as stringify
class TestStringify(unittest.TestCase):
def test_simple_object(self):
node = {'c':6, 'b': [4,5], 'a': 3, 'z': None}
actual = stringify.stringify(node)
expected = '{"a":3,"b":[4,5],"c":6,"z":null}'
self.ass... |
import datetime
import os
import uuid
from django.conf import settings
from django.core.exceptions import ObjectDoesNotExist
from django.db import models
from django.urls import reverse
from django.utils import timezone
from django.utils.translation import ugettext_lazy as _
from pinax.invitations.models import JoinInv... |
import socket
import random
SERVERHOST = 'localhost'
SERVERPORT = 4080
LOCALIP = '127.0.0.2'
LOCALPORT = 4082
LOCALNAME = "30_PERCENT_SEE"
def higher(dice_a, dice_b):
ad1, ad2 = dice_a[0], dice_a[1]
bd1, bd2 = dice_b[0], dice_b[1]
if ad1 == bd1 and ad2 == bd2: return False
if ad1 == "2" and ad2 == "1": return T... |
import os
os.system('git add -A && git commit -m "Working on changes in my website (Amaia)" && git push origin master'); |
"""Tests for hermite_e module.
"""
from __future__ import division, absolute_import, print_function
import numpy as np
import numpy.polynomial.hermite_e as herme
from numpy.polynomial.polynomial import polyval
from numpy.testing import (
TestCase, assert_almost_equal, assert_raises,
assert_equal, assert_, run_m... |
import floq.core.fixed_system as fs
import floq.evolution as ev
import floq.errors as er
import floq.helpers.index as h
class ParametricSystemBase(object):
"""
Base class to specify a physical system that still has open parameters,
such as the control amplitudes, the control duration, or other arbitrary
... |
from qgis.core import QgsMapLayerRegistry, QgsGeometry, QgsField, QgsFeature, QgsPoint
from PyQt4.QtCore import QVariant
def getAllbbox(layer, width, height, srid, overlap):
for feature in layer.selectedFeatures():
geom = feature.geometry()
if geom.type() <> QGis.Line:
print "Geometry ty... |
from django.conf import settings
from django.conf.urls import url
from plans.views import CreateOrderView, OrderListView, InvoiceDetailView, AccountActivationView, \
OrderPaymentReturnView, CurrentPlanView, UpgradePlanView, OrderView, BillingInfoRedirectView, \
BillingInfoCreateView, BillingInfoUpdateView, Bill... |
from handlers import Handler
from models import User
class Login(Handler):
def get(self):
self.render('login-form.html')
def post(self):
username = self.request.get('username')
password = self.request.get('password')
u = User.login(username, password)
if u:
se... |
import unittest
import json
import sys
try:
from unittest.mock import Mock
except ImportError:
from mock import Mock
import requests
from tabpy_client.rest import *
class TestRequestsNetworkWrapper(unittest.TestCase):
def test_init(self):
rnw = RequestsNetworkWrapper()
def test_init_with_session... |
__all__ = ['DAObject', 'DAList', 'DADict', 'DAOrderedDict', 'DASet', 'DAFile', 'DAFileCollection', 'DAFileList', 'DAStaticFile', 'DAEmail', 'DAEmailRecipient', 'DAEmailRecipientList', 'DATemplate', 'DAEmpty', 'DALink', 'RelationshipTree', 'DAContext']
from docassemble.base.util import DAObject, DAList, DADict, DAOrdere... |
"""
Basic utility functions
"""
import redislite
from .server import RDB_FILE
def header(message, width=80):
header_message = '## ' + message + ' '
end_chars = width - (len(message) + 4)
header_message += '#'*end_chars
print(header_message)
def connect_to_redis():
return redislite.Redis(dbfilename=R... |
CATKIN_PACKAGE_PREFIX = ""
PROJECT_PKG_CONFIG_INCLUDE_DIRS = "".split(';') if "" != "" else []
PROJECT_CATKIN_DEPENDS = "".replace(';', ' ')
PKG_CONFIG_LIBRARIES_WITH_PREFIX = "".split(';') if "" != "" else []
PROJECT_NAME = "hector_imu_tools"
PROJECT_SPACE_DIR = "/home/trevor/ROS/catkin_ws/devel"
PROJECT_VERSION = "0.... |
import unittest
import os
import random
import numpy as np
from pymatgen.core.structure import Structure
from pymatgen.core.lattice import Lattice
from pymatgen.core.surface import Slab, SlabGenerator, generate_all_slabs, \
get_symmetrically_distinct_miller_indices
from pymatgen.symmetry.groups import SpaceGroup
fr... |
import unittest
import datetime
from cwr.parser.encoder.dictionary import ComponentDictionaryEncoder
from cwr.work import ComponentRecord
"""
ComponentRecord to dictionary encoding tests.
The following cases are tested:
"""
__author__ = 'Bernardo MartΓnez Garrido'
__license__ = 'MIT'
__status__ = 'Development'
class Te... |
from django.db import models
from django.utils.translation import ugettext_lazy as _
from cms.models.pluginmodel import CMSPlugin
from djangocms_text_ckeditor.fields import HTMLField
from easy_thumbnails.alias import aliases
from easy_thumbnails.signals import saved_file
from easy_thumbnails.signal_handlers import gene... |
import struct
from common import *
from objects import ObjectAppType
from bcddevice import BCDDevice
ElementClass = enum(Library=0x1,
Application=0x2,
Device=0x3,
Hidden=0x4)
ElementFormat = enum(Unknown=0,
Device=1,
S... |
from unittest import TestCase
from stm.configuration import Configuration
from stm.image import Image
import os, os.path
class Test_filename(TestCase):
def checkImage(self, input, output):
img = Image(self.conf)
img.loadImage(input)
self.assertEqual(img.getThumbnailName(), output)
def se... |
import pymongo
from pprint import pprint
def mongo_conn(db, collection):
conn = pymongo.MongoClient('localhost', 27017)
db_conn = conn[db]
coll_conn = db_conn[collection]
print coll_conn
return coll_conn
def list_and_count(coll_field, coll_conn, display_limit=10):
a = list(coll_conn.aggregate(
... |
from base import Problem
class Solution(Problem):
def solve(self, input_):
numberLargest = 0
for a in range(1, 100):
if a % 10 != 0:
for b in range(1, 100):
num_pow = a**b
number_sum = self.digits_sum(num_pow)
if... |
from __future__ import unicode_literals
import frappe
import HTMLParser
import smtplib, quopri
from frappe import msgprint, throw, _
from frappe.email.smtp import SMTPServer, get_outgoing_email_account
from frappe.email.email_body import get_email, get_formatted_html
from frappe.utils.verified_command import get_signed... |
import os
import click
from chado import ChadoInstance
from chakin.cli import pass_context
from chakin import config
from chakin.io import warn, info
CONFIG_TEMPLATE = """## Chado's chakin: Global Configuration File.
__default: local
local:
dbhost: "%(dbhost)s"
dbname: "%(dbname)s"
dbuser: "%(dbuser)s"
... |
"""
** marun flavor: compoom **
usage: compoom=/path/to/append.script
add parameter -XX:OnOutOfMemoryError=
"""
import util
def apply(conf, currentflags, flavor_conf):
compressor = flavor_conf.get('compressor', 'gzip,lz4 --rm')
for cmd in compressor.split(','):
cmds = cmd.split()
if util.find_c... |
from flask import Flask
from flask.ext.bootstrap import Bootstrap
from flask.ext.mail import Mail
from flask.ext.moment import Moment
from flask.ext.sqlalchemy import SQLAlchemy
from flask.ext.login import LoginManager
from flask.ext.pagedown import PageDown
from config import config
import os
bootstrap = Bootstrap()
m... |
"""Test transaction signing using the signrawtransaction* RPCs."""
from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import assert_equal, assert_raises_rpc_error
class SignRawTransactionsTest(BitcoinTestFramework):
def set_test_params(self):
self.setup_clean_chain = Tru... |
"""REANA client validation utilities."""
import sys
from typing import Dict, NoReturn, Union
import click
from reana_commons.errors import REANAValidationError
from reana_commons.validation.operational_options import validate_operational_options
from reana_commons.validation.utils import validate_reana_yaml, validate_w... |
from .util import Spec
class Port(Spec):
STATES = [
"listening", "closed", "open",
"bound_to",
"tcp", "tcp6", "udp"
]
def __init__(self, portnumber):
self.portnumber = portnumber
self.get_state()
self.state = {
'state': 'closed',
'bound... |
__version__ = '0.3.0' |
"""
To create an Attribute Editor template using python, do the following:
1. create a subclass of `uitypes.AETemplate`
2. set its ``_nodeType`` class attribute to the name of the desired node type, or name the class using the
convention ``AE<nodeType>Template``
3. import the module
AETemplates which do not meet on... |
from rpython.rlib import jit
import interpret
import parse
import kernel_type as kt
def entry_point(argv):
jit.set_param(None, "trace_limit", 20000)
interpret.run(argv)
return 0
def target(driver, args):
return entry_point, None |
import pytest
from playlog.lib.json import Encoder
def test_encoder():
encoder = Encoder()
with pytest.raises(TypeError):
encoder.default(object()) |
class Solution(object):
def strStr(self, haystack, needle):
"""
:type haystack: str
:type needle: str
:rtype: int
"""
if not needle:
return 0
if len(haystack) < len(needle):
return -1
for i in xrange(len(haystack)):
if i + le... |
import os
import json
class FakeResponse(object):
status_code = 200
text = None
headers = []
def __init__(self, text):
self.text = text
def json(self):
return json.loads(self.text)
def response(name):
content = open(os.path.join(os.path.dirname(__file__), 'responses', name)).read()
return FakeResponse(conten... |
import numpy as np
def gauss(win, sigma):
x = np.arange(0, win, 1, float)
y = x[:,np.newaxis]
x0 = y0 = win // 2
g=1/(2*np.pi*sigma**2)*np.exp((((x-x0)**2+(y-y0)**2))/2*sigma**2)
return g
def gaussx(win, sigma):
x = np.arange(0, win, 1, float)
y = x[:,np.newaxis]
x0 = y0 = win // 2
g... |
'''
'roi_gcibs.py' compares two groups informed by an a priori bootstrap analysis.
'''
import os
import sys
import argparse
import tempfile, shutil
import json
import pprint
import copy
from collections import defaultdict
from _common import systemMisc as misc
from _common ... |
from collections import UserList
from copy import copy
from npc.util import print_err
class Tag(UserList):
"""
Defines a mult-value tag object
"""
def __init__(self, name: str, *args, required: bool=False, hidden: bool=False, limit: int=-1):
"""
Create a new Tag object
Args:
... |
"""srt URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.10/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based v... |
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('blog', '0006_auto_20160321_1527'),
]
operations = [
migrations.CreateModel(
name='Blog',
fields=... |
from contextlib import contextmanager
@contextmanager
def failnow():
try:
yield
except Exception:
import sys
sys.excepthook(*sys.exc_info())
sys.exit(1) |
"""
Qxf2 Services: A plug-n-play class for logging.
This class wraps around Python's loguru module.
"""
import os, inspect
import pytest,logging
from loguru import logger
from pytest_reportportal import RPLogger, RPLogHandler
class Base_Logging():
"A plug-n-play class for logging"
def __init__(self,log_file_nam... |
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "maiziblog2.settings")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv) |
'''
"jscompile" plugin for cocos command line tool
'''
__docformat__ = 'restructuredtext'
import sys
import subprocess
import os
import json
import inspect
import platform
import cocos
from MultiLanguage import MultiLanguage
class CCPluginJSCompile(cocos.CCPlugin):
"""
compiles (encodes) and minifies JS files
... |
import socket
import struct
import sys
from time import sleep
import logging
class SocketChannelFactory():
'''
Provides method to create channel connection.
'''
def openChannel(self, host, port):
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((host, port))
retur... |
import time
import json
import pprint
import hashlib
import struct
import re
import base64
import httplib
import sys
from multiprocessing import Process
ERR_SLEEP = 15
MAX_NONCE = 1000000L
settings = {}
pp = pprint.PrettyPrinter(indent=4)
class VirtaCoinRPC:
OBJID = 1
def __init__(self, host, port, username, password... |
from django.conf import settings
from mock import Mock
from cabot.cabotapp import defs
from datetime import datetime
def build_absolute_url(relative_url):
"""Prepend https?://host to a url, useful for links going into emails"""
return '{}://{}{}'.format(settings.WWW_SCHEME, settings.WWW_HTTP_HOST, relative_url)... |
'''
alignment utility functions
'''
import os
import sys
import subprocess
import logging
import mmap
import gzip
import multiprocessing
from operator import itemgetter
import numpy as np
def pair_alignment(paths, args):
""" creates the alignment """
# validate parameters.
assert os.path.isdir(args.base_dir... |
from os import remove, mkdir, listdir, rmdir
from os.path import join, expanduser, isdir
from os.path import split as splitdir
import codecs
from shutil import copy2
indir = join(expanduser("~"),"Desktop")
orgdir = ""
bakdir = ""
with codecs.open(join(indir,"_diff.txt"), 'r', encoding='utf8') as diff:
# Read first ... |
from operator import itemgetter
import gym
from gym import spaces
from gym.utils import seeding
from .game import Game
from .card import Card
from .player import PlayerAction, PlayerTools
from .agents.random import AgentRandom
class LoveLetterEnv(gym.Env):
"""Love Letter Game Environment
The goal of hotter cold... |
from datetime import datetime
if not require("attachments"):
raise AssertionError("'forwardMessages' requires 'attachments'")
BASE_SPACER = chr(32) + unichr(183) + chr(32)
def parseForwardedMessages(self, msg, depth=0):
body = ""
if msg.has_key("fwd_messages"):
spacer = BASE_SPACER * depth
body = "\n" + spacer
... |
from .core import Report, ReportResponse
__all__ = [
Report,
ReportResponse,
] |
from flask import Flask
from os.path import expanduser
def create_app():
app = Flask(__name__)
app.config.from_pyfile(expanduser('~/.directory-tools.py'))
from directory_tools.frontend import frontend
app.register_blueprint(frontend)
return app |
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "aalto_fitness.settings")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv) |
__author__ = 'hujin'
import sys
from os import path
from twisted.internet import reactor
from twisted.web import server, resource
from twisted.python import log
from dockerman.storage import ServiceStore
from dockerman.api import Root
from dockerman.docker import Client
from dockerman.manager import Manager
from docker... |
"""Unit tests for reviewboard.diffviewer.models.filediff."""
from itertools import chain
from reviewboard.diffviewer.models import DiffSet, FileDiff
from reviewboard.diffviewer.tests.test_diffutils import \
BaseFileDiffAncestorTests
from reviewboard.testing import TestCase
class FileDiffTests(TestCase):
"""Unit... |
import csv, sys, subprocess
from lib_time import *
def float_to_percentage(float_number):
return("%0.2f" % float_number +"%")
def normalize_dict(dic):
max_elem = max(dic.values())
for key, value in dic.items():
normalized_val = int((100 * value)/max_elem)
if normalized_val == 0:
normalized_val = 1
dic[key]=... |
import time
from datetime import datetime
import zeromq_rx
def printIt(params):
print(datetime.now(),str(params))
if __name__ == "__main__":
zeromq_rx.init(printIt)
print("Watching...")
while True:
time.sleep(1) |
from __future__ import unicode_literals
from django.apps import AppConfig
class SequencerConfig(AppConfig):
name = 'sequencer' |
import urllib.request
import time
def pega_preΓ§o():
pagina = urllib.request.urlopen('http://beans.itcarlow.ie/prices-loyalty.html')
texto = pagina.read().decode('utf8')
onde = texto.find('>$')
inicio= onde + 2
fim = inicio + 4
return float(texto[inicio:fim])
opΓ§Γ£o = input("deseja comprar jΓ‘? (S/... |
import logging
import json
import os
import re
from urlparse import urljoin
from lxml import html
from thready import threaded
import requests
from scrapekit.util import collapse_whitespace
from connectedafrica.scrapers.util import MultiCSV
from connectedafrica.scrapers.util import make_path
log = logging.getLogger('np... |
'''This module contains some glue code encapsulating a "main" process.
The code here is aimed at wrapping the most common tasks involved in creating
and, especially, training a neural network model.
'''
import climate
import datetime
import downhill
import os
import warnings
from . import graph
from . import trainer
lo... |
import unittest
import asyncio
import io
import multiprocessing
import urllib.request
import time
import grole
def simple_server():
app = grole.Grole()
@app.route('/')
def hello(env, req):
return 'Hello, World!'
app.run(host='127.0.0.1')
class TestServe(unittest.TestCase):
def test_simple(se... |
if __package__ is None:
import sys
import os.path
sys.path[0:0] = [
os.path.dirname( # project_root
os.path.dirname( # tests
os.path.abspath(__file__) # this file
)
)
]
import httmock
import pytest
from six import m... |
import django
import time
from uuid import uuid1
from datetime import timedelta
from threading import Thread
from django.template import Template
from django.test import TestCase, TransactionTestCase
from django.contrib.auth.models import User, Group
from django.utils import timezone
from django.core import management,... |
class HTTPError(Exception):
'''
Represents an HTTP Exception when response status code >= 300.
:ivar int status:
the status code of the response
:ivar str message:
the message
:ivar list headers:
the returned headers, as a list of (name, value) pairs
:ivar bytes body:
... |
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('userprofile', '0020_auto_20190507_0150'),
('news', '0019_auto_20190512_1608'),
]
operations = [
migrations.AddField(
model_name='article',
... |
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
import random
char_raw = 'hello_world_good_morning_see_you_hello_great'
char_list = sorted(list(set(char_raw)))
char_to_idx = {c: i for i, c in enumerate(char_list)}
idx_to_char = {i: c for i, c in enumerate(char_list)}
char_data = [char_to_idx[... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.