content stringlengths 4 20k |
|---|
# app
from app import app
from helpers import stripped, name_image_file
# flickr_api
import flickr_api, json, urllib
from flickr_api.api import flickr
flickr_key = app.config['FLICKR_API_KEY']
flickr_secret = app.config['FLICKR_API_SECRET']
# authorize access to flickr
flickr_api.set_keys(api_key = flickr_key, api_sec... |
"""
Provides access to the system apps (global .desktop files for Linux,
Start Menu on windows).
Linux:
SystemAppProvider parses and interprets .desktop files
from all paths defined by QStandardPaths::ApplicationsLocation
(http://doc.qt.io/qt-5/qstandardpaths.html).
The processing is done by DesktopEntryProvi... |
from __future__ import absolute_import
from __future__ import print_function
from keras.datasets import mnist
from keras.models import Sequential
from keras.layers.core import Dense, Activation
from keras.utils import np_utils
from keras.wrappers.scikit_learn import *
import numpy as np
batch_size = 128
nb_epoch = 1
... |
from django.test import SimpleTestCase
from ..utils import setup
class SpacelessTagTests(SimpleTestCase):
@setup({'spaceless01': "{% spaceless %} <b> <i> text </i> </b> {% endspaceless %}"})
def test_spaceless01(self):
output = self.engine.render_to_string('spaceless01')
self.assertEqu... |
from __future__ import unicode_literals
from .. import Provider as PersonProvider
class Provider(PersonProvider):
formats = (
'{{first_name}} {{last_name}}',
'{{first_name}} {{last_name}}',
'{{first_name}} {{last_name}}',
'{{first_name}} {{last_name}}',
'{{first_name}} {{la... |
#!/usr/bin/env python
import os, inspect
import capnp
import tests_capnp
test_data_dir = os.path.dirname(os.path.abspath(__file__))
################################################################################
# Sanity checks for handwritten messages
def read(schema, name):
p = os.path.join(test_data_dir, na... |
from setuptools import setup, find_packages
from codecs import open # To use a consistent encoding
from os import path
import csrec_webapp
here = path.abspath(path.dirname(__file__))
# Get the long description from the relevant file
long_description = open('README.md').read()
def setup_package():
build_require... |
# encoding: utf-8
from __future__ import unicode_literals
from io import BytesIO
from django.conf.urls import url
from django.contrib.auth.models import User
from django.shortcuts import redirect
from django.test import TestCase
from rest_framework.decorators import api_view
from rest_framework.response import Respo... |
import glob
import os
import pickle
import platform
import select
import shlex
import subprocess
import traceback
from ansible.module_utils.six import PY2, b
from ansible.module_utils._text import to_bytes, to_text
def sysv_is_enabled(name, runlevel=None):
'''
This function will check if the service name sup... |
#!/usr/bin/python -u
# $Id: xslt.py 8353 2009-03-17 16:57:50Z mzjn $
import sys
import libxml2
import libxslt
from docbook import adjustColumnWidths
# Check the arguments
usage = "Usage: %s xmlfile.xml xslfile.xsl [outputfile] [param1=val [param2=val]...]" % sys.argv[0]
xmlfile = None
xslfile = None
outfile = "-"
pa... |
#! /usr/bin/python
#-*- coding: utf-8 -*-
from PySide import QtGui, QtCore
########################################################################
class Highlighter(QtGui.QSyntaxHighlighter):
#----------------------------------------------------------------------
def __init__(self, parent, extra):
s... |
import traceback
import warnings
from fito.model import Model
from fito.model import ModelParameter
from fito.specs.fields import CollectionField, PrimitiveField
try:
from gensim.models import Word2Vec as GensimWord2Vec
except ImportError:
traceback.print_exc()
warnings.warn('Could not import Word2Vec')
... |
from odoo.addons.account.tests.account_test_classes import AccountingTestCase
import time
class TestAccountBudgetCommon(AccountingTestCase):
def setUp(self):
super(TestAccountBudgetCommon, self).setUp()
# In order to check account budget module in Odoo I created a budget with few budget position... |
#!/usr/bin/python
# -*- encoding: utf-8 -*-
from Pessoa import Pessoa
import urllib2, urllib, json
from urllib2 import URLError, HTTPError
from ConfigUrl import urlpath
p = Pessoa()
url = urlpath()
user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'
headers = { 'User-Agent' : user_agent }
#data = urll... |
'''test for reference counting problems.
If a Python object is garbage collected while another object is using its
data, you will get a segmentation fault.
'''
import array
import gc
import tempfile as tfi
import cairo
import py.test as test
width, height = 256, 256
def draw(ctx, width, height):
"example draw co... |
import sys, pexpect, string, os, cmdline_test_data
#
# function to run test
#
def runTest(child,test):
child.send(test["Sequence"])
if test["Result"] == None:
return 0
child.expect(test["Result"],1)
#
# history test is a special case
#
# This test does the following:
# 1) fills the history with garbage up to its... |
"""
Annotation Component Page.
"""
from bok_choy.page_object import PageObject
from selenium.webdriver import ActionChains
class AnnotationComponentPage(PageObject):
"""
View of annotation component page.
"""
url = None
active_problem = 0
def is_browser_on_page(self):
return self.q(c... |
import compileall
import glob
import os
import re
import subprocess
import shutil
import sys
import zipfile
def run(cmd, exit=True, cwd=None):
print cmd
if subprocess.Popen(cmd.split(), cwd=cwd).wait() != 0:
if exit:
print 'Failed!'
sys.exit(1)
else:
print 'Ignoring failure.'
def find(... |
# coding: utf-8
from __future__ import unicode_literals
from .common import InfoExtractor
from .amp import AMPIE
from ..utils import (
ExtractorError,
int_or_none,
parse_iso8601,
)
class BleacherReportIE(InfoExtractor):
_VALID_URL = r'https?://(?:www\.)?bleacherreport\.com/articles/(?P<id>\d+)'
_... |
"""Module containing the template for documents."""
from soc.models import document as document_model
from soc.logic.helper import prefixes
from soc.views import forms
from soc.views import template
from soc.views.helper import lists
class DocumentForm(forms.ModelForm):
"""Django form for creating documents."""
... |
# -*- coding: utf-8 -*-
"""
To provide a shim layer over Pillow/PIL situation until the PIL support is
removed.
Combinations To Account For
===========================
* Pillow:
* never has ``_imaging`` under any Python
* has the ``Image.alpha_composite``, which may aid in detection
* PIL
* CPython 2.... |
{
'name': 'Contracts Management: hr_expense link',
'version': '1.1',
'category': 'Hidden',
'description': """
This module is for modifying account analytic view to show some data related to the hr_expense module.
===========================================================================================... |
from __future__ import absolute_import
from __future__ import print_function
import numpy as np
from keras.utils.test_utils import get_test_data
from keras.preprocessing import sequence
from keras.optimizers import SGD, RMSprop, Adagrad
from keras.utils import np_utils
from keras.models import Sequential, Graph
from k... |
from __future__ import unicode_literals
import os
import django
from guardian.compat import unittest
from guardian.utils import abspath
from django.conf import settings
from django.conf import UserSettingsHolder
from django.utils.functional import wraps
THIS = abspath(os.path.dirname(__file__))
TEST_TEMPLATES_DIR = a... |
from openerp.report.render.rml2pdf import utils
import copy
class odt2odt(object):
def __init__(self, odt, localcontext):
self.localcontext = localcontext
self.etree = odt
self._node = None
def render(self):
def process_text(node,new_node):
for child in utils._child... |
import os
import re
from setuptools import setup
# Set external files
try:
from pypandoc import convert
README = convert('README.md', 'rst')
except ImportError:
README = open(os.path.join(os.path.dirname(__file__), 'README.md')).read()
with open(os.path.join(os.path.dirname(__file__), 'requirements.txt'))... |
"""
Course API Authorization functions
"""
from student.roles import GlobalStaff
def can_view_courses_for_username(requesting_user, target_username):
"""
Determine whether `requesting_user` has permission to view courses available
to the user identified by `target_username`.
Arguments:
reque... |
"""
Logical Link Control(LLC, IEEE 802.2) parser/serializer
http://standards.ieee.org/getieee802/download/802.2-1998.pdf
LLC format
+-----------------+--------------+
| DSAP address | 8 bits |
+-----------------+--------------+
| SSAP address | 8 bits |
+-----------------+------... |
# -*- coding: utf-8 -*-
import mock
from nose.tools import * # noqa (PEP8 asserts)
import hmac
import hashlib
from StringIO import StringIO
import furl
from modularodm import Q
from modularodm.exceptions import ValidationError
from framework.auth.core import Auth
from website import settings
from website.models i... |
import os
import pytest
import responses
import zipfile
from urllib.parse import parse_qs
from urllib.parse import urlparse
from django.conf import settings
from papers.models import Researcher
from publishers.models import AliasPublisher
from publishers.models import Journal
from publishers.models import Publisher
... |
COUNTED_UNKNOWN_PROPERTIES = [
"-webkit-font-smoothing",
"zoom",
"-webkit-tap-highlight-color",
"speak",
"text-size-adjust",
"-webkit-font-feature-settings",
"-webkit-user-drag",
"size",
"-webkit-clip-path",
"orphans",
"widows",
"-webkit-user-modify",
"-webkit-margin-... |
"""Represent the topology of servers."""
from collections import namedtuple
from pymongo import common
from pymongo.server_type import SERVER_TYPE
from pymongo.errors import ConfigurationError
from pymongo.server_description import ServerDescription
TOPOLOGY_TYPE = namedtuple('TopologyType', ['Single', 'ReplicaSetN... |
import os
from unittest import TestCase, mock
from commissaire_http.handlers import create_jsonrpc_response
def create_environ(path='/', headers={}):
"""
Shortcut for creating an fake WSGI environ.
"""
env = {
'PATH_INFO': path,
}
env.update(headers)
return env
def get_fixture_... |
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import offsetbox
from sklearn import (manifold, datasets, decomposition, ensemble, lda,
random_projection)
def digits_plot():
digits = datasets.load_digits(n_class=6)
n_digits = 500
X = digits.data[:n_digits]
y = di... |
import unittest
from test import test_support
import base64
class LegacyBase64TestCase(unittest.TestCase):
def test_encodestring(self):
eq = self.assertEqual
eq(base64.encodestring("www.python.org"), "d3d3LnB5dGhvbi5vcmc=\n")
eq(base64.encodestring("a"), "YQ==\n")
eq(base64.encod... |
from testlib import mox
import unittest
from google.appengine.api import apiproxy_stub_map
from google.appengine.api import files
from google.appengine.api.files import testutil as files_testutil
from mapreduce import context
from mapreduce import errors
from mapreduce import model
from mapreduce import output_writers... |
from __future__ import absolute_import
import numpy as nm
from sfepy.base.base import load_classes, Struct
from sfepy import get_paths
def transform_basis(transform, bf):
"""
Transform a basis `bf` using `transform` array of matrices.
"""
if bf.ndim == 3:
nbf = nm.einsum('cij,qdj->cqdi', trans... |
# coding=utf-8
"""
Collect stats from postfix-stats. postfix-stats is a simple threaded stats
aggregator for Postfix. When running as a syslog destination, it can be used to
get realtime cumulative stats.
#### Dependencies
* socket
* json (or simplejson)
* [postfix-stats](https://github.com/disqus/postfix-stats)
... |
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import rcParams
plt.ion()
rcParams.update({'figure.autolayout': True})
def plotResult():
resultTM = np.load('result/reberSequenceTM.npz')
resultLSTM = np.load('result/reberSequenceLSTM.npz')
plt.figure()
plt.hold(True)
plt.subplot(2,2,1)
... |
from pybench import Test
class PythonFunctionCalls(Test):
version = 2.1
operations = 5*(1+4+4+2)
rounds = 60000
def test(self):
global f,f1,g,h
# define functions
def f():
pass
def f1(x):
pass
def g(a,b,c):
... |
from __future__ import absolute_import
from invenio.ext.admin.views import ModelView
from invenio.ext.sqlalchemy import db
from invenio.modules.pidstore.models import PersistentIdentifier, PidLog
class PersistentIdentifierAdmin(ModelView):
_can_create = False
_can_edit = False
_can_delete = False
co... |
from openerp.addons.auditlog import migrate_from_audittrail
def migrate(cr, version):
"""if we migrate from an older version, it's a migration from audittrail"""
migrate_from_audittrail(cr) |
#!/usr/bin/env python
import unittest
import os
from test import test_support
from Tkinter import Tcl
from _tkinter import TclError
class TclTest(unittest.TestCase):
def setUp(self):
self.interp = Tcl()
def testEval(self):
tcl = self.interp
tcl.eval('set a 1')
self.assertEqua... |
"""This file must not depend on any module specific to the WebSocket protocol.
"""
from mod_pywebsocket import http_header_util
# Additional log level definitions.
LOGLEVEL_FINE = 9
# Constants indicating WebSocket protocol version.
VERSION_HIXIE75 = -1
VERSION_HYBI00 = 0
VERSION_HYBI01 = 1
VERSION_HYBI02 = 2
VERS... |
#=======================================================================
__version__ = '''0.0.00'''
__sub_version__ = '''20070725015812'''
#-----------------------------------------------------------------------
import sys
#-----------------------------------------------------------------set---
# An evil equivale... |
{
'name' : 'Analytic Accounting',
'version': '1.1',
'author' : 'OpenERP SA',
'website' : 'https://www.tunierp.com/page/accounting',
'category': 'Hidden/Dependency',
'depends' : ['base', 'decimal_precision', 'mail'],
'description': """
Module for defining analytic accounting object.
=========... |
'''
Utility classes for creating dynamic html documents
'''
__license__ = '''
This file is part of Dominate.
Dominate is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as
published by the Free Software Foundation, either version 3 of
the License, or (a... |
"""dbm compatibility module for Python versions that don't have dbm.
This does not not NOT (repeat, *NOT*) provide complete dbm functionality.
It's just a stub on which to hang just enough pieces of dbm functionality
that the whichdb.whichdb() implementstation in the various 2.X versions of
Python won't blow up even i... |
# Django settings for example project.
import os
DEBUG = True
ADMINS = (
('Tester', '<EMAIL>'),
)
MANAGERS = ADMINS
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
'NAME': '%s/db.sqlite' % os.path.d... |
from django.template import TemplateSyntaxError
from django.test import SimpleTestCase
from ..utils import setup
class TemplateTagTests(SimpleTestCase):
@setup({'templatetag01': '{% templatetag openblock %}'})
def test_templatetag01(self):
output = self.engine.render_to_string('templatetag01')
... |
from __future__ import print_function
from PyKCS11 import *
import binascii
pkcs11 = PyKCS11Lib()
pkcs11.load() # define environment variable PYKCS11LIB=YourPKCS11Lib
# get 1st slot
slot = pkcs11.getSlotList(tokenPresent=True)[0]
session = pkcs11.openSession(slot, CKF_SERIAL_SESSION | CKF_RW_SESSION)
session.login... |
"""Wrapper around tf-slim's training code contrib/slim/python/slim/learning.py
to support training of pruned models
*******************************************************************
* A simple working training script with support for model pruning *
*******************************************************************... |
"""Tests for ops.gmm."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
from tensorflow.contrib.factorization.python.ops import gmm as gmm_lib
from tensorflow.contrib.learn.python.learn.estimators import kmeans
from tensorflow.contrib.l... |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
from PyQt5.QtWidgets import QApplication, QWidget
from PyQt5.QtGui import QIcon
from PyQt5.QtWidgets import QLabel, QGridLayout
from PyQt5.QtWidgets import QLineEdit, QPushButton, QHBoxLayout
from PyQt5.QtWidgets import QMessageBox
from PyQt5.QtCore import Qt
class Kalkulat... |
import os
import logging
# standardize use of logging module in fs-drift
def start_log(prefix, verbosity=0):
log = logging.getLogger(prefix)
if os.getenv('LOGLEVEL_DEBUG') != None or verbosity != 0:
log.setLevel(logging.DEBUG)
else:
log.setLevel(logging.INFO)
log_format = prefix + ' %(... |
try:
import pyodbc
except ImportError:
pyodbc_found = False
else:
pyodbc_found = True
class NotSupportedError(Exception):
pass
class CannotDropError(Exception):
pass
# module specific functions
def get_role_facts(cursor, role=''):
facts = {}
cursor.execute("""
select r.name, r.as... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = r'''
---
module: vexata_volume
version_added: 2.8
short_description: Manage... |
from django.conf import settings
from ... import signals
from ...models import RegistrationProfile
from ...views import ActivationView as BaseActivationView
from ...views import RegistrationView as BaseRegistrationView
from ...compat import RequestSite, is_app_installed, get_site_model
from ...users import UserModel
... |
import os
import re
import sys
import unittest
class TestableTestProgram(unittest.TestProgram):
module = '__main__'
exit = True
defaultTest = failfast = catchbreak = buffer = None
verbosity = 1
progName = ''
testRunner = testLoader = None
def __init__(self):
pass
class TestDisc... |
# -*- coding: utf-8 -*-
from django import test
from cradmin_legacy import cradmin_testhelpers
from model_bakery import baker
from devilry.apps.core.models import PeriodTag
from devilry.apps.core.models import RelatedExaminer, RelatedStudent
from devilry.devilry_admin.views.period.manage_tags import manage_tags
from... |
"""
AR_Random app implements Active ranking Random
author: Sumeet Katariya, <EMAIL>
last updated: 09/24/2016
AR_Random implements random sampling
"""
import numpy as np
import numpy.random
import next.utils as utils
#import pickle
#import logging
#logging.basicConfig(filename='logging_AR_Random.log', level=logging.D... |
"""Common DNS Exceptions."""
class DNSException(Exception):
"""Abstract base class shared by all dnspython exceptions."""
pass
class FormError(DNSException):
"""DNS message is malformed."""
pass
class SyntaxError(DNSException):
"""Text input is malformed."""
pass
class UnexpectedEnd(SyntaxEr... |
""" Encoding Aliases Support
This module is used by the encodings package search function to
map encodings names to module names.
Note that the search function normalizes the encoding names before
doing the lookup, so the mapping will have to map normalized
encoding names to module names.
Con... |
'''Tool for a script to keep track changes performed on a large number
of objects.
Example:
from running_stats import Stats
stats = Stats()
for package in packages:
if package.enabled:
package.delete()
stats.add('deleted', package.name)
else:
stats.add('not deleted' package.name)
print... |
# coding: utf-8
from __future__ import unicode_literals
import re
import base64
from .common import InfoExtractor
from ..compat import (
compat_urllib_parse_urlencode,
compat_str,
)
from ..utils import (
int_or_none,
parse_iso8601,
smuggle_url,
unsmuggle_url,
urlencode_postdata,
)
class ... |
from __future__ import absolute_import
import logging
import time
from Queue import Empty
from collections import defaultdict
from itertools import cycle
from multiprocessing import Queue, Process
from kafka.common import ProduceRequest, TopicAndPartition
from kafka.partitioner import HashedPartitioner
from kafka.pr... |
__title__ = 'zerorpc'
__version__ = '0.5.2'
__author__ = 'François-Xavier Bourlet <<EMAIL>>.'
__license__ = 'MIT'
__copyright__ = 'Copyright 2015 François-Xavier Bourlet <<EMAIL>>.' |
""" Test unit for the miscutil/lib/inveniocfg_upgrader module. """
from datetime import date
import os
import os.path
import shutil
import sys
import tempfile
import six
from invenio.testsuite import make_test_suite, run_test_suite, InvenioTestCase
def dictify(ls, value=None):
if value is not None:
re... |
"""
Dribbble OAuth2 backend, docs at:
http://psa.matiasaguirre.net/docs/backends/dribbble.html
http://developer.dribbble.com/v1/oauth/
"""
from social.backends.oauth import BaseOAuth2
class DribbbleOAuth2(BaseOAuth2):
"""Dribbble OAuth authentication backend"""
name = 'dribbble'
AUTHORIZATION_URL... |
from openerp import tools
from openerp.osv import fields, osv
class sale_report(osv.osv):
_name = "sale.report"
_description = "Sales Orders Statistics"
_auto = False
_rec_name = 'date'
_columns = {
'date': fields.datetime('Date Order', readonly=True), # TDE FIXME master: rename into date... |
import auth_crypt
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: |
from msrest.pipeline import ClientRawResponse
from .. import models
class PolymorphismOperations(object):
"""PolymorphismOperations operations.
:param client: Client for service requests.
:param config: Configuration of service client.
:param serializer: An object model serializer.
:param deseri... |
#!/usr/bin/env python
import os
import subprocess
import json
class Command(object):
def __init__(self, kubeconfig=None):
if kubeconfig is None:
print("Require a kubeconfig file")
return
self.kubeconfig=kubeconfig
def execute_cmd(self, cmd):
cmd = cmd.split()
... |
"""
.. dialect:: oracle+zxjdbc
:name: zxJDBC for Jython
:dbapi: zxjdbc
:connectstring: oracle+zxjdbc://user:pass@host/dbname
:driverurl: http://www.oracle.com/technology/software/tech/java/sqlj_jdbc/index.html.
"""
import decimal
import re
from sqlalchemy import sql, types as sqltypes, util
from sqlal... |
import re
import bleach
from django.utils.translation import ugettext_lazy as _
ALLOWED_TAGS = bleach.ALLOWED_TAGS + [
'div', 'span', 'p', 'br', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6',
'pre', 'code', 'cite',
'dl', 'dt', 'dd', 'small', 'sub', 'sup', 'u', 'strike', 'samp', 'abbr',
'ul', 'ol', 'li',
'no... |
import json, datetime
from django import forms
from django.utils.safestring import mark_safe
from django.utils.html import format_html
import utils
class Html5DateInput(forms.DateInput):
input_type = 'date'
class AngularPopupDatePicker(forms.DateInput):
def __init__(self,attrs=None,max=None,min=None):
if attrs... |
from WidgetRedirector import WidgetRedirector
from Delegator import Delegator
class Percolator:
def __init__(self, text):
# XXX would be nice to inherit from Delegator
self.text = text
self.redir = WidgetRedirector(text)
self.top = self.bottom = Delegator(text)
self.bottom.... |
ANSIBLE_METADATA = {'metadata_version': '1.0',
'status': ['preview'],
'supported_by': 'community'}
try:
from pyvcloud.schema.vcd.v1_5.schemas.vcloud.networkType import FirewallRuleType
from pyvcloud.schema.vcd.v1_5.schemas.vcloud.networkType import ProtocolsType
except ... |
import os
import re
import pep8
PYTHON_CLIENTS = ['cinder', 'glance', 'keystone', 'nova', 'swift', 'neutron',
'ironic', 'heat', 'sahara']
PYTHON_CLIENT_RE = re.compile('import (%s)client' % '|'.join(PYTHON_CLIENTS))
TEST_DEFINITION = re.compile(r'^\s*def test.*')
SETUP_TEARDOWN_CLASS_DEFINITION = ... |
import os, sys, time, signal
try:
from django.utils.six.moves import _thread as thread
except ImportError:
from django.utils.six.moves import _dummy_thread as thread
# This import does nothing, but it's necessary to avoid some race conditions
# in the threading module. See http://code.djangoproject.com/ticket... |
"""
Modules that get shown to the users when an error has occurred while
loading or rendering other modules
"""
import hashlib
import logging
import json
import sys
from lxml import etree
from xmodule.x_module import XModule, XModuleDescriptor
from xmodule.errortracker import exc_info_to_str
from xblock.fields import... |
__revision__ = "src/engine/SCons/Options/PackageOption.py 74b2c53bc42290e911b334a6b44f187da698a668 2017/11/14 13:16:53 bdbaddog"
__doc__ = """Place-holder for the old SCons.Options module hierarchy
This is for backwards compatibility. The new equivalent is the Variables/
class hierarchy. These will have deprecation... |
from __future__ import unicode_literals
from . import Infinite
from .helpers import WriteMixin
class Spinner(WriteMixin, Infinite):
message = ''
phases = ('-', '\\', '|', '/')
hide_cursor = True
def update(self):
i = self.index % len(self.phases)
self.write(self.phases[i])
class Pi... |
from gnuradio import gr, gr_unittest, blocks
class test_peak_detector(gr_unittest.TestCase):
def setUp(self):
self.tb = gr.top_block()
def tearDown(self):
self.tb = None
def test_01(self):
tb = self.tb
data = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
9, 8, 7, 6,... |
# Augmented assignment test.
x = 2
x += 1
x *= 2
x **= 2
x -= 8
x //= 2
x //= 1
x %= 12
x &= 2
x |= 5
x ^= 1
print x
x = [2]
x[0] += 1
x[0] *= 2
x[0] **= 2
x[0] -= 8
x[0] //= 2
x[0] //= 2
x[0] %= 12
x[0] &= 2
x[0] |= 5
x[0] ^= 1
print x
x = {0: 2}
x[0] += 1
x[0] *= 2
x[0] **= 2
x[0] -= 8
x[0] //= 2
x[0] //= 1
x[0]... |
import numpy as np
from random import shuffle
def softmax_loss_naive(W, X, y, reg):
"""
Softmax loss function, naive implementation (with loops)
Inputs:
- W: C x D array of weights
- X: D x N array of data. Data are D-dimensional columns
- y: 1-dimensional array of length N with labels 0...K-1, for K class... |
__all__ = ['Database']
####################################################################################################
from pathlib import Path
import yaml
####################################################################################################
class Database:
DEFAULT_DATA_DIRECTORY = Path(__f... |
import numpy as np
import fdmb
import itertools
# Header
print('fdmb test for the EM fit implementation')
print('Documentation on the data can be found in ar2Data.README', end='\n\n')
# Model parameters
obs = np.loadtxt('ar2DataObs.dat')
nData = 5000
dim = 2
order = 2
aThresh = 1e-8
pThresh = 1e-10
maxIter = np.int3... |
#!/usr/bin/env python
'''
Created on Dec 6, 2013
:author: jzupka
'''
import sys
import time
import inspect
import remote_interface
import messenger
def getsource(obj):
return inspect.getsource(obj)
def wait_timeout(timeout):
if timeout is None:
while 1:
yield True
else:
en... |
#!/usr/bin/env python
'''
Unit tests for oc adm router
'''
import os
import six
import sys
import unittest
import mock
# Removing invalid variable names for tests so that I can
# keep them brief
# pylint: disable=invalid-name,no-name-in-module
# Disable import-error b/c our libraries aren't loaded in jenkins
# pylin... |
import time
from openerp.tests.common import TransactionCase
class TestAuditlogAutovacuum(TransactionCase):
def setUp(self):
super(TestAuditlogAutovacuum, self).setUp()
self.groups_model_id = self.env.ref('base.model_res_groups').id
self.groups_rule = self.env['auditlog.rule'].create({
... |
"""Primitives for dealing with datastore indexes.
Example index.yaml file:
------------------------
indexes:
- kind: Cat
ancestor: no
properties:
- name: name
- name: age
direction: desc
- kind: Cat
properties:
- name: name
direction: ascending
- name: whiskers
direction: descending
- kin... |
import zlib
from . import register_test
# Detect blacklisted files based on their extension.
blacklisted_extensions = ("dll", "exe", "dylib", "so", "sh", "class")
blacklisted_magic_numbers = (
(0x4d, 0x5a), # EXE/DLL
(0x5a, 0x4d), # Alternative for EXE/DLL
(0x7f, 0x45, 0x4c, 0x46), # UNIX ... |
import types
def gen1():
yield 1
yield 2
yield 3
g = gen1()
assert isinstance(g, types.GeneratorType)
assert list(g) == [1, 2, 3]
assert list(g) == [] # pylint: disable=g-explicit-bool-comparison
def gen2():
for c in 'foobar':
yield c
yield '!'
g = gen2()
assert list(g) == ['f', 'o', 'o', 'b', 'a', '... |
ANSIBLE_METADATA = {'status': ['preview'],
'supported_by': 'community',
'version': '1.0'}
import base64
import hashlib
from ansible.module_utils.ipa import IPAClient
class UserIPAClient(IPAClient):
def __init__(self, module, host, port, protocol):
super(UserIPACli... |
import fabric
FABRIC = fabric.createClient()
class Vec3():
def __init__( self, x = None, y = None, z = None ):
if type( x ) is int and type( y ) is int and type( z ) is int:
self.x = x
self.y = y
self.z = z
elif x is None and y is None and z is None:
self.x = 0
self.y = 0
... |
from django.template.defaultfilters import phone2numeric_filter
from django.test import SimpleTestCase
from django.utils.safestring import mark_safe
from ..utils import setup
class Phone2numericTests(SimpleTestCase):
@setup({'phone2numeric01': '{{ a|phone2numeric }} {{ b|phone2numeric }}'})
def test_phone2n... |
class SortByType(object):
"""
PUBLISH_DATE:
Date title was published
CREATION_DATE:
Date title was created.
MODIFIED_DATE
Date title was last modified.
PLAYS_TOTAL
Number of times this title has been viewed.
PLAYS_TRAILING_WEEK
Number of times this tit... |
"""
RAR parser
Status: can only read higher-level attructures
Author: Christophe Gisquet
"""
from hachoir_parser import Parser
from hachoir_core.field import (StaticFieldSet, FieldSet,
Bit, Bits, Enum,
UInt8, UInt16, UInt32, UInt64,
String, TimeDateMSDOS32,
NullBytes, NullBits, RawBytes)
from hachoir_... |
"""
Collection of KBucket classes storing contacts for RoutingTables.
Classes:
KBucket -- A classic k-bucket.
CachingKBucket -- A KBucket with a replacement cache.
Exceptions:
FullBucketError -- Raised when adding a contact to a full KBucket.
"""
import collections
import functools
from dht import const... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.