content stringlengths 4 20k |
|---|
bodyDefault = '''
importScripts('worker-testharness.js');
importScripts('test-helpers.sub.js');
importScripts('/common/get-host-info.sub.js');
var host_info = get_host_info();
test(function() {
var import_script_failed = false;
try {
importScripts(host_info.HTTPS_REMOTE_ORIGIN +
base_path() + 'e... |
# encoding: utf-8
from __future__ import unicode_literals
import json
from .common import InfoExtractor
from ..utils import (
int_or_none,
js_to_json,
)
class KrasViewIE(InfoExtractor):
IE_DESC = 'Красвью'
_VALID_URL = r'https?://krasview\.ru/(?:video|embed)/(?P<id>\d+)'
_TEST = {
'url'... |
"""
Routines for configuring Glance
"""
import logging
import logging.config
import logging.handlers
import os
import sys
from oslo.config import cfg
from paste import deploy
from glance.version import version_info as version
paste_deploy_opts = [
cfg.StrOpt('flavor',
help=_('Partial name of a pi... |
__all__ = ("IEngineFactory", )
import dbus.service
from ibus.common import \
IBUS_IFACE_ENGINE_FACTORY
class IEngineFactory(dbus.service.Object):
# define method decorator.
method = lambda **args: \
dbus.service.method(dbus_interface=IBUS_IFACE_ENGINE_FACTORY, \
**args)... |
from vanilla import CheckBoxListCell
from mechanic.storage import Storage
from mechanic.extension import Extension
from mechanic.ui.lists.extension import ExtensionList
from mechanic.ui.formatters.version import VersionFormatter
class SettingsList(ExtensionList):
"""Return an ExtensionList for settings window.""... |
from sqlparse import sql, tokens as T
from sqlparse.compat import text_type
from sqlparse.utils import offset, indent
class ReindentFilter(object):
def __init__(self, width=2, char=' ', wrap_after=0, n='\n',
comma_first=False):
self.n = n
self.width = width
self.char = cha... |
# Generic set of parameters to use with base local planners
# To use:
#
# from local_planner_limits import add_generic_localplanner_params
# gen = ParameterGenerator()
# add_generic_localplanner_params(gen)
# ...
#
# Using these standard parameters instead of your own allows easier switching of local planners
# ne... |
""" Crazy hacks to make bugzilla work without throwing SSL timeouts. """
import sys
import urllib2
import xmlrpclib
# If we're not on python2.7, we assume we're on python2.6.
PY27 = (
sys.version_info[0] == 2 and
sys.version_info[1] == 7
)
def hotpatch_bugzilla():
""" Hotpatch or "duck-punch" bugzilla.... |
"""Support for Stochastic Computation Graphs.
See the @{$python/contrib.bayesflow.stochastic_graph} guide.
@@surrogate_loss
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
# go/tf-wildcard-import
# pylint: disable=wildcard-import
from tensorflow.contr... |
#!/usr/bin/env python
# coding=utf-8
""" A configurable Hello World "experiment".
In this example we configure the message using a dictionary with
``ex.add_config``
You can run it like this::
$ ./02_hello_config_dict.py
WARNING - 02_hello_config_dict - No observers have been added to this run
INFO - 02_hello_co... |
"""Presubmit script for perf_expectations.
See http://dev.chromium.org/developers/how-tos/depottools/presubmit-scripts for
details on the presubmit API built into gcl.
"""
PERF_EXPECTATIONS = 'tools/perf_expectations/perf_expectations.json'
CONFIG_FILE = 'tools/perf_expectations/chromium_perf_expectations.cfg'
def C... |
"""Support for the Lyft API."""
from datetime import timedelta
import logging
from lyft_rides.auth import ClientCredentialGrant
from lyft_rides.client import LyftRidesClient
from lyft_rides.errors import APIError
import voluptuous as vol
from homeassistant.components.sensor import PLATFORM_SCHEMA, SensorEntity
from h... |
__all__ = ['abs', 'absolute', 'add', 'arccos', 'arccosh', 'arcsin', 'arcsinh',
'arctan', 'arctan2', 'arctanh', 'bitwise_and', 'bitwise_not',
'bitwise_or', 'bitwise_xor', 'ceil', 'cos', 'cosh', 'divide',
'equal', 'exp', 'fabs', 'floor', 'floor_divide',
'fmod', 'greater', 'grea... |
#############################################################################
#############################################################################
import common
from common import *
from common import (addon_id,addon_name,addon_path)
######################################################################... |
import socket
import binascii
import re
import logging
import time
from contextlib import contextmanager
from functools import wraps
from django.conf import settings
from paucore.stats.slowjam import slowjam_context
logger = logging.getLogger(__name__)
class DummySocket(object):
def sendto(self, value, addr):... |
"""
Tests for the milestones helpers library, which is the integration point for the edx_milestones API
"""
from mock import patch
from milestones.exceptions import InvalidCourseKeyException, InvalidUserException
from util import milestones_helpers
from xmodule.modulestore.tests.django_utils import ModuleStoreTestCas... |
"""
A smarter {% if %} tag for django templates.
While retaining current Django functionality, it also handles equality,
greater than and less than operators. Some common case examples::
{% if articles|length >= 5 %}...{% endif %}
{% if "ifnotequal tag" != "beautiful" %}...{% endif %}
"""
import unit... |
"""Base Command class, and related routines"""
from __future__ import absolute_import
import logging
import os
import sys
import optparse
import warnings
from pip import cmdoptions
from pip.index import PackageFinder
from pip.locations import running_under_virtualenv
from pip.download import PipSession
from pip.excep... |
import os
from xdg.BaseDirectory import xdg_config_home
from ulauncher.search.apps.AppDb import AppDb
from ulauncher.utils.desktop.DesktopParser import DesktopParser
class AutostartPreference:
AUTOSTART_FLAG = 'X-GNOME-Autostart-enabled'
_ulauncher_desktop = None # path to ulauncher.desktop
_ulauncher_... |
##### Description of this python file #####
# This is the start location for preprocessing script for the data preparation prior to running the model
##### VARIABLES - Used in this file#####
#
#---------------------------------------------------------------------#
##### START OF CODE #####
### Import statements - ... |
import os
import string
import cherrypy
from sickbeard import encodingKludge as ek
# use the built-in if it's available (python 2.6), if not use the included library
try:
import json
except ImportError:
from lib import simplejson as json
# this is for the drive letter code, it only works on windo... |
import vulpo
from vulpo.pyami.scriptbase import ScriptBase
import os, StringIO
class CopyBot(ScriptBase):
def __init__(self):
super(CopyBot, self).__init__()
self.wdir = vulpo.config.get('Pyami', 'working_dir')
self.log_file = '%s.log' % self.instance_id
self.log_path = os.path.joi... |
import time
start_time = time.time()
import numpy as np
from sklearn.metrics import precision_recall_curve, roc_curve, auc
from sklearn.cross_validation import ShuffleSplit
from utils import plot_pr
from utils import load_sanders_data
from utils import tweak_labels
from sklearn.feature_extraction.text import TfidfV... |
"""Usage:
python compare.py <path to text file with annotated data> <path to config file>
"""
import sys
import os
import codecs
import csv
import logging
from collections import Counter
from bitext import Bitext
from chatterbox import Chatterbox
from datumbox import Datumbox
from lymbix import Lymbix... |
import mock
import requests
import novaclient.client
import novaclient.extension
import novaclient.tests.fakes as fakes
import novaclient.v1_1.client
import novaclient.v3.client
from novaclient.tests import utils
import json
class ClientTest(utils.TestCase):
def test_client_with_timeout(self):
instance... |
import sys
try:
import boto.ec2
HAS_BOTO = True
except ImportError:
HAS_BOTO = False
def main():
argument_spec = ec2_argument_spec()
argument_spec.update(dict(
resource = dict(required=True),
tags = dict(),
state = dict(default='present', choices=['present', 'a... |
"""The Internet Printing Protocol (IPP) integration."""
from __future__ import annotations
from datetime import timedelta
import logging
from pyipp import IPP, IPPError, Printer as IPPPrinter
from homeassistant.components.sensor import DOMAIN as SENSOR_DOMAIN
from homeassistant.config_entries import ConfigEntry
from... |
from django.db.models.fields import Field
from django.db.models.sql.expressions import SQLEvaluator
from django.utils.translation import ugettext_lazy as _
from django.contrib.gis import forms
from django.contrib.gis.db.models.constants import GIS_LOOKUPS
from django.contrib.gis.db.models.lookups import GISLookup
from ... |
import sys
if len(sys.argv)==1:
print "Usage: main.py cfg_file [cfg_site]"
print "Example:"
print " main.py cfg_gnu"
print " main.py cfg_gnu custom_cfg_site"
sys.exit(1)
args = []
args.extend(sys.argv)
args.remove(args[1])
args.remove(args[0])
cfg_file = __import__(sys.argv[1])
builders = cfg_... |
""" Search index used to load data into elasticsearch"""
import logging
from elasticsearch.exceptions import ConnectionError
from django.conf import settings
from django.db.models.signals import post_delete, post_save
from django.dispatch import receiver
from django.utils import translation
from functools import wrap... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import time
from datetime import datetime, timedelta
from ansible.module_utils._text import to_text
from ansible.plugins.action import ActionBase
from ansible.utils.display import Display
display = Display()
class TimedOutExcep... |
"""
========
numpydoc
========
Sphinx extension that handles docstrings in the Numpy standard format. [1]
It will:
- Convert Parameters etc. sections to field lists.
- Convert See Also section to a See also entry.
- Renumber references.
- Extract the signature from the docstring, if it can't be determined otherwise.... |
from __future__ import absolute_import, division, unicode_literals
import os
import sys
import traceback
import warnings
import re
warnings.simplefilter('error')
from .support import get_data_files
from .support import TestData, convert, convertExpected, treeTypes
from html5lib import html5parser, constants
# Run t... |
#! /usr/bin/python
"""A simple plugin to connect rsyslog to SOLR
Based on Radu Gheorghe's idea as expressed in
http://blog.sematext.com/2013/12/16/video-using-solr-for-logs-with-rsyslog-flume-fluentd-and-logstash/
Watch out for slide 26.
Copyright (C) 2014 by Adiscon GmbH
This file is part of rsyslog... |
import sys
import os
from TinyIDS.collector import BaseCollector
DEFAULT_GLOB_EXP = (
'/usr/local/sbin/*',
'/usr/local/bin/*',
'/sbin/*',
'/bin/*',
'/usr/sbin/*',
'/usr/bin/*',
'/root/bin/*',
'/lib/*',
'/usr/lib/*',
'/usr/local/lib/*',
)
class CollectorBackend(BaseCollector)... |
"""
Commands to be used in pyroman rules files.
allow, reject, drop are just convenience commands, that can be replaced by
add_rule(Firewall.allow, ...) etc. but that are easier to read.
"""
#Copyright (c) 2011 Erich Schubert <EMAIL>
#Permission is hereby granted, free of charge, to any person obtaining a copy
#of th... |
"""distutils.command.build
Implements the Distutils 'build' command."""
# This module should be kept compatible with Python 2.1.
__revision__ = "$Id: build.py 37828 2004-11-10 22:23:15Z loewis $"
import sys, os
from distutils.core import Command
from distutils.util import get_platform
def show_compilers ():
f... |
# -*- coding: utf-8 -*-
"""
pygments.lexers.markup
~~~~~~~~~~~~~~~~~~~~~~
Lexers for non-HTML markup languages.
:copyright: Copyright 2006-2014 by the Pygments team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
import re
from pygments.lexer import RegexLexer, include, bygroups, using... |
r"""JSON (JavaScript Object Notation) <http://json.org> is a subset of
JavaScript syntax (ECMA-262 3rd edition) used as a lightweight data
interchange format.
:mod:`simplejson` exposes an API familiar to users of the standard library
:mod:`marshal` and :mod:`pickle` modules. It is the externally maintained
version of ... |
from __future__ import absolute_import, division, print_function
import unittest
import numpy as np
import datashape
import blaze
from blaze.datadescriptor import dd_as_py
from blaze.tests.common import MayBeUriTest
from blaze import append
from blaze.py2help import skip
class TestEphemeral(unittest.TestCase):
... |
import xml.etree.ElementTree as ET
import codecs
def indent(elem, level=0):
i = "\n" + level*" "
if len(elem):
if not elem.text or not elem.text.strip():
elem.text = i + " "
if not elem.tail or not elem.tail.strip():
elem.tail = i
for elem in elem:
... |
"""Handle version information related to Visual Stuio."""
import errno
import os
import re
import subprocess
import sys
import gyp
class VisualStudioVersion(object):
"""Information regarding a version of Visual Studio."""
def __init__(self, short_name, description,
solution_version, project_versi... |
#!/usr/bin/env python
from __future__ import print_function
import json
import optparse
import os
import subprocess
import sys
import tempfile
CHUNK_SIZE = 2**20
DEFAULT_DATA_TABLE_NAME = "bowtie_indexes"
def get_id_name( params, dbkey, fasta_description=None):
# TODO: ensure sequence_id is unique and does not... |
"""A simple Set class."""
class Set(object):
"""A simple set class.
Sets are not in Python until 2.3, and rdata are not immutable so
we cannot use sets.Set anyway. This class implements subset of
the 2.3 Set interface using a list as the container.
@ivar items: A list of the items which are in t... |
#! /usr/bin/env python
"""This script handles reading command line arguments and starting the
training process. It shouldn't be executed directly; it is used by
run_nips.py or run_nature.py.
"""
import os
import argparse
import logging
import ale_python_interface
import cPickle
import ale_experiment
import ale_agent... |
import os
import sys
if "--testbase2" in sys.argv:
testbase2 = True
else:
testbase2 = False
computername = os.environ.get('COMPUTERNAME',"any").lower()
DEBUG = False
TEMPLATE_DEBUG = DEBUG
ADMINS = (
# ('Your Name', 'somebody_fill_me_in'),
)
MANAGERS = ADMINS
#define your database here (may have to chang... |
from yowsup.structs import ProtocolEntity, ProtocolTreeNode
from .iq_groups import GroupsIqProtocolEntity
class ListGroupsIqProtocolEntity(GroupsIqProtocolEntity):
'''
<iq id="{{id}}"" type="get" to="g.us" xmlns="w:g2">
<"{{participating | owning}}"></"{{participating | owning}}">
</iq>
res... |
"""Integration providing core pieces of infrastructure."""
import asyncio
import itertools as it
import logging
from typing import Awaitable
import voluptuous as vol
import homeassistant.core as ha
import homeassistant.config as conf_util
from homeassistant.exceptions import HomeAssistantError
from homeassistant.help... |
from lcc.stars_processing.utilities.base_decider import BaseDecider
from lcc.entities.exceptions import QueryInputError
class CustomDecider(BaseDecider):
'''
This decider allows to specify ranges of coordinates got from descriptors.
So there is no need to run `learn` method. Anyway it is implemented
t... |
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
unicode_literals, with_statement)
import BaseHTTPServer
import itertools
import json
import logging
import mimetypes
import os
import pkgutil
import re
import urllib
import urlparse
from collections im... |
import warnings
from django.template import Library
from django.template import defaulttags
from django.utils.deprecation import RemovedInDjango19Warning
register = Library()
@register.tag
def ssi(parser, token):
warnings.warn(
"Loading the `ssi` tag from the `future` library is deprecated and "
... |
from __future__ import unicode_literals
import datetime
import decimal
from collections import defaultdict
from django.contrib.auth import get_permission_codename
from django.core.exceptions import FieldDoesNotExist
from django.db import models
from django.db.models.constants import LOOKUP_SEP
from django.db.models.d... |
import datetime
import json
import mock
from nose.tools import eq_, ok_
from crontabber.app import CronTabber
from socorro.unittest.cron.setup_configman import (
get_config_manager_for_crontabber,
)
from socorro.lib.datetimeutil import utc_now
from socorro.unittest.cron.jobs.base import IntegrationTestBase
from... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#This is a Python version of the op-reference.rb sample script written
#by Øyvind Kolås for the Ruby binding (rgegl) of gegl.
import Gegl
import gobject
operations = Gegl.list_operations()
print "<html><body>"
print "<ul>"
for operation_name in operations:
print "<li... |
# This is Python example on how to use Mongoose embeddable web server,
# http://code.google.com/p/mongoose
#
# Before using the mongoose module, make sure that Mongoose shared library is
# built and present in the current (or system library) directory
import mongoose
import sys
# Handle /show and /form URIs.
def Even... |
"""Cancel old, duplicate tests of the same pr.
This can happen with repeated '/test all' commands, or
even something as simple as pushing new code while builds are already queued.
"""
import sys
import requests
def prune(host):
"""Cancel old, duplicate tests of the same pr."""
queue = requests.get('http://... |
from i18n import _
import struct
import sys, os
import dispatch, encoding, util
logfile = None
def log(*args):
if not logfile:
return
for a in args:
logfile.write(str(a))
logfile.flush()
class channeledoutput(object):
"""
Write data from in_ to out in the following format:
... |
from six import StringIO
import pandas as pd
def parse_metadata(descr_table):
parser = MetadataParser(descr_table)
return parser.parse()
def _noop(tup):
return None
def _item_converter(i):
def _get_item(converter=None):
def _converter(tup):
result = tup[i]
if conver... |
import collections
import logging
logger = logging.getLogger(__name__)
class Event(object):
"""
An event sent through the dfms framework.
Events have at least a field describing the type of event they are (instead
of having subclasses of the `Event` class), and therefore this class makes
sure th... |
import unittest
import logging
import struct
from struct import *
from nose.tools import *
from ryu.ofproto import ether
from ryu.lib.packet.ethernet import ethernet
from ryu.lib.packet.packet import Packet
from ryu.lib.packet.arp import arp
from ryu.lib.packet.vlan import vlan
from ryu.lib import addrconv
LOG = logg... |
# coding: utf-8
# In[56]:
get_ipython().magic(u'matplotlib inline')
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.ticker import FuncFormatter
df = pd.read_excel("https://github.com/chris1610/pbpython/blob/master/data/sample-salesv3.xlsx?raw=true")
df.head(n=10)
# In[57]:
... |
from ..mixin import ValueType
class IntConstraint(ValueType):
__slots__ = "width min max".split()
def __init__(self, width, min_, max_):
self.width = width
self.min = min_
self.max = max_
# self.isBot = (-min_ == max_+1 == (1<<width)//2)
@staticmethod
def range(width, ... |
# Check every path through every method of UserList
from collections import UserList
from test import support, list_tests
class UserListTest(list_tests.CommonTest):
type2test = UserList
def test_getslice(self):
super().test_getslice()
l = [0, 1, 2, 3, 4]
u = self.type2test(... |
from sos.plugins import Plugin, RedHatPlugin, DebianPlugin, UbuntuPlugin
class OpenStackHorizon(Plugin):
"""OpenStack Horizon
"""
plugin_name = "openstack_horizon"
profiles = ('openstack', 'openstack_controller')
option_list = []
def setup(self):
self.limit = self.get_option("log_si... |
import copy
from oslotest import mockpatch
from tempest.lib.services.compute import versions_client
from tempest.tests.lib import fake_auth_provider
from tempest.tests.lib.services.compute import base
class TestVersionsClient(base.BaseComputeServiceTest):
FAKE_INIT_VERSION = {
"version": {
"... |
"""
CommonObject is the object that players can put into their inventory.
"""
from muddery.utils.localized_strings_handler import _
from muddery.typeclasses.common_objects import MudderyFood, MudderyEquipment
class Food(MudderyFood):
"""
This is a food. Players can use it to change their properties, such as... |
"""Add cache per rlms type
Revision ID: 1a3e5ec9c2fd
Revises: 7f806cb0445
Create Date: 2015-05-06 16:33:34.158433
"""
# revision identifiers, used by Alembic.
revision = '1a3e5ec9c2fd'
down_revision = '7f806cb0445'
from alembic import op
import sqlalchemy as sa
def upgrade():
### commands auto generated by Al... |
# -*- coding: utf-8 -*-
"""
pygments.lexers.iolang
~~~~~~~~~~~~~~~~~~~~~~
Lexers for the Io language.
:copyright: Copyright 2006-2015 by the Pygments team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
from pygments.lexer import RegexLexer
from pygments.token import Text, Comment, Oper... |
r"""
=====================================================================
The Johnson-Lindenstrauss bound for embedding with random projections
=====================================================================
The `Johnson-Lindenstrauss lemma`_ states that any high dimensional
dataset can be randomly projected i... |
"""Parser engine for the grammar tables generated by pgen.
The grammar table must be loaded first.
See Parser/parser.c in the Python distribution for additional info on
how this parsing engine works.
"""
import pytoken as token
import pysymbol as symbol
class Node:
def __init__(self, type, value, context, chil... |
import hr_timesheet_sign_in_out
import hr_timesheet_print_employee
import hr_timesheet_print_users
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: |
from openerp import api, models, fields
from .. import match_algorithm
class fetchmail_server_folder(models.Model):
_name = 'fetchmail.server.folder'
_rec_name = 'path'
_order = 'sequence'
def _get_match_algorithms(self):
def get_all_subclasses(cls):
return (cls.__subclasses__() +... |
"""
REST API Documentation for the NRS TFRS Credit Trading Application
The Transportation Fuels Reporting System is being designed to streamline compliance reporting for transportation fuel suppliers in accordance with the Renewable & Low Carbon Fuel Requirements Regulation.
OpenAPI spec version: v1
... |
""" Django REST Framework Serializers """
from django.core.urlresolvers import reverse
from rest_framework import serializers
from courseware.courses import course_image_url
class CourseSerializer(serializers.Serializer):
""" Serializer for Courses """
id = serializers.CharField() # pylint: disable=invalid... |
"""
Visibility Transformer implementation.
"""
from openedx.core.lib.block_structure.transformer import BlockStructureTransformer, FilteringTransformerMixin
from .utils import collect_merged_boolean_field
class VisibilityTransformer(FilteringTransformerMixin, BlockStructureTransformer):
"""
A transformer that... |
from django.db import models
from django.core.urlresolvers import reverse
from common.models import TimestampedModel
from postgres.fields import JSONField # Using schinckel/django-postgres until Django 1.9
from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.models import C... |
# -*- coding: utf-8 -*-
"""
jinja2.loaders
~~~~~~~~~~~~~~
Jinja loader classes.
:copyright: (c) 2010 by the Jinja Team.
:license: BSD, see LICENSE for more details.
"""
import os
import sys
import weakref
from types import ModuleType
from os import path
try:
from hashlib import sha1
except Imp... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['deprecated'],
'supported_by': 'community'}
import os
import re
from ansible.module_utils.basic import AnsibleModule
# get list o... |
"""
ldap.modlist - create add/modify modlist's
See http://www.python-ldap.org/ for details.
$Id: modlist.py,v 1.17 2009/07/26 11:09:58 stroeder Exp $
Python compability note:
This module is known to work with Python 2.0+ but should work
with Python 1.5.2 as well.
"""
from ldap import __version__
import string,ldap... |
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
def g(x,sigma = 0.1):
return np.exp(-x**2/sigma**2)
def fromdistance(fn, shape, center=None, dtype=float):
def distance(*args):
d = 0
for i in range(len(shape)):
d += ((args[i]-center[i])/float(max(1,shape[i]-1))... |
try:
import requests
except ImportError:
message = ('Missing "requests", please install it using pip:\n'
'pip install requests')
raise ImportError(message)
try:
import json
except ImportError:
message = ('Missing "json", please install it using pip:\n'
'pip install jso... |
"""
Python Interchangeable Virtual Instrument Library
Copyright (c) 2012-2017 Alex Forencich
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the... |
# -*- coding: utf-8 -*-
from __future__ import with_statement
from cms.test_utils.compat import skipIf
from cms.test_utils.testcases import CMSTestCase
from cms.test_utils.util.context_managers import TemporaryDirectory
from sphinx.application import Sphinx
import cms
import os
import socket
from cms.utils.compat.strin... |
# Offers example of inline C for binary search algorithm.
# Borrowed from Kalle Svensson in the Python Cookbook.
# The results are nearly in the "not worth it" category.
#
# C:\home\ej\wrk\scipy\compiler\examples>python binary_search.py
# Binary search for 3000 items in 100000 length list of integers:
# speed in pytho... |
# PYTHON_ARGCOMPLETE_OK
"""
pytest: unit and functional testing with Python.
"""
# else we are imported
from _pytest.config import (
main, UsageError, cmdline,
hookspec, hookimpl
)
from _pytest.fixtures import fixture, yield_fixture
from _pytest.assertion import register_assert_rewrite
from _pytest.freeze_su... |
# Create your views here.
from django.http import HttpResponse,HttpResponseRedirect
from django.template import RequestContext
from django.shortcuts import render_to_response,redirect
from django.contrib.auth import authenticate, login,logout
from django.contrib.auth.decorators import login_required
# our own models ... |
"""
Tests that a loadable_module target is built correctly.
"""
import TestGyp
import os
import struct
import sys
if sys.platform == 'darwin':
test = TestGyp.TestGyp(formats=['ninja', 'make', 'xcode'])
CHDIR = 'loadable-module'
test.run_gyp('test.gyp', chdir=CHDIR)
test.build('test.gyp', test.ALL, chdir=CH... |
import posixpath
import sys
from file_system import FileSystem, StatInfo, FileNotFoundError
from future import All, Future
from path_util import AssertIsDirectory, IsDirectory, ToDirectory
from third_party.json_schema_compiler.memoize import memoize
class CachingFileSystem(FileSystem):
'''FileSystem which implemen... |
#! /usr/bin/python3
"""
Broadcast a message, with or without a price.
Multiple messages per block are allowed. Bets are be made on the 'timestamp'
field, and not the block index.
An address is a feed of broadcasts. Feeds may be locked with a broadcast whose
text field is identical to ‘lock’ (case insensitive). Bets ... |
from __future__ import unicode_literals
import re
from django.core.exceptions import FieldDoesNotExist
from django.db.models.constants import LOOKUP_SEP
from django.db.models.expressions import Col, ExpressionNode
from django.db.models.lookups import Lookup
from django.utils import six
gis_lookups = {}
class GISLo... |
#!/usr/bin/env python
"""Tests for the file export tool plugin."""
import argparse
import os
from grr.lib import access_control
from grr.lib import aff4
from grr.lib import data_store
from grr.lib import flags
from grr.lib import test_lib
from grr.lib import utils
from grr.tools.export_plugins import file_plugin
c... |
"""Tests for acme.fields."""
import datetime
import unittest
import pytz
from acme import jose
class RFC3339FieldTest(unittest.TestCase):
"""Tests for acme.fields.RFC3339Field."""
def setUp(self):
self.decoded = datetime.datetime(2015, 3, 27, tzinfo=pytz.utc)
self.encoded = '2015-03-27T00:0... |
# Read in a hyperspectral data cube as an array and parse metadata from the header file
import os
import cv2
import numpy as np
from plantcv.plantcv import params
from plantcv.plantcv import plot_image
from plantcv.plantcv import print_image
from plantcv.plantcv import Spectral_data
from plantcv.plantcv.transform impo... |
import os
from PyQt4 import QtGui
from src.common.widgets import VerticalContainer
from src.common.utils import load_css_for_widget, BURNER_VERSION
from src.common.paths import images_path, anim_path, css_path
# App dimensions constants
APP_WIDTH = 500
APP_HEIGHT = 330
CONTAINER_HEIGHT = 140
# These are used as obje... |
"""
This config file runs the simplest dev environment"""
# We intentionally define lots of variables that aren't used, and
# want to import all variables from base settings files
# pylint: disable=W0401, W0614
from .common import *
from logsettings import get_logger_config
# import settings from LMS for consistent ... |
from os import path
from errbot import BotPlugin, botcmd
def tail(f, window=20):
return ''.join(f.readlines()[-window:])
class Utils(BotPlugin):
# noinspection PyUnusedLocal
@botcmd
def echo(self, _, args):
""" A simple echo command. Useful for encoding tests etc ...
"""
re... |
"""This code example creates new creative sets.
To determine which creative sets exist, run get_all_creative_sets.py.
The LoadFromStorage method is pulling credentials and properties from a
"googleads.yaml" file. By default, it looks for this file in your home
directory. For more information, see the "Caching authent... |
import re
import vim
from ycm import vimsupport
SYNTAX_GROUP_REGEX = re.compile(
r"""^
(?P<group_name>\w+)
\s+
xxx
\s+
(?P<content>.+?)
$""",
re.VERBOSE )
KEYWORD_REGEX = re.compile( r'^[\w,]+$' )
SYNTAX_ARGUMENT_REGEX = re.compile(
r"^\w+=.*$" )
SYNTAX_ARGUMENTS = set([
... |
from JumpScale import j
from collections import OrderedDict
class ModelBase():
def __init__(self, capnp_schema, category, db, index, key="", new=False):
self.logger = j.logger.get(capnp_schema.schema.node.displayName) # TODO find something better than this
self._capnp_schema = capnp_schema
... |
"""Test the Firmata config flow."""
from unittest.mock import patch
from pymata_express.pymata_express_serial import serial
from homeassistant import config_entries, setup
from homeassistant.components.firmata.const import CONF_SERIAL_PORT, DOMAIN
from homeassistant.const import CONF_NAME
from homeassistant.core impo... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.