content stringlengths 4 20k |
|---|
"""Brings inception_v1, inception_v2 and inception_v3 under one namespace."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
# pylint: disable=unused-import
from tensorflow.contrib.slim.python.slim.nets.inception_v1 import inception_v1
from tensorflow.cont... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import os
from ast import literal_eval
from jinja2 import Template
from string import ascii_letters, digits
from ansible.module_utils._text import to_text
from ansible.module_utils.parsing.convert_bool import boolean, BOOLEANS_TR... |
from __future__ import unicode_literals
from .common import InfoExtractor
from ..compat import compat_str
from ..utils import (
clean_html,
float_or_none,
int_or_none,
try_get,
)
class HitRecordIE(InfoExtractor):
_VALID_URL = r'https?://(?:www\.)?hitrecord\.org/records/(?P<id>\d+)'
_TEST = {
... |
import sys
import logging
import binascii
from urllib.parse import quote_plus as urlencode
from counterpartylib.lib import config, script
from counterpartycli import util
from counterpartycli import wallet
from counterpartycli import messages
from counterpartycli.messages import get_pubkeys
logger = logging.getLogger... |
from __future__ import division, absolute_import, print_function
import re
import itertools
def isBlank(line):
return not line
def isLabel(line):
return line[0].isdigit()
def isComment(line):
return line[0] != ' '
def isContinuation(line):
return line[5] != ' '
COMMENT, STATEMENT, CONTINUATION = 0, 1... |
import re
from flask import url_for
import pytest
from selenium.webdriver.common.by import By
from tests.helpers import slow
from tests.integration.integration_helpers import (
enter_api_token,
go_to_home_page,
wait_for_element,
wait_for_title,
)
@pytest.mark.usefixtures('live_server')
@slow
class T... |
import struct
import unittest2
from kafka.codec import (
has_snappy, gzip_encode, gzip_decode,
snappy_encode, snappy_decode
)
from kafka.protocol import (
create_gzip_message, create_message, create_snappy_message, KafkaProtocol
)
from testutil import *
class TestCodec(unittest2.TestCase):
def test_gz... |
"""
Common functions for the SSH classes.
Maintainer: Paul Swartz
"""
import struct, warnings
try:
from Crypto import Util
except ImportError:
warnings.warn("PyCrypto not installed, but continuing anyways!",
RuntimeWarning)
from twisted.python import randbytes
def NS(t):
"""
net string... |
from helpers import LuigiTestCase
import luigi
import luigi.interface
import tempfile
import re
_testing_glob_var = None
class CmdlineTest(LuigiTestCase):
def test_dynamic_loading(self):
with tempfile.NamedTemporaryFile(dir='test/', prefix="_foo_module", suffix='.py') as temp_module_file:
t... |
import OpenPNM
import scipy as sp
class SurfaceTensionTest:
def setup_class(self):
self.net = OpenPNM.Network.Cubic(shape=[3, 3, 3])
self.phase = OpenPNM.Phases.GenericPhase(network=self.net)
self.phase['pore.temperature'] = 298.0 # K
self.phase['pore.molecular_weight'] = 0.018 #... |
import luigi
import luigi.contrib.hadoop
import luigi.contrib.hdfs
# To make this run, you probably want to edit /etc/luigi/client.cfg and add something like:
#
# [hadoop]
# jar: /usr/lib/hadoop-xyz/hadoop-streaming-xyz-123.jar
class InputText(luigi.ExternalTask):
"""
This task is a :py:class:`luigi.task.Ex... |
"""Tankerkoenig sensor integration."""
import logging
from homeassistant.const import (
ATTR_ATTRIBUTION,
ATTR_LATITUDE,
ATTR_LONGITUDE,
CURRENCY_EURO,
)
from homeassistant.helpers.update_coordinator import (
CoordinatorEntity,
DataUpdateCoordinator,
UpdateFailed,
)
from .const import DOM... |
#!/usr/bin/env python
"""
Build F90 module support for f2py2e.
Copyright 2000 Pearu Peterson all rights reserved,
Pearu Peterson <<EMAIL>>
Permission to use, modify, and distribute this software is given under the
terms of the NumPy License.
NO WARRANTY IS EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.
$Date: 2005/02/... |
# -*- coding: utf-8 -*-
"""
***************************************************************************
py
---------------------
Date : August 2012
Copyright : (C) 2012 by Victor Olaya
Email : volayaf at gmail dot com
***************************************... |
# -*- coding: utf-8 -*-
from semantics import *
from vm import *
# Clase que maneja el mapeo de memoria del lenguaje.
class Memory:
# Se inicializa una instancia de la clase memoria. Se le asigna el nombre de
# la función y se asigna memoria dependiendo de la memoria que esta función
# haya marcado que necesite p... |
"""
Main abstraction layer for retrieving and storing information about disk
images used by the compute layer.
"""
from nova.image import glance
class API(object):
"""Responsible for exposing a relatively stable internal API for other
modules in Nova to retrieve information about disk images. This API
a... |
#!/usr/bin/python
import os
import sys
import hooking
import traceback
import guestfs
'''
fileinject vdsm hook
====================
hook is getting target file name and its content and
create that file in target machine.
hook will try to add the file only to the operation system
partition, i.e.
Windows: /c/myfile
L... |
#!/usr/bin/env python
#-*- coding:utf-8 -*-
"""
A module to use Allocine API V3 in Python
Repository: https://github.com/xbgmsharp/allocine
Base on work from: https://github.com/gromez/allocine-api
License: LGPLv2 http://www.gnu.org/licenses/lgpl.html
Sample code:
from allocine import allocine
api = allocine(... |
"""
Wrapper for loading templates from "templates" directories in INSTALLED_APPS
packages.
"""
import os
import sys
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from django.template.base import TemplateDoesNotExist
from django.template.loader import BaseLoader
from django.u... |
__all__ = [
'Process', 'current_process', 'active_children', 'freeze_support',
'Lock', 'RLock', 'Semaphore', 'BoundedSemaphore', 'Condition',
'Event', 'Barrier', 'Queue', 'Manager', 'Pipe', 'Pool', 'JoinableQueue'
]
#
# Imports
#
import threading
import sys
import weakref
#brython fix me
#import array... |
ur"""<rst>
Plugin for the Speed-Link Media Remote Control (SL-6399)
"""
import eg
eg.RegisterPlugin(
name = "Speed-Link SL-6399 Media Remote",
author = "Bitmonster",
version = "1.0.0",
kind = "remote",
guid = "{ED814A18-5379-46B5-9A3B-65449C21871E}",
description = __doc__,
hardwareId = "U... |
from __future__ import unicode_literals
import frappe
import json
import re
from frappe import _
from frappe.utils import nowdate
def execute(filters=None):
if not filters: filters.setdefault('posting_date', [nowdate(), nowdate()])
columns, data = [], []
columns = get_columns()
data = get_data(filters)
return col... |
import json
import urllib
def main():
queryurl = 'https://archive.org/advancedsearch.php?q=collection%3Awikimediacommons&fl[]=identifier&sort[]=&sort[]=&sort[]=&rows=1000&page=1&output=json&callback=callback'
raw = urllib.urlopen(queryurl).read()
raw = raw.split('callback(')[1].strip(')')
result = json... |
from shinken_test import *
class TestConfig(ShinkenTest):
def setUp(self):
self.setup_with_file('etc/shinken_groups_pickle.cfg')
def test_dispatch(self):
sub_confs = self.conf.confs
print "NB SUB CONFS", len(sub_confs)
vcfg = None
# Find whe... |
"""
Base class for all objects that can receive the keyboard focus on the UI.
"""
from gnue.common import events
from gnue.forms.input import displayHandlers
from gnue.forms.GFObjects.GFObj import GFObj
from gnue.forms.GFObjects.GFField import InvalidFieldValueError
from toolib import debug
__all__ = ['GFTabStop']
#... |
#!/usr/bin/python
"""
Custom topology for Mininet
"""
from mininet.topo import Topo
from mininet.net import Mininet
from mininet.node import Host, RemoteController
from mininet.node import Node
from mininet.node import CPULimitedHost
from mininet.link import TCLink
from mininet.cli import CLI
from mininet.log import s... |
# -*- coding: utf-8 -*-
{
"A volunteer is defined as active if they've participated in an average of 8 or more hours of Program work or Trainings per month in the last year": "A volunteer is defined as active if they've participated in an average of 8 or more hours of Programme work or Trainings per month in the last y... |
# -*- coding: utf-8 -*-
'''
Exodus Add-on
Copyright (C) 2016 Exodus
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, or
(at your option) any l... |
# -*- coding: koi8-r -*-
import unittest
from test import support
class PEP263Test(unittest.TestCase):
def test_pep263(self):
self.assertEqual(
"ðÉÔÏÎ".encode("utf-8"),
b'\xd0\x9f\xd0\xb8\xd1\x82\xd0\xbe\xd0\xbd'
)
self.assertEqual(
"\ð".encode("utf-8")... |
"""Test where byte objects are accepted"""
import unittest
import sys
from ctypes import *
class BytesTest(unittest.TestCase):
def test_c_char(self):
x = c_char(b"x")
x.value = b"y"
c_char.from_param(b"x")
(c_char * 3)(b"a", b"b", b"c")
def test_c_wchar(self):
x = c_wch... |
# -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding field 'CourseMode.sku'
db.add_column('course_modes_coursemode', 'sku',
self.g... |
from threading import Event, Lock
from uuid import uuid1
from ncclient.xml_ import *
from ncclient.transport import SessionListener
from errors import OperationError, TimeoutExpiredError, MissingCapabilityError
import logging
logger = logging.getLogger("ncclient.operations.rpc")
class RPCError(OperationError):
... |
import json
from social.p3 import urlencode
from social.tests.backends.oauth import OAuth1Test
class TripitOAuth1Test(OAuth1Test):
backend_path = 'social.backends.tripit.TripItOAuth'
user_data_url = 'https://api.tripit.com/v1/get/profile'
expected_username = 'foobar'
access_token_body = json.dumps({
... |
{
'name': 'Survey',
'version': '2.0',
'category': 'Marketing',
'description': """
Create beautiful web surveys and visualize answers
==================================================
It depends on the answers or reviews of some questions by different users. A
survey may have multiple pages. Each page ... |
"""Tensorflow op that scales gradient for backwards pass."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow as tf
from tensorflow.python.framework import function
def scale_gradient(net, scale, name="scale_gradient"):
"""Scales gradien... |
from django.conf.urls import patterns, url
from django.conf import settings
from django.views.generic import TemplateView
js_info_dict = {
'packages': ('geonode.layers',),
}
urlpatterns = patterns(
'geonode.layers.views',
url(r'^$',
TemplateView.as_view(template_name='layers/layer_list.html'),
... |
import requests
import logging
import amqp.exceptions
import semantic_version as semver
from django import template
from django.conf import settings
from django.core.cache import cache
from celery.app import app_or_default
from allianceauth import __version__
register = template.Library()
TAG_CACHE_TIME = 10800 # 3 ... |
from __future__ import unicode_literals
import frappe
from frappe.utils import flt
from frappe import msgprint, _
def execute(filters=None):
return _execute(filters)
def _execute(filters=None, additional_table_columns=None, additional_query_columns=None):
if not filters: filters = {}
invoice_list = get_invoices(f... |
from django.core.exceptions import SuspiciousOperation
from django.core.signing import BadSignature
from django.utils import simplejson as json
from django.contrib.formtools.wizard import storage
class CookieStorage(storage.BaseStorage):
encoder = json.JSONEncoder(separators=(',', ':'))
def __init__(self, *... |
# -*- coding: utf-8 -*-
#
# django_pam/auth/tests/base_test.py
#
import os
import sys
import json
import types
import getpass
import six
from io import open
from collections import OrderedDict
from django.conf import settings
from django.test import TestCase
from django.utils.translation import ugettext
class Base... |
from build_utils import expand_template, standard_dict
from build_utils_codes import *
import re
# sources and sinks
ss_signatures = ['s', 'i', 'f', 'c']
ss_roots = [
'gr_vector_source_X',
'gr_vector_sink_X',
'gr_noise_source_X',
'gr_sig_source_X',
'gr_probe_signal_X',
'gr_probe_signal_vX'
... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
DOCUMENTATION = r'''
---
module: bigip_device_auth_radius_server
short_description: Manages the RADIUS server configuration of the device
description:
- Manages a device's RADIUS server configuration.
- Used in tandem with the C(... |
"""Unit tests for abc.py."""
import unittest, weakref
from test import test_support
import abc
from inspect import isabstract
class TestABC(unittest.TestCase):
def test_abstractmethod_basics(self):
@abc.abstractmethod
def foo(self): pass
self.assertTrue(foo.__isabstractmethod__)
... |
"""
Usage: merge-event-log-tags.py [-o output_file] [input_files...]
Merge together zero or more event-logs-tags files to produce a single
output file, stripped of comments. Checks that no tag numbers conflict
and fails if they do.
-h to display this usage message and exit.
"""
import cStringIO
import getopt
import... |
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
import fnmatch
import traceback
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.ovirt import (
check_sdk,
create_connection,
get_dict_o... |
# coding=utf-8
r"""
This code was generated by
\ / _ _ _| _ _
| (_)\/(_)(_|\/| |(/_ v1.0.0
/ /
"""
from tests import IntegrationTestCase
from tests.holodeck import Request
from twilio.base.exceptions import TwilioException
from twilio.http.response import Response
class CredentialListTestCase(In... |
import unittest
from copy import deepcopy
from schema_util import RemoveNoDocs, DetectInlineableTypes, InlineDocs
class SchemaUtilTest(unittest.TestCase):
def testRemoveNoDocs(self):
expected_nodoc = [
{
'name': 'B',
'list': [
{
'name': 'B2'
}
]
... |
from abc import abstractmethod
from oslo.config import cfg
from neutron.api.v2 import attributes
from neutron.api.v2 import resource_helper
from neutron.plugins.vmware.common.utils import NetworkTypes
GATEWAY_RESOURCE_NAME = "network_gateway"
DEVICE_RESOURCE_NAME = "gateway_device"
# Use dash for alias and collectio... |
#!/usr/bin/env python
"""
Archlinux only uses /usr/bin folder. /bin, /sbin and /usr/sbin are symlinks to it.
This program read all .fc files and find /bin, /sbin and /usr/sbin definitions
which don't have a matching /usr/bin definition.
Same thing applies to /usr/lib and /lib folders
"""
import re
import os
import os.... |
"""Cluster creation related checks"""
from sahara import conductor as c
from sahara import context
from sahara import exceptions as ex
from sahara.i18n import _
conductor = c.API
data_source_type = {
"type": "string",
"enum": ["swift", "hdfs", "maprfs"]
}
job_configs = {
"type": "object",
"propertie... |
from coalib.bearlib.languages.documentation.DocstyleDefinition import (
DocstyleDefinition)
from coalib.results.Diff import Diff
from coalib.results.TextRange import TextRange
from coalib.bearlib.languages.documentation.DocumentationExtraction import (
extract_documentation_with_markers)
class DocBaseClass:
... |
# coding: utf8
{
'!langcode!': 'fr-ca',
'!langname!': 'Français (Canadien)',
'"update" is an optional expression like "field1=\'newvalue\'". You cannot update or delete the results of a JOIN': '"update" est une expression optionnelle comme "champ1=\'nouvellevaleur\'". Vous ne pouvez mettre à jour ou supprimer les résul... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import os
import json
import pytest
import sys
if sys.version_info < (2, 7):
pytestmark = pytest.mark.skip("F5 Ansible modules require Python >= 2.7")
from ansible.module_utils.basic import AnsibleModule
try:
from librar... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from API.db import *
import os,time,random,re
clear=lambda: os.system("clear")
cont="s"
print "Bienvenido a la configuración de UserBot."
print "Nota: Algunos segmentos requridos u opcionales dejarlos en blanco si no sabes para que sirve.\n\n"
while cont != "*":
print "Mar... |
"""Tests for CNF detection in tree nodes."""
import unittest
from tt.trees import ExpressionTreeNode
class TestTreeNodeIsCnf(unittest.TestCase):
def assert_is_cnf(self, postfix_tokens):
"""Assert the passed tokens are in conjunctive normal form."""
self.assertTrue(ExpressionTreeNode.build_tree(... |
#!/usr/bin/env python
"""
Created on Wed Jul 29 07:00:00 2015
@author: Jorj McKie
Copyright (c) 2015 Jorj X. McKie
The license of this program is governed by the GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007. See the "COPYING" file of this repository.
This is an example for using the Python binding PyMuPDF of M... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import print_function
import contextlib
import multiprocessing
import socket
import time
class ServerContext(object):
"""
This object manages a group of simple servers. Each of them is run in a
separate process. This is the s... |
"""Provides an API for generating Event protocol buffers."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import time
from tensorflow.core.framework import graph_pb2
from tensorflow.core.framework import summary_pb2
from tensorflow.core.protobuf import ... |
from optparse import make_option
from django.core.management.base import BaseCommand
from addons.models import Addon
from amo.utils import chunked
from devhub.tasks import convert_purified, flag_binary, get_preview_sizes
tasks = {
'flag_binary': {'method': flag_binary, 'qs': []},
'get_preview_sizes': {'meth... |
"""
Verifies that Makefiles get rebuilt when a source gyp file changes and
--generator-output is used.
"""
import TestGyp
# Regenerating build files when a gyp file changes is currently only supported
# by the make and Android generators, and --generator-output is not supported
# by Android and ninja, so we can only ... |
#!/bin/python
import sys
class AddressInfo():
def __init__(self, address):
self.foo = {}
self.full_access = 0
self.partial_access = 0
self.address = address
def addPartial(self, acc):
self.partial_access = acc
def addFull(self, acc):
self.full_access = acc
def __str__(self):
... |
import hashlib
import http.server
import json
import logging
import os
import re
import shutil
import socketserver
import subprocess
from contextlib import contextmanager, ExitStack
from itertools import chain
from multiprocessing import Process
from shutil import rmtree, which
from subprocess import check_call
from ty... |
# -*- encoding:utf-8 -*-
from __future__ import unicode_literals
MESSAGES = {
"%d min remaining to read": "Il reste encore %d min. de lecture",
"(active)": "(actif)",
"Also available in:": "Également disponible en:",
"Archive": "Archives",
"Categories": "Catégories",
"Comments": "Commentaires",... |
from sos.plugins import Plugin, RedHatPlugin, DebianPlugin, UbuntuPlugin
class OpenStackHorizon(Plugin):
"""OpenStack Horizon
"""
plugin_name = "openstack_horizon"
profiles = ('openstack', 'openstack_controller')
option_list = [("log", "gathers openstack horizon logs", "slow", True)]
def set... |
"""LZX data stream parser.
Also includes a decompression function (slow!!) which can decompress
LZX data stored in a Hachoir stream.
Author: Robert Xiao
Creation date: July 18, 2007
"""
from hachoir_parser import Parser
from hachoir_core.field import (FieldSet,
UInt32, Bit, Bits, PaddingBits,
RawBytes, Parser... |
"""
Views for managing backups.
"""
import operator
from django.core.urlresolvers import reverse
from django.utils.translation import ugettext_lazy as _
from horizon import exceptions
from horizon import forms
from horizon import messages
from openstack_dashboard import api
from openstack_dashboard.dashboards.proje... |
import math
import numpy as np
import h5py
import matplotlib.pyplot as plt
from PIL import Image
from scipy import ndimage
import tensorflow as tf
from tensorflow.python.framework import ops
from cnn_utils import *
np.random.seed(1)
# Loading the data (signs)
X_train_orig, Y_train_orig, X_test_orig, Y_test_orig, c... |
#-*- coding: utf8 -*-
import pymongo, time as T, sys
from twython import TwythonStreamer
from twython import Twython
#HTAG="#arenaNETmundial"
HTAG="#aao0"
HTAG_=HTAG.replace("#","H")
#client=pymongo.MongoClient()
#db = client['mytest']
#C = db['twitter'] #collection
#foo=C.find()
#tweets=[ff for ff in foo if "arenaNETm... |
# 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 ..dev import *
CLASSES_TO_DBS = {
'BerkeleyX/CS169.1x/2012_Fall': "cs169.db",
'BerkeleyX/CS188.1x/2012_Fall': "cs188_1.db",
'HarvardX/CS50x/2012': "... |
import argparse
import ariba
def run(options):
plotter = ariba.mic_plotter.MicPlotter(
options.prepareref_dir,
options.antibiotic,
options.mic_file,
options.summary_file,
options.outprefix,
use_hets=options.use_hets,
main_title=options.main_title,
plot_height=options... |
"""Tests for IPython.lib.display.
"""
#-----------------------------------------------------------------------------
# Copyright (c) 2012, the IPython Development Team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file COPYING.txt, distributed with this software.
#-------... |
from __future__ import absolute_import, division, print_function, \
with_statement
from ctypes import c_char_p, c_int, c_ulonglong, byref, \
create_string_buffer, c_void_p
from shadowsocks.crypto import util
__all__ = ['ciphers']
libsodium = None
loaded = False
buf_size = 2048
# for salsa20 and chacha20
B... |
"""MIME-Type Parser
This module provides basic functions for handling mime-types. It can handle
matching mime-types against a list of media-ranges. See section 14.1 of the
HTTP specification [RFC 2616] for a complete explanation.
http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.1
Contents:
- parse_mi... |
"""
WSGI config for rando project.
This module contains the WSGI application used by Django's development server
and any production WSGI deployments. It should expose a module-level variable
named ``application``. Django's ``runserver`` and ``runfcgi`` commands discover
this application via the ``WSGI_APPLICATION`` se... |
"""
## @file
"""
from PIL import (Image,
ImageChops)
from nupic.regions.ImageSensorFilters.BaseFilter import BaseFilter
class CenteredMultipleScales(BaseFilter):
"""
Create scaled versions of the original image and centers them.
"""
def __init__(self, scales=[1], background=0, simultaneou... |
from __future__ import unicode_literals
import time
import poplib
import frappe
from frappe.utils import extract_email_id, convert_utc_to_user_timezone, now, cint
from frappe.utils.scheduler import log
class EmailSizeExceededError(frappe.ValidationError): pass
class EmailTimeoutError(frappe.ValidationError): pass
clas... |
__all__ = [
'ZerigoDNSDriver'
]
import copy
import base64
import httplib
from xml.etree import ElementTree as ET
from libcloud.utils import fixxpath, findtext, findattr, findall
from libcloud.utils import merge_valid_keys, get_new_obj
from libcloud.common.base import XmlResponse, ConnectionUserAndKey
from libcl... |
from test_framework import BitcoinTestFramework
from bitcoinrpc.authproxy import AuthServiceProxy, JSONRPCException
from util import *
import os
import shutil
# Create one-input, one-output, no-fee transaction:
class MempoolCoinbaseTest(BitcoinTestFramework):
def setup_network(self):
# Just need one node ... |
#!/usr/bin/env python
from __future__ import print_function
import os
import re
import sys
import six
import threading
__author__ = 'Maurice Green'
__purpose__ = 'System Cahce Hit Ratio'
class Proc(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
uname = os.uname()
... |
# -*- coding: utf-8 -*-
"""
Student dashboard page.
"""
from bok_choy.page_object import PageObject
from . import BASE_URL
class DashboardPage(PageObject):
"""
Student dashboard, where the student can view
courses she/he has registered for.
"""
def __init__(self, browser):
"""Initialize t... |
import os
import cPickle
import string
import nltk
from itertools import chain
from collections import defaultdict
# local import
from politeness_strategies import get_politeness_strategy_features
# Will need access to local dir
# for support files
LOCAL_DIR = os.path.split(__file__)[0]
def get_unigrams_and_bigrams... |
import mock
from tornado import testing
from tredis import exceptions
from . import base
class SortedSetTests(base.AsyncTestCase):
@testing.gen_test
def test_zadd_single(self):
key, value = self.uuid4(2)
result = yield self.client.zadd(key, '1', value)
self.assertEqual(result, 1)
... |
"""Unittests for grit.format.policy_templates.writers.admx_writer."""
import re
import unittest
class XmlWriterBaseTest(unittest.TestCase):
'''Base class for XML writer unit-tests.
'''
def GetXMLOfChildren(self, parent):
'''Returns the XML of all child nodes of the given parent node.
Args:
pare... |
import gdb
import os
import re
from linux import modules
if hasattr(gdb, 'Breakpoint'):
class LoadModuleBreakpoint(gdb.Breakpoint):
def __init__(self, spec, gdb_command):
super(LoadModuleBreakpoint, self).__init__(spec, internal=True)
self.silent = True
self.gdb_comman... |
"""Chain Tests."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
from tensorflow.contrib.distributions.python.ops.bijectors.bijector_test_util import assert_scalar_congruency
from tensorflow.contrib.distributions.python.ops.bijectors.c... |
# -*- coding: utf-8 -*-
"""
Local dispatcher.
The local interface is process-local. It is lightweight, and good for testing environments, but doesn't handle anything that wouldn't normally be process local.
"""
from ..base import DispatcherService, DispatcherKeyword
from ..scheduler import Scheduler
from ..utils.cal... |
# -*- coding: utf-8 -*-
import unittest2
from ..controllers import main
class ActionMungerTest(unittest2.TestCase):
def test_actual_treeview(self):
action = {
"views": [[False, "tree"], [False, "form"],
[False, "calendar"]],
"view_type": "tree",
"... |
import asyncore as _asyncore
import random as _random
import threading as _threading
import time as _time
from .confsys import Configurable as _Configurable
from .logger import mkInfoFunction as _mkInfoFunction
from .logger import mkWarnFunction as _mkWarnFunction
_proxyInfo = _mkInfoFunction('Proxy')
_proxyWarn = _m... |
# This program verifies the continuous crowdsensing game model is group strategyproofed.
import random
import math
from copy import deepcopy
# Let there be 100 users.
n = 100
# Let the upper bound of the users' unit costs be 10.
k_max = 10.0
# Let the upper bound of the revenue coefficients be 20.
lambda_max = 20.0
# ... |
#!/usr/bin/env python3
from distutils.version import StrictVersion
import os
import re
import requests
import subprocess
import sys
import tempfile
from client.api import assignment
from client.utils import auth
GITHUB_TOKEN_FILE = '.github-token'
GITHUB_REPO = 'okpy/ok-client'
OK_SERVER_URL = 'okpy.org'
def abort(m... |
"""Test that the wallet can send and receive using all combinations of address types.
There are 5 nodes-under-test:
- node0 uses legacy addresses
- node1 uses p2sh/segwit addresses
- node2 uses p2sh/segwit addresses and bech32 addresses for change
- node3 uses bech32 addresses
- node4 uses a p2sh/s... |
import http.client
from lxml import html
from datetime import datetime
import csv
import os
import time
conn = http.client.HTTPSConnection("www.hockey-reference.com")
def writeCsv(coach, years):
if len(years) == 0:
print("No years")
return
directory = "./stats/coach"
filename = "%s/%s.cs... |
import operator
import warnings
import weakref
from bson import DBRef, ObjectId, SON
import pymongo
from mongoengine.common import _import_class
from mongoengine.errors import ValidationError
from mongoengine.base.common import ALLOW_INHERITANCE
from mongoengine.base.datastructures import BaseDict, BaseList
__all__... |
#!/usr/bin/env python
import rospy
import pyaudio
import numpy as np
import json
from rospkg import RosPack
from std_msgs.msg import Float32
from os.path import join
class SoundController(object):
def __init__(self):
self.rospack = RosPack()
with open(join(self.rospack.get_path('apex_playground'),... |
# $Id: 231_reg_bad_fail_stale_false_nonce_changed.py 2392 2008-12-22 18:54:58Z bennylp $
import inc_sip as sip
import inc_sdp as sdp
# In this test we simulate broken server, where:
# - it wants to signal that NONCE has change
# - but it sets stale=false
# For this case pjsip will retry authentication until
# PJSIP_MA... |
import os
import re
from setuptools import setup
VERSION = re.search(
r"VERSION\s*=\s*['\"](.*)['\"]",
open(os.path.join(os.path.dirname(__file__), 'password_session', '__init__.py')).read()
).group(1)
README = open(os.path.join(os.path.dirname(__file__), 'README.rst')).read()
# allow setup.py to be run from... |
import os
import shutil
import tempfile
from nose.tools import assert_true, assert_equal, assert_false
from sqoop.conf import SQOOP_CONF_DIR
from sqoop.client.base import SqoopClient
from sqoop.sqoop_properties import reset
def test_security_plain():
tmpdir = tempfile.mkdtemp()
finish = SQOOP_CONF_DIR.set_for_t... |
"""Module for parsing and testing package version predicate strings.
"""
import re
import distutils.version
import operator
re_validPackage = re.compile(r"(?i)^\s*([a-z_]\w*(?:\.[a-z_]\w*)*)(.*)")
# (package) (rest)
re_paren = re.compile(r"^\s*\((.*)\)\s*$") # (list) inside of parentheses
re_splitComparison = re.com... |
import unittest
from telemetry.page import page as page_module
from telemetry.page import record_wpr
class TestPage(page_module.Page):
def __init__(self):
super(TestPage, self).__init__(url='file://foo.html',
page_set=None,
base_dir=None)
... |
# purpose: Sudoku game, uses 3rd party file 'generator.py'
import math,sys,os,time,pygame as pg
from pygame.locals import *
from random import randint
from ScoreScreen import ScoreScreen
import Fade
from os import environ
environ['SDL_VIDEO_CENTERED'] = '1'
BG = (255,255,255)
C1 = (0,0,0)
C2 = (120,120,... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.