content string |
|---|
import hashlib
import logging
import datetime
import threading
import xml.etree.cElementTree
class wettercom():
_server = 'api.wetter.com'
"""get city code
returns one or more city code(s) for use in forecast function
"""
def search(self, location):
retval = {}
searchURL = 'ht... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
import unittest
import speech_recognition as sr
class TestRecognition(unittest.TestCase):
def setUp(self):
self.AUDIO_FILE_EN = os.path.join(os.path.dirname(os.path.realpath(__file__)), "english.wav")
self.AUDIO_FILE_FR = os.path.join(os.p... |
import fresh_tomatoes
import media
# Create instances of the class "Movie" in the module "media"
fight_club = media.Movie("Fight Club",
"An insomniac office worker, "
"looking for a way to change his life",
"https://upload.wikimedia.org"
... |
{ 'sequence': 500,
'name' : 'Displays product in hr analytic timesheet'
, 'version' : '0.7'
, 'category' : 'HR'
, 'description' : """
This module displays the hidden field product_id
"""
, 'author' : 'ChriCar Beteiligungs- und Beratungs- GmbH'
, 'depends' : ['hr_timesheet' ]
, 'data' : ['hr_tim... |
from __future__ import print_function
from builtins import object
from mock import *
from atrcopy import SegmentData, AtariDosFile, DefaultSegment, XexContainerSegment, errors
class TestAtariDosFile:
def setup(self):
pass
def test_segment(self):
bytes = np.asarray([0xff, 0xff, 0x00, 0x60, 0... |
from __future__ import print_function, division, absolute_import
import logging
from os.path import exists
from six import string_types
from six.moves import intern
import numpy as np
import pandas as pd
from .attribute_parsing import expand_attribute_strings
from .parsing_error import ParsingError
from .required_col... |
import discord
from discord.ext import commands
from datetime import datetime, timedelta
import asyncio
import pytz
import json
import re
class Time(commands.Cog):
"""
Commands dealing with the passage of time.
"""
def __init__(self, bot):
self.chiaki = bot
# load relevant... |
#!/usr/bin/env python
"""
Some scary shit hapens here...
Parse cleaned compendum text file, with each career page
on new line
"""
import re
import json
def split_literal(line, literal, append=None):
head, sep, tail = line.partition(literal)
if not sep:
raise ValueError('No such literal: {}'.format(li... |
#
# $Id: crc.py 194 2007-04-05 15:31:53Z cameron $
#
from defines import *
class crc:
def __init__(self, parent=None):
self.attributes = {} # initialize attributes
self.attributes["Match"] = 1 # Match attribute set to 1 tells the main program we can... |
from hyperspy.drawing import image
from hyperspy.drawing.mpl_he import MPL_HyperExplorer
from hyperspy.docstrings.plot import PLOT2D_DOCSTRING, KWARGS_DOCSTRING
class MPL_HyperImage_Explorer(MPL_HyperExplorer):
def plot_signal(self,
colorbar=True,
scalebar=True,
... |
from ....const import GRAMPS_LOCALE as glocale
_ = glocale.get_translation().gettext
import logging
LOG = logging.getLogger(".citationfilter")
#-------------------------------------------------------------------------
#
# GRAMPS modules
#
#-------------------------------------------------------------------------
from ... |
''' Provides the ``ServerSession`` class.
'''
#-----------------------------------------------------------------------------
# Boilerplate
#-----------------------------------------------------------------------------
from __future__ import annotations
import logging # isort:skip
log = logging.getLogger(__name__)
#... |
import numpy as np
# Selection function will select parents for next generation based on fitness data
def Tournament(fitness,nParents,args):
'''
Choose best individual based on the Tournament (Default)
'''
tournamentsize = 3
if 'tournamentsize' in args:
tournamentsize = args['tournamentsiz... |
"""Drop OCID tables
Revision ID: 138cb0d71dfb
Revises: 5797389a3842
Create Date: 2017-08-08 11:15:19.821330
"""
import logging
from alembic import op
import sqlalchemy as sa
log = logging.getLogger("alembic.migration")
revision = "138cb0d71dfb"
down_revision = "5797389a3842"
def upgrade():
for table in (
... |
#! /usr/bin/python
import math
import sys
import os
import subprocess
def log_out(out):
print(out[:-1])
def run_proc(p, wait):
if not wait:
pid = os.fork()
if pid != 0:
return
proc = subprocess.Popen(p, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) ... |
from __future__ import absolute_import, division, print_function, \
with_statement
import os
import socket
import struct
import re
import logging
if __name__ == '__main__':
import sys
import inspect
file_path = os.path.dirname(os.path.realpath(inspect.getfile(inspect.currentframe())))
os.chdir(fil... |
"""The tests device sun light trigger component."""
# pylint: disable=protected-access
from datetime import datetime
from asynctest import patch
import pytest
from homeassistant.components import (
device_sun_light_trigger,
device_tracker,
group,
light,
)
from homeassistant.components.device_tracker.c... |
#!/usr/bin/python
import datetime
import hashlib
import json
import logging
import os
import time
from subprocess import call
print "Content-type: text/html"
print
def generate_hashstring(user):
timestamp = datetime.datetime.fromtimestamp(time.time()).strftime('%Y-%m-%d-%H')
hashbase = user['client'] + '&' + ... |
from django.core.exceptions import ObjectDoesNotExist
from django.test import TestCase
from django.urls import reverse
from core.models import ValidationScenario
from tests.utils import TestConfiguration
class ValidationScenarioTestCase(TestCase):
python_validation_payload = """def test_record_has_words(record, ... |
from openerp.osv import fields, orm
DIRECTIONS = [
(0, 'Sinistra (0)'),
(1, '1'),
(2, '2')
]
class account_journal(orm.Model):
_inherit = 'account.journal'
_columns = {
'teamsystem_code': fields.integer('Codice TeamSystem'),
'teamsystem_invoice_position': fields.selection(DIRECTI... |
#!/usr/bin/env python
import sys, os, time
from spaces_config import config
from providers import providers
#from helpers import get_message, make_message
import SocketServer
import toposort
import ipdb
import re
reserved_option_names = ['_uses', '_provider']
def get_config(filepath):
cfg = config.SpacesConfigPa... |
import pygame
import socket
from string import *
import random
import datetime
import time
import obd
UDP_IP = "127.0.0.1"
#UDP_IP = "192.168.0.112"
#UDP_IP="192.168.0.112"
UDP_PORT =5555
sock = socket.socket(socket.AF_INET, # Internet
socket.SOCK_DGRAM) # UDP
sock.bind((UDP_IP, UDP_PORT))
c... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
import urllib2
import time
from datetime import datetime
from bs4 import BeautifulSoup
TXF_NAME = u'臺指現'
TE_NAME = u'電子現'
TF_NAME = u'金融現'
targets = set()
targets.add(TXF_NAME)
targets.add(TE_NAME)
targets.add(... |
#!/usr/bin/env python
# -*- coding: utf8 -*-
# *****************************************************************
# ** PTS -- Python Toolkit for working with SKIRT **
# ** © Astronomical Observatory, Ghent University **
# *****************************************************************
##... |
# Send Weather by Ferran Fabregas <EMAIL>
import random, math
import sys
import time
import re
from twython import Twython
from twython import TwythonStreamer
import subprocess
# Eliza setup
responseStarts = []
responseCurrentIndices = []
responseEnds = []
previousInput = ""
userInput = ""
CONVERSATION_KEYWORDS = ["CA... |
import uuid
from django.contrib.auth.decorators import login_required
from django.core.urlresolvers import reverse
from django.core.urlresolvers import reverse_lazy
from django.shortcuts import render
from django.utils.translation import ugettext as _
from django.views.generic import ListView, DetailView
from django.v... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from enum import IntEnum
__author__ = 'James Iter'
__date__ = '2017/3/22'
__contact__ = '<EMAIL>'
__copyright__ = '(c) 2017 by James Iter.'
class JimVEdition(IntEnum):
standalone = 0
hyper_convergence = 1
class StorageMode(IntEnum):
local = 0
shared_... |
# -*- coding: utf-8 -*-
#歧視無邊,回頭是岸。鍵起鍵落,情真情幻。
# Correction
import os.path, glob
import requests
from lxml.html import fromstring, tostring, parse
from io import StringIO, BytesIO
import codecs
import pandas as pd
import json
XML_encoding="utf-8"
# Data source
URL_ = "https://en.wikipedia.org/wiki/Arab_League"
URL_co... |
import httplib
from cStringIO import StringIO
from urllib2 import urlparse
from cgi import parse_qs
from libcloud.common.base import RawResponse
class multipleresponse(object):
"""
A decorator that allows MockHttp objects to return multi responses
"""
count = 0
func = None
def __init__(self,... |
"""
tests.test_invalid_forms.py
---------------------------
Flask-User automated tests:
Tests all forms with as many invalid field values as possible
:copyright: (c) 2013 by Ling Thio
:author: Ling Thio (<EMAIL>)
:license: Simplified BSD License, see LICENSE.txt for more details.
"""
from ... |
# -*- coding: utf-8 -*-
import enum
import sys
from ast import iter_fields
import six
from . import docstring
from . import types
PY35 = sys.version_info > (3, 5) # FunctionDef returns & arg annotation
# from ast.py
def dump(node, annotate_fields=True, include_attributes=False):
"""
Return a formatted du... |
"""Test the RPC HTTP basics."""
from test_framework.test_framework import DoriancoinTestFramework
from test_framework.util import *
import http.client
import urllib.parse
class HTTPBasicsTest (DoriancoinTestFramework):
def set_test_params(self):
self.num_nodes = 3
def setup_network(self):
se... |
import functools
import warnings
from importlib import import_module
from django.utils import six
from django.utils.deprecation import RemovedInDjango20Warning
from django.utils.inspect import getargspec
from django.utils.itercompat import is_iterable
from .base import Node, Template, token_kwargs
from .exceptions im... |
from __future__ import unicode_literals
import os.path, shutil
from django.core.management.base import BaseCommand, CommandError
from django.conf import settings
from require.conf import settings as require_settings
def default_staticfiles_dir():
staticfiles_dirs = getattr(settings, "STATICFILES_DIRS", ())
... |
# -*- coding: utf8
from __future__ import division, print_function
from scripts.learn_base import create_input_table
from scripts.learn_base import create_grid_search
from scripts.learn_base import clf_summary
from sklearn.cross_validation import cross_val_score
from sklearn.cross_validation import StratifiedKFold
f... |
"""Binary Sensor platform for FireServiceRota integration."""
import logging
from homeassistant.components.binary_sensor import BinarySensorEntity
from homeassistant.config_entries import ConfigEntry
from homeassistant.helpers.typing import HomeAssistantType
from homeassistant.helpers.update_coordinator import (
C... |
# Rolling rotamericity metric - part of the EMRinger analysis tool.
# Reference:
#
# Barad BA, Echols N, Wang RY-R, Cheng YC, DiMaio F, Adams PD, Fraser JS.
# EMRinger: side-chain-directed model and map validation for 3D electron
# cryomicroscopy. Nature Methods published online 17 August 2015;
# doi:10.1038/nmeth.... |
from pythonpixels import PPImage, PPColor
# from pythonpixels import PPColor
from pythonpixels import vec4_from_vec3, bgr_from_hex
import pygame
import os
from pythonpixels import bufferToTupleStyleString
# formerly static_createFromImageFile
def load_image(self,fileName):
returnKVI = None
if os.path.exists(f... |
from django.conf import settings
from django.conf.urls.defaults import *
from django.views.generic.simple import direct_to_template
from django.contrib.auth.views import login, logout, password_change
from django.contrib import admin
admin.autodiscover()
urlpatterns = patterns('',
url(r'^$', 'music_server.views.i... |
import os
from traceback import format_exception
import colorama
import ray
import ray.cloudpickle as pickle
from ray.core.generated.common_pb2 import RayException, Language
import setproctitle
class RayError(Exception):
"""Super class of all ray exception types."""
def to_bytes(self):
# Extract ex... |
from persistent.dict import PersistentDict
from pyramid.events import subscriber
from pyramid.threadlocal import get_current_request
import yampy
from novaideo.event import ObjectPublished
from novaideo.connectors.core import YAMMER_CONNECTOR_ID
@subscriber(ObjectPublished)
def mysubscriber_object_published(event):... |
from .usql_type_py3 import USqlType
class USqlTableType(USqlType):
"""A Data Lake Analytics catalog U-SQL table type item.
Variables are only populated by the server, and will be ignored when
sending a request.
:param compute_account_name: the name of the Data Lake Analytics account.
:type compu... |
"""Test Rotest's Logs behavior."""
from __future__ import absolute_import
import os
import time
import unittest
from rotest.common import core_log
from rotest.common.log import get_test_logger
from rotest.common.config import ROTEST_WORK_DIR
class TestLog(unittest.TestCase):
"""Test logs functionality."""
T... |
"""
Shows how to combine Normalization and Colormap instances to draw
"levels" in pcolor, pcolormesh and imshow type plots in a similar
way to the levels keyword argument to contour/contourf.
"""
import matplotlib.pyplot as plt
from matplotlib.colors import BoundaryNorm
from matplotlib.ticker import MaxNLocator
import... |
import sys
import struct
import urllib
# Copyright
# =========
# Copyright (C) 2016 Trustwave Holdings, Inc.
#
# 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 Foundation, either version 3 of the License, o... |
import os
from django.core.urlresolvers import reverse
from onadata.apps.main.tests.test_base import TestBase
from onadata.apps.viewer.models.export import Export
from onadata.apps.main.models.meta_data import MetaData
from onadata.apps.viewer.views import export_list
class TestExportList(TestBase):
def setUp(... |
#!/usr/bin/env python
'''Train a simple deep CNN on the CIFAR10 small images dataset.
Using TFRecord queues with Keras and multi-GPU enabled. Compare with:
https://github.com/avolkov1/keras_experiments/blob/master/examples/cifar/cifar10_cnn_mgpu.py
https://github.com/fchollet/keras/blob/master/examples/cifar10_cnn.py
... |
"""
Flask-GoogleLogin
"""
from base64 import (urlsafe_b64encode as b64encode,
urlsafe_b64decode as b64decode)
from urllib.parse import urlencode, parse_qsl
from functools import wraps
from flask import request, redirect, abort, current_app, url_for
from flask_login import LoginManager, encode_cook... |
from scipy.spatial.distance import cosine
from sklearn.preprocessing import normalize
from sklearn.metrics import pairwise, precision_recall_curve, average_precision_score, roc_curve
import json
import argparse
import pandas as pd
import numpy as np
from joblib import Parallel, delayed
import tempfile
import shutil
imp... |
from twisted.trial import unittest
from mock import MagicMock
from pixelated.config.site import PixelatedSite
from twisted.web.test.requesthelper import DummyChannel
class TestPixelatedSite(unittest.TestCase):
def test_add_security_headers(self):
request = self.create_request()
request.process()
... |
from neutron_lib.api.definitions import portbindings
from neutron_lib.callbacks import events
from neutron_lib.callbacks import registry
from neutron_lib.services.qos import constants as qos_consts
from oslo_log import log as logging
from neutron.api.rpc.callbacks import events as rpc_events
from neutron.api.rpc.callb... |
from openstackclient.tests.volume.v1 import fakes as service_fakes
from openstackclient.volume.v1 import service
class TestService(service_fakes.TestService):
def setUp(self):
super(TestService, self).setUp()
# Get a shortcut to the ServiceManager Mock
self.service_mock = self.app.client... |
import time
from huey import crontab
from huey.contrib.djhuey import task, periodic_task, db_task
def tprint(s, c=32):
# Helper to print messages from within tasks using color, to make them
# stand out in examples.
print('\x1b[1;%sm%s\x1b[0m' % (c, s))
# Tasks used in examples.
@task()
def add(a, b):
... |
import time
from multiprocessing import Process
from psycopg2 import InternalError
import logging
from database import connection
class ProcessRouteCalculation(Process):
def __init__(self, route_queue, route_counter):
Process.__init__(self)
self.logging = logging.getLogger(self.name)
self... |
#!/usr/bin/python
# coding=utf-8
__author__ = "João Andrade"
__date__ = "$24/Abr/2015 23:17:25$"
import sys
import time
import os
class Main:
'''
Main application class.
Arguments:
-p : path of the project
-all : include hidden files of the project
'''
def __init__(self, args):
... |
import mock
from ceagle.api import client
from tests.unit import test # noqa
class ClientTestCase(test.TestCase):
def test___init__(self):
self.assertRaises(TypeError, client.Client)
self.assertRaises(TypeError, client.Client, "foo")
ct = client.Client("foo", "foo_ep")
self.asse... |
"""Registry for layers and their parameters/variables.
This represents the collection of all layers in the approximate Fisher
information matrix to which a particular FisherBlock may belong. That is, we
might have several layer collections for one TF graph (if we have multiple K-FAC
optimizers being used, for example.... |
#!/usr/bin/env python
"""functions for working with 3D "vectors" (really just arrays of length three)"""
# Copyright 2010 Kevin Keating
#
# Licensed under the Educational Community 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 L... |
''' Functions for arranging bokeh Layout objects.
'''
#-----------------------------------------------------------------------------
# Imports
#-----------------------------------------------------------------------------
from __future__ import absolute_import
from .core.enums import Location, SizingMode
from .model... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
import openedx.core.djangoapps.xmodule_django.models
class Migration(migrations.Migration):
dependencies = [
('course_groups', '0002_change_inline_default_cohort_value'),
]
operations = [
... |
from sys import stderr
from os import environ
from os import listdir
from os.path import join, isfile
from setuptools import setup
# The list of external python modules that are required
_REQUIRED_MODULES = ["CFPropertyList", "zlib"]
def checkForModule(moduleName):
'''Check that the given Python module name is ... |
# stdlib, alphabetical
import cgi
import datetime
import logging
import os
import shutil
import tempfile
import time
# Core Django, alphabetical
from django.conf import settings
from django.http import HttpResponse
from django.template.loader import render_to_string
from django.utils import timezone
from django.utils.... |
from collections import Counter, defaultdict
from functools import partial, reduce
from linear_algebra import shape, get_row, get_column, make_matrix, \
vector_mean, vector_sum, dot, magnitude, vector_subtract, scalar_multiply
from statistics import correlation, standard_deviation, mean
from probability import inve... |
from __future__ import absolute_import, unicode_literals
from groove import _constants
from groove import utils
from groove._groove import ffi, lib
from groove.buffer import Buffer
from groove.groove import GrooveClass
from groove.playlist import PlaylistItem
__all__ = ['Sink']
class Sink(GrooveClass):
"""Groo... |
import numpy as np
def get_indices(list, center):
start =0
end = 0
if center < 3:
start = 0
end = 5
elif center > len(list) - 3:
start = len(list) - 5
end = len(list)
else:
start = center - 2
end = center + 3
return (start, end)
def get_value(x, ... |
import json
from twisted.web.server import NOT_DONE_YET
from twisted.web.resource import Resource
from twisted.logger import Logger
log = Logger()
class Api(Resource):
isLeaf = True
def __init__(self, dispatcher, global_tokens):
Resource.__init__(self)
self.dispatcher = dispatcher
... |
from bpy.types import Operator, PropertyGroup
from bpy.props import BoolProperty, FloatProperty, IntProperty, PointerProperty
from .. import var
class Dimensions(PropertyGroup):
x: FloatProperty(name="Width", step=0.1, unit="LENGTH")
y: FloatProperty(name="Length", step=0.1, unit="LENGTH")
z1: FloatPrope... |
"""Exceptions and error messages."""
import logging
logger = logging.getLogger(__name__)
class NotSupportedException(Exception):
"""Exception raised when requirements are not installed.
Attributes
----------
dep : Module
The dependent module.
dep_name : String
Name of the depend... |
import json
import numpy as np
from eli5.base import (
Explanation, TargetExplanation, FeatureWeights, FeatureWeight)
from eli5.formatters.as_dict import format_as_dict, _numpy_to_python
# format_as_dict is called in eli5.tests.utils.format_as_all
def test_numpy_to_python():
x = _numpy_to_python({
... |
#!/usr/bin/python2.7
import unittest
from nassl import _nassl, SSL_VERIFY_NONE
from nassl.ssl_client import SslClient
import socket
class X509_EXTENSION_Tests(unittest.TestCase):
def test_new_bad(self):
self.assertRaises(NotImplementedError, _nassl.X509_EXTENSION, (None))
class X509_EXTENSION_Tests_Onl... |
__author__ = 'Shamal Faily'
class GoalAssociation:
def __init__(self,associationId,envName,goalName,goalDimName,aType,subGoalName,subGoalDimName,alternativeId,rationale):
self.theId = associationId
self.theEnvironmentName = envName
self.theGoal = goalName
self.theGoalDimension = goalDimName
self.... |
import sys
import unittest
import codecs
import StringIO
import pyauparser
class TestGrammar(unittest.TestCase):
def setUp(self):
self.grammar = pyauparser.Grammar.load_file("Data/operator.egt")
def test_load(self):
self.assertEqual(len(self.grammar.properties), 8)
self.a... |
# -*- coding: utf-8 -*-
"""
Given an array nums, there is a sliding window of size k which is moving from the very left of the array to the very
right. You can only see the k numbers in the window. Each time the sliding window moves right by one position.
For example,
Given nums = [1,3,-1,-3,5,3,6,7], and k = 3.
Win... |
from __future__ import print_function
import sys
import logging
import txaio
txaio.use_asyncio()
# some library you use is using txaio logging stuff
class Library(object):
log = txaio.make_logger()
def something(self):
self.log.info("info log from library foo={foo}", foo='bar')
self.log.debu... |
import mock
from webob import exc
from oslo_policy import policy as oslo_policy
from nova.api.openstack.compute import certificates \
as certificates_v21
from nova.cert import rpcapi
from nova import context
from nova import exception
from nova import policy
from nova import test
from nova.tests.unit.api.open... |
# encoding: utf-8
# module PyQt4.QtGui
# from /usr/lib/python2.7/dist-packages/PyQt4/QtGui.so
# by generator 1.135
# no doc
# imports
import PyQt4.QtCore as __PyQt4_QtCore
class QAbstractItemDelegate(__PyQt4_QtCore.QObject):
""" QAbstractItemDelegate(QObject parent=None) """
def closeEditor(self, *args, **kw... |
"""
Test suite for module plantweb.args.
See http://pythontesting.net/framework/pytest/pytest-introduction/#fixtures
"""
from __future__ import unicode_literals, absolute_import
from __future__ import print_function, division
from os import listdir
from os.path import join, abspath, dirname, normpath
from plantweb ... |
import logging
import redis
import json
log = logging.getLogger(__name__)
class UserToken(object):
"""Utility class to deal with user token session in cache."""
_token_prefix = 'tokens::'
def __init__(self, redis_host, redis_port=6379):
self.client = redis.Redis(redis_host, redis_port)
de... |
import numpy as np
def alinear(x1,y1,x2,y2,dim_1_x,dim_1_y,dim_2_x,dim_2_y, actual): # 1: Referencia 2: Pos. de la imagen actual
diferencia_x = x1 - x2
diferencia_y = y1 - y2
matriz_final = np.zeros((dim_1_x,dim_1_y))
for i in range(dim_2_x):
for j in range(dim_2_y):
x = i + difer... |
import os
import signal
import subprocess
import sys
from pathlib import Path
from unittest import mock, skipUnless
from django.db import connection
from django.db.backends.postgresql.client import DatabaseClient
from django.test import SimpleTestCase
class PostgreSqlDbshellCommandTestCase(SimpleTestCase):
def s... |
# -*- coding:utf-8 -*-
from datetime import datetime
from django.test import TestCase
from django.shortcuts import resolve_url as r
from eventex.subscriptions.models import Subscription
class SubscriptionModelTest(TestCase):
def setUp(self):
self.obj = Subscription(
name='Adriano Margarin',... |
#########################################################################################################
# Description: Low-level functions for running classification models and model ensembles
#
#########################################################################################################
# RandomForest i... |
"""Node assortativity coefficients and correlation measures.
"""
from networkx.algorithms.assortativity.mixing import (
degree_mixing_matrix,
attribute_mixing_matrix,
numeric_mixing_matrix,
)
from networkx.algorithms.assortativity.pairs import node_degree_xy
__all__ = [
"degree_pearson_correlation_coef... |
#!/usr/bin/env python
# encoding: utf-8
import os
import sys
import importlib
try:
tc = importlib.import_module("termcolor")
except ImportError:
tc = None
class ColorFormatter(object):
def __init__(self, color_enabled):
self.__color_enabled = color_enabled
def get_color_text(self, value, c... |
import ast
import glob
import os
import shutil
import unittest
from unittest.mock import patch
import frappe
from frappe.utils.boilerplate import make_boilerplate
class TestBoilerPlate(unittest.TestCase):
@classmethod
def tearDownClass(cls):
bench_path = frappe.utils.get_bench_path()
test_app_dir = os.path.jo... |
from __future__ import unicode_literals
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
from django.http import Http404
from django.shortcuts import get_object_or_404
from django.utils.translation import ugettext_lazy as... |
from indico.core.signals.event import _signals
sidemenu = _signals.signal('sidemenu', """
Expected to return ``MenuEntryData`` objects to be added to the event side menu.
A single entry can be returned directly, multiple entries must be yielded.
""")
deleted = _signals.signal('deleted', """
Called when an event is d... |
'''
Created on November 18, 2014
@author: cmills
The original /tasr endpoints are defined here. These should be considered
deprecated and are likely to be removed before the next version. These are
here to preserve compatibility with some older code.
'''
import avro.schema
import bottle
import json
import tasr.app_... |
import logging
from couchdbkit import ChangesStream, ResourceNotFound
from casexml.apps.case.models import CommCareCase
from corehq.apps.indicators.models import FormIndicatorDefinition, \
CaseIndicatorDefinition, CaseDataInFormIndicatorDefinition
from corehq.apps.indicators.utils import get_namespaces, get_indicat... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import atexit
import ctypes
import distutils.ccompiler
import os.path
import platform
import shutil
import sys
import tempfile
__version__ = '0.0.1'
def c(source, libraries=[]):
r"""
>>> c('int add(int a, int b) {return a + b;}').add(40, 2)
42
>>> sqrt =... |
import re
from diffoscope.tools import tool_required
from diffoscope.difference import Difference
from .utils.file import File
from .utils.command import Command
class Pdftotext(Command):
@tool_required('pdftotext')
def cmdline(self):
return ['pdftotext', self.path, '-']
class Pdftk(Command):
... |
#
# Authors: Luis Seabra Lopes
# October-November 2013
#
from croblink import *
from math import *
class MyRob(CRobLink):
def run(self):
if rob.status!=0:
print "Connection refused or error"
quit()
state='stop'
stoppedState='run'
self.start_saved = Fal... |
# -*- coding: utf-8 -*-
#
import sys
import os
import shlex
import subprocess
import xml.etree.ElementTree
from recommonmark.parser import CommonMarkParser
on_rtd = os.environ.get('READTHEDOCS', None) == 'True'
# Add python libraries to sys.path for autodoc
sys.path.insert(0, '_dummy_non_ros_env') # to avoid Import... |
# -*- coding: utf-8 -*-
from south.v2 import DataMigration
class Migration(DataMigration):
def forwards(self, orm):
"Write your forwards methods here."
courses = orm['courses.course'].objects.all()
for course in courses:
if course.created_from:
course.is_activi... |
"""
This transformation rule tries to identify the PRelu structure generated by
Keras, and convert it to a single op.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.core.framework import attr_value_pb2
from tensorflow.python.framework... |
import urlparse
import scrapy
from candidates.items import Candidate
from candidates.loaders import CandidateLoader
class BBCConstituenciesSpider(scrapy.Spider):
"""
Scrapes consituency results for the 2015 UK general election from the BBC's
website.
"""
name = "bbc"
allowed_domains = ["bb... |
import raiders
from collections import defaultdict
from hypothesis import given
from hypothesis import strategies as st
def check(starting, swaps):
positions = {x: i for i, x in enumerate(starting)}
pattern = starting.copy()
for (l, r) in swaps:
li = positions[l]
ri = positions[r]
... |
#!/usr/bin/env python
'''
Basic wrappers for the VIRL API
'''
import requests
simengine_host = "http://10.10.20.160:19399"
virl_user = "guest"
virl_password = "guest"
def get_simulations():
u = simengine_host + "/simengine/rest/list"
r = requests.get(u, auth=(virl_user, virl_password))
return r.json... |
"""
Notebook Tag
------------
This is a liquid-style tag to include a static html rendering of an IPython
notebook in a blog post.
Syntax
------
{% notebook filename.ipynb [ cells[start:end] ]%}
The file should be specified relative to the ``notebooks`` subdirectory of the
content directory. Optionally, this subdire... |
print [] == [1,]
print [] == []
print [1,] == [1,]
print [1,2] == [3,4]
print [1,2] == [1,2]
print [1,2] == [1,]
print [1,2] == [1,2,3]
print [1,2,3] == [1,2]
print [1,2,3] == [1,2,3]
print
print [] != [1,]
print [] != []
print [1,] != [1,]
print [1,2] != [3,4]
print [1,2] != [1,2]
print [1,2] != [1,]
print [1,2] != [1... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.