content stringlengths 4 20k |
|---|
print("---SAPreduced_matrix, has_SAP, find_ZFloor, Zsap, etc.")
def SAPmatrix(A):
"""
Input: a symmetric matrix A
Output: The matrix for checking if A has SAP
"""
if A.is_symmetric()==False:
raise ValueError("Input matrix is not symmetric.")
AA=[];
n=A.dimensions()[0];
row_num=0... |
import unittest
from test.test_support import run_unittest
import sys
import warnings
class AllTest(unittest.TestCase):
def check_all(self, modname):
names = {}
with warnings.catch_warnings():
warnings.filterwarnings("ignore", ".* (module|package)",
... |
import os
import sys
execfile('/etc/courtlistener')
sys.path.append(INSTALL_ROOT)
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings")
from alert.search.models import Document, Citation
from alert.lib.db_tools import queryset_generator
from alert.lib.string_utils import clean_string
from alert.lib.string_utils... |
"""Hook for Google Drive service"""
from typing import Any, Optional
from googleapiclient.discovery import Resource, build
from googleapiclient.http import MediaFileUpload
from airflow.gcp.hooks.base import CloudBaseHook
# noinspection PyAbstractClass
class GoogleDriveHook(CloudBaseHook):
"""
Hook for the G... |
#!/usr/bin/env python
'''
Simple "Square Detector" program.
Loads several images sequentially and tries to find squares in each image.
'''
# Python 2/3 compatibility
import sys
PY3 = sys.version_info[0] == 3
if PY3:
xrange = range
import numpy as np
import cv2
def angle_cos(p0, p1, p2):
d1, d2 = (p0-p1).... |
#!/usr/bin/python
import os
import sys
import logging
import shutil
import common
from autotest.client import utils
from autotest.client.shared import logging_manager
from virttest import utils_misc
def package_jeos(img):
"""
Package JeOS and make it ready for upload.
Steps:
1) Move /path/to/jeos.q... |
from __future__ import division
import struct
k = [
0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0... |
"""
Unittest for time.strftime
"""
import calendar
import sys
import re
from test import test_support
import time
import unittest
# helper functions
def fixasctime(s):
if s[8] == ' ':
s = s[:8] + '0' + s[9:]
return s
def escapestr(text, ampm):
"""
Escape text to deal with possible locale val... |
# encoding: utf-8
from __future__ import unicode_literals
import re
from .common import InfoExtractor
class InaIE(InfoExtractor):
_VALID_URL = r'https?://(?:www\.)?ina\.fr/video/(?P<id>I?[A-Z0-9]+)'
_TEST = {
'url': 'http://www.ina.fr/video/I12055569/francois-hollande-je-crois-que-c-est-clair-video.... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
from ansible.plugins.action import ActionBase
from ansible.plugins.action.copy import ActionModule as CopyActionModule
# Even though CopyActionModule inherits from ActionBase, we still need to
# directly inherit from ActionBase t... |
import sys
from ctypes.util import find_library
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from django.db.backends.sqlite3.base import (
Database, DatabaseWrapper as SQLiteDatabaseWrapper, SQLiteCursorWrapper,
)
from django.utils import six
from .client import SpatiaL... |
"""AutoComplete.py - An IDLE extension for automatically completing names.
This extension can complete either attribute names of file names. It can pop
a window with all available names, for the user to select from.
"""
import os
import sys
import string
from idlelib.configHandler import idleConf
# This string inclu... |
import sys
import time
from . import statusfile
REPORT_TEMPLATE = (
"""Total: %(total)i tests
* %(skipped)4d tests will be skipped
* %(timeout)4d tests are expected to timeout sometimes
* %(nocrash)4d tests are expected to be flaky but not crash
* %(pass)4d tests are expected to pass
* %(fail_ok)4d tests are ex... |
import json
from django.core import checks, exceptions, serializers
from django.db import connection
from django.db.models import OuterRef, Subquery
from django.db.models.expressions import RawSQL
from django.forms import Form
from django.test.utils import CaptureQueriesContext, isolate_apps
from . import PostgreSQLS... |
"""
Template file used by the OPF Experiment Generator to generate the actual
description.py file by replacing $XXXXXXXX tokens with desired values.
This description.py file was generated by:
'~/nupic/eng/lib/python2.6/site-packages/nupic/frameworks/opf/expGenerator/ExpGenerator.py'
"""
from nupic.frameworks.opf.expd... |
ANSIBLE_METADATA = {'metadata_version': '1.0',
'status': ['preview'],
'supported_by': 'community'}
import sys
import paramiko
import time
import argparse
import socket
import array
import json
import time
import re
try:
from ansible.module_utils import cnos
HAS_LIB = Tr... |
from __future__ import unicode_literals
from django.db.models import Q
from django.contrib.auth.backends import ModelBackend
from account.compat import get_user_model, get_user_lookup_kwargs
from account.models import EmailAddress
class UsernameAuthenticationBackend(ModelBackend):
def authenticate(self, **cre... |
import setuptools
from os import path
if __name__ == "__main__":
here = path.abspath(path.dirname(__file__))
with open(path.join(here, 'DESCRIPTION.rst'), encoding='utf-8') as f:
long_description = f.read()
setuptools.setup(
name="watershed",
version="0.0.1",
description="Da... |
# -*- coding: utf-8 -*-
"""
Functions to process AVAPS dropsondes data
"""
import datetime
import netCDF4 as nc
import numpy as np
from . import DsFld, ObsData
from . import utils
def read_avaps_nc(fname, flds=None, time2datetime=False):
"""Read AVAPS dropsonde data from a NetCDF file.
Open a NetCDF file an... |
# coding=utf-8
'''This module handles all functions responsible for modifying the course
settings page.
View Function: instructorEditTestFile (instructor/testSettings.html)
Redirect Functions: TODO
AJAX Fuctions: TODO
'''
#Import the app
from app import app
#Import needed flask functions
from flask import g, rend... |
#!/usr/bin/env python
"""
Integration (not unit) tests for pylast.py
"""
import os
import time
import unittest
import pytest
from flaky import flaky
import pylast
def load_secrets():
secrets_file = "test_pylast.yaml"
if os.path.isfile(secrets_file):
import yaml # pip install pyyaml
with op... |
from oslo_config import cfg
from oslo_log import log
CONF = cfg.CONF
LOG = log.getLogger(__name__)
class FakeVolume(object):
def __init__(self, **kwargs):
self.id = kwargs.pop('id', 'fake_vol_id')
self.status = kwargs.pop('status', 'available')
self.device = kwargs.pop('device', '')
... |
class ModuleDocFragment(object):
# Standard files documentation fragment
DOCUMENTATION = """
options:
provider:
description:
- A dict object containing connection details.
default: null
suboptions:
host:
description:
- Specifies the DNS host name or address for conne... |
"""
Indent the each enum item in the enum block.
== Violation ==
enum A {
A_A, <== Violation
A_B <== Violation
}
== Good ==
enum A {
A_A, <== Good
A_B
}
"""
from nsiqcppstyle_rulehelper import *
from nsiqcppstyle_reporter import *
from nsiqcppstyle_rulemanager import... |
{
"name" : "Romania - Accounting",
"version" : "1.0",
"author" : "ERPsystems Solutions",
"website": "http://www.erpsystems.ro",
"category" : "Localization/Account Charts",
"depends" : ['account','account_chart','base_vat'],
"description": """
This is the module to manage the Accounting Chart... |
from __future__ import print_function
import sys
import os
import glob
import tempfile
import shutil
import time
import urllib2
import netrc
import json
from urlparse import urlparse, urljoin
from subprocess import Popen, PIPE, check_call
from w3lib.form import encode_multipart
from scrapy.command import ScrapyComman... |
import unittest
import random
import math
import os
from IECore import *
class GammaOp( ColorTransformOp ) :
def __init__( self, gamma = 1.0 ) :
ColorTransformOp.__init__( self, "applies gamma" )
self.gamma = gamma
def begin( self, operands ) :
pass
def transform( self, color ) :
return Color3f(
m... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
import traceback
from ansible.module_utils.basic import AnsibleModule
from ansible.module_u... |
# -*- coding: utf-8 -*-
"""
End-to-end tests for the LMS.
"""
from unittest import expectedFailure
from ..helpers import UniqueCourseTest
from ...pages.lms.auto_auth import AutoAuthPage
from ...pages.lms.course_info import CourseInfoPage
from ...pages.lms.tab_nav import TabNavPage
from ...pages.xblock.acid import Aci... |
from __future__ import print_function
from pyspark.sql import SparkSession
# $example on$
from pyspark.ml.regression import GeneralizedLinearRegression
# $example off$
"""
An example demonstrating generalized linear regression.
Run with:
bin/spark-submit examples/src/main/python/ml/generalized_linear_regression_exa... |
import numpy as np
from numpy.testing import assert_equal, assert_raises
from numpy.testing import assert_array_almost_equal
from scipy import sparse
from sklearn.utils.testing import assert_less
from sklearn.linear_model import LinearRegression, RANSACRegressor
from sklearn.linear_model.ransac import _dynamic_max_tri... |
# -*- coding: utf-8 -*-
'''
fantastic Add-on
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 later version.
This pro... |
"""
@package mi.dataset.parser
@file marine-integrations/mi/dataset/parser/dosta_ln_auv.py
@author Jeff Roy
@brief Parser and particle Classes and tools for the dosta_ln_auv data
Release notes:
initial release
"""
__author__ = 'Jeff Roy'
__license__ = 'Apache 2.0'
from mi.core.log import get_logger
log = get_logger(... |
import Image
from numpy import asarray
def crop_image(path, cropX, cropY, cropW, cropH):
image = Image.open(path)
x = int(cropX)
y = int(cropY)
x2 = int(cropW) + x
y2 = int(cropH) + y
img = image.crop((x, y, x2, y2))
img.save(path)
def image_should_be_blank(path, expected=True):
im... |
import random
from twisted.internet import reactor
from twisted.internet.defer import inlineCallbacks
from autobahn.wamp.types import SubscribeOptions
from autobahn.twisted.util import sleep
from autobahn.twisted.wamp import ApplicationSession
class Component(ApplicationSession):
"""
An application component... |
"""Example OpenHTF Phase Groups.
PhaseGroups are used to control phase shortcutting due to terminal errors to
better guarentee when teardown phases run.
"""
import openhtf as htf
def setup_phase(test):
test.logger.info('Setup in a group.')
def main_phase(test):
test.logger.info('This is a main phase.')
def ... |
from datetime import timedelta
from flask import make_response, request, current_app
from functools import update_wrapper
def crossdomain(origin=None, methods=None, headers=None,
max_age=21600, attach_to_all=True,
automatic_options=True):
if methods is not None:
methods = '... |
"""Common operations for RNN Estimators (deprecated).
This module and all its submodules are deprecated. See
[contrib/learn/README.md](https://www.tensorflow.org/code/tensorflow/contrib/learn/README.md)
for migration instructions.
"""
from __future__ import absolute_import
from __future__ import division
from __futur... |
"""Tests for Substr op from string_ops."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
from tensorflow.python.framework import errors_impl
from tensorflow.python.ops import string_ops
from tensorflow.python.platform import test
cla... |
from django.test import TestCase, RequestFactory
from django.test.utils import override_settings
from bedrock.base.middleware import LocaleURLMiddleware
@override_settings(DEV=True)
class TestLocaleURLMiddleware(TestCase):
def setUp(self):
self.rf = RequestFactory()
self.middleware = LocaleURLMid... |
import os
import unittest
import shutil
import sys
import tempfile
SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
PARENT_DIR = os.path.dirname(SCRIPT_DIR)
CHROME_SRC = os.path.dirname(os.path.dirname(os.path.dirname(PARENT_DIR)))
MOCK_DIR = os.path.join(CHROME_SRC, "third_party", "pymock")
sys.path.append(PA... |
import xbmc
import xbmcplugin
import xbmcaddon
import xbmcgui
import urllib
import urllib2
import re
import sys
import os
import time
import socket
from StringIO import StringIO
import gzip
module_log_enabled = False
http_debug_log_enabled = False
LIST = "list"
THUMBNAIL = "thumbnail"
MOVIES = "movies"
TV_SHOWS = "t... |
# -*- coding: utf-8 -*-
"""
Python Flight Mechanics Engine (PyFME).
Copyright (c) AeroPython Development Team.
Distributed under the terms of the MIT License.
Trimmer
-------
This module solves the problem of calculating the values of the state and
control vectors that satisfy the state equations of the aircraft at th... |
from __future__ import unicode_literals
import re
from .common import InfoExtractor
from ..utils import (
ExtractorError,
js_to_json,
int_or_none,
parse_iso8601,
)
class ABCIE(InfoExtractor):
IE_NAME = 'abc.net.au'
_VALID_URL = r'https?://(?:www\.)?abc\.net\.au/news/(?:[^/]+/){1,2}(?P<id>\d+... |
# -*- coding: utf-8 -*-
from hachoir_core.compatibility import any, sorted
from hachoir_core.endian import endian_name
from hachoir_core.tools import makePrintable, makeUnicode
from hachoir_core.dict import Dict
from hachoir_core.error import error, HACHOIR_ERRORS
from hachoir_core.i18n import _
from hachoir_core.log i... |
"""Fixtures for the server webserver."""
import re
import sys
import json
import os.path
from http import HTTPStatus
import attr
import pytest
from PyQt5.QtCore import pyqtSignal, QUrl
from end2end.fixtures import testprocess
from qutebrowser.utils import utils
class Request(testprocess.Line):
"""A parsed li... |
import os, subprocess, types, sys, re
def check_output_for_error(output, match, error_in_first_match):
success = re.findall(match, output)
if len(success) > 0:
if (error_in_first_match):
print "[ERROR] %s" % success[0]
sys.exit(1)
else:
return True
else:
return False
def check_and_print_err(err, war... |
from clang.cindex import CompilationDatabase
from clang.cindex import CompilationDatabaseError
from clang.cindex import CompileCommands
from clang.cindex import CompileCommand
import os
import gc
kInputsDir = os.path.join(os.path.dirname(__file__), 'INPUTS')
def test_create_fail():
"""Check we fail loading a data... |
from core.vectors import PhpCode, ShellCmd, ModuleExec, Os
from core.module import Module
from core import messages
from core import modules
import re
class Phpconf(Module):
"""Audit PHP configuration."""
def init(self):
self.register_info(
{
'author': [
... |
#!/usr/bin/python
""" PN CLI show commands """
#
# This file is part of Ansible
#
# Ansible 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 later ver... |
from testfixtures import LogCapture
from twisted.trial import unittest
from twisted.python.failure import Failure
from twisted.internet import defer, reactor
from pydispatch import dispatcher
from scrapy.utils.signal import send_catch_log, send_catch_log_deferred
class SendCatchLogTest(unittest.TestCase):
@defe... |
"""Monkey patch os._exit when running under coverage so we don't lose coverage data in forks, such as with `pytest --boxed`."""
import gc
import os
try:
import coverage
except ImportError:
coverage = None
try:
test = coverage.Coverage
except AttributeError:
coverage = None
def pytest_configure():
... |
from nose.plugins.attrib import attr
from test.integration.base import DBTIntegrationTest
MODEL_PRE_HOOK = """
insert into {{this.schema}}.on_model_hook (
state,
target_name,
target_schema,
target_type,
target_threads,
run_started_at,
invocation_id
) VALUES... |
from __future__ import absolute_import
import logging
import operator
import os
import tempfile
import shutil
import warnings
from pip.req import InstallRequirement, RequirementSet, parse_requirements
from pip.locations import build_prefix, virtualenv_no_global, distutils_scheme
from pip.basecommand import Command
fr... |
# coding=UTF-8
# Tornado modules.
import tornado.web
import tornado.escape
# Import application modules.
from base import BaseHandler
# General modules.
import logging
class LoginHandler(BaseHandler, tornado.auth.GoogleMixin):
"""
Handler for logins with Google Open ID / OAuth
http://www.tornadoweb.org... |
#!/usr/bin/env python
'''
nsot
====
Ansible Dynamic Inventory to pull hosts from NSoT, a flexible CMDB by Dropbox
Features
--------
* Define host groups in form of NSoT device attribute criteria
* All parameters defined by the spec as of 2015-09-05 are supported.
+ ``--list``: Returns JSON hash of host groups -... |
"""Module implementing the logic for running hooks.
"""
from ganeti import constants
from ganeti import errors
from ganeti import utils
from ganeti import compat
from ganeti import pathutils
def _RpcResultsToHooksResults(rpc_results):
"""Function to convert RPC results to the format expected by HooksMaster.
@t... |
import numpy as np
from sklearn.utils.testing import assert_almost_equal
from sklearn.utils.testing import assert_array_almost_equal
from sklearn.utils.testing import assert_array_equal
from sklearn.utils.testing import assert_raises
from sklearn.utils.testing import assert_warns
from sklearn import datasets
from skl... |
from io import BytesIO
from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
from ginga.web.pgw import Widgets
class PlotWidget(Widgets.Canvas):
"""
This class implements the server-side backend of the surface for a
web-based plot viewer. It uses a web socket to connect to an HTML5
... |
"""
This test file will run through some LMS test scenarios regarding access and navigation of the LMS
"""
import time
from mock import patch
from nose.plugins.attrib import attr
from django.conf import settings
from django.core.urlresolvers import reverse
from django.test.utils import override_settings
from coursewa... |
import os
import sys
import string
import xml.etree.ElementTree as etree
from xml.etree.ElementTree import SubElement
from utils import _make_path_relative
from utils import xml_indent
fs_encoding = sys.getfilesystemencoding()
def _get_filetype(fn):
if fn.rfind('.cpp') != -1 or fn.rfind('.cxx') != -1:
re... |
# -*- coding: utf-8 -*-
"""
werkzeug.testsuite.urls
~~~~~~~~~~~~~~~~~~~~~~~
URL helper tests.
:copyright: (c) 2013 by Armin Ronacher.
:license: BSD, see LICENSE for more details.
"""
import unittest
from werkzeug.testsuite import WerkzeugTestCase
from werkzeug.datastructures import OrderedMultiD... |
# encoding: utf-8
"""
command.py
Created by Thomas Mangin on 2015-12-15.
Copyright (c) 2009-2015 Exa Networks. All rights reserved.
"""
from exabgp.version import version as _version
class Text (object):
callback = {}
def __new__ (cls,name):
def register (function):
cls.callback[name] = function
return f... |
from __future__ import unicode_literals
from django import http
from django.contrib.contenttypes.models import ContentType
from django.contrib.sites.models import Site, get_current_site
from django.core.exceptions import ObjectDoesNotExist
from django.utils.translation import ugettext as _
def shortcut(request, conte... |
import os.path as path
import mimetypes
mimetypes.init()
from django.utils.translation import ugettext as _
from django.contrib.contenttypes.models import ContentType
from taiga.base import filters
from taiga.base import exceptions as exc
from taiga.base.api import ModelCrudViewSet
from taiga.base.api.utils import ge... |
"""
INLINE PATTERNS
=============================================================================
Inline patterns such as *emphasis* are handled by means of auxiliary
objects, one per pattern. Pattern objects must be instances of classes
that extend markdown.Pattern. Each pattern object uses a single regular
express... |
class Blob(object):
"""Blob object"""
def __init__(self, value=None, file=None, id=None):
self._file = file
self.id = id
self.value = value
@property
def file(self):
from StringIO import StringIO
if self._file:
f = self._file
else:
... |
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
import datetime
import fnmatch
import hashlib
import mimetypes
import os
import stat as osstat # os.stat constants
import traceback
# import module snippets
from ansible.module_... |
from django.utils.translation import ugettext_lazy as _
from horizon import exceptions
from horizon import tabs
from openstack_dashboard.api import nova
from openstack_dashboard.dashboards.admin.hypervisors.compute import tables
class ComputeHostTab(tabs.TableTab):
table_classes = (tables.ComputeHostTable,)
... |
import base64
import urllib
import sys
import requests
from PyQt4.QtGui import QApplication, QPushButton
from electrum.plugins import BasePlugin, hook
from electrum.i18n import _
class Plugin(BasePlugin):
button_label = _("Verify GA instant")
@hook
def transaction_dialog(self, d):
d.verify_bu... |
DASHBOARD = 'project'
# If set to True, this dashboard will be set as the default dashboard.
DEFAULT = True
# A dictionary of exception classes to be added to HORIZON['exceptions'].
ADD_EXCEPTIONS = {}
# A list of applications to be added to INSTALLED_APPS.
ADD_INSTALLED_APPS = ['openstack_dashboard.dashboards.project'... |
import urlparse
import os
from rtorrent.compat import is_py3
def bool_to_int(value):
"""Translates python booleans to RPC-safe integers"""
if value is True:
return("1")
elif value is False:
return("0")
else:
return(value)
def cmd_exists(cmds_list, cmd):
"""Check if given... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""This file is part of the Scribee project.
"""
__author__ = 'Emanuele Bertoldi <<EMAIL>>'
__copyright__ = 'Copyright (c) 2011 Emanuele Bertoldi'
__version__ = '0.0.1'
import sys
import os
import fileinput
import settings
class Scribox(object):
def __init__(self):
... |
import warnings
import hou
import toolutils
import IECore
import IECoreHoudini
class FnParameterisedHolder():
_nodeType = None
# create our function set and stash which node we're looking at
def __init__(self, node=None):
self.__node = node
# check this node is still valid
def nodeValid(self):
if not s... |
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
unicode_literals, with_statement)
import os
from textwrap import dedent
from pants.backend.jvm.artifact import Artifact
from pants.backend.jvm.repository import Repository
from pants.backend.jvm.scala... |
"""Course Builder test suite.
This script runs all functional and units test in the Course Builder project.
Here is how to use the script:
- download WebTest Python package from a URL below and put
the files in a folder of your choice, for example: tmp/webtest:
http://pypi.python.org/packages/sour... |
# A Demo of a service that takes advantage of the additional notifications
# available in later Windows versions.
# Note that all output is written as event log entries - so you must install
# and start the service, then look at the event log for messages as events
# are generated.
# Events are generated for USB devi... |
"""Module to talk to EtherpadLite API."""
import json
import urllib
import urllib2
class EtherpadLiteClient:
"""Client to talk to EtherpadLite API."""
API_VERSION = 1 # TODO probably 1.1 sometime soon
CODE_OK = 0
CODE_INVALID_PARAMETERS = 1
CODE_INTERNAL_ERROR = 2
CODE_INVALID_FUNCTION = 3
... |
# -*- 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 'Coupon.expiration_date'
db.add_column('shoppingcart_coupon', 'expiration_date',
... |
# Webhooks for external integrations.
from typing import Any, Dict
from django.http import HttpRequest, HttpResponse
from zerver.decorator import REQ, api_key_only_webhook_view, has_request_variables
from zerver.lib.response import json_success
from zerver.lib.webhooks.common import check_send_webhook_message
from ze... |
import logging
import struct
from ryu.base import app_manager
from ryu.controller import ofp_event
from ryu.controller import dpset
from ryu.controller.handler import MAIN_DISPATCHER
from ryu.controller.handler import set_ev_cls
from ryu.ofproto import ofproto_v1_2
from ryu.ofproto import ether
from ryu.lib.mac import... |
# -*- coding: utf-8 -*-
from datetime import datetime
from urllib import urlencode
import hashlib
from openerp import SUPERUSER_ID
from openerp.osv import osv, fields
class Users(osv.Model):
_inherit = 'res.users'
def __init__(self, pool, cr):
init_res = super(Users, self).__init__(pool, cr)
... |
"""This script lays out the PNaCl translator files for a
normal Chrome installer, for one platform. Once run num-of-arches times,
the result can then be packed into a multi-CRX zip file.
This script depends on and pulls in the translator nexes and libraries
from the toolchain directory (so that must be do... |
import glob
import os
import platform
import subprocess
import sys
from setuptools import Command, Extension, setup, find_packages
from setuptools.command.test import test as TestCommand
def define_extensions(cythonize=False):
compile_args = ['-fopenmp',
'-ffast-math']
# There are probl... |
# test for+range, mostly to check optimisation of this pair
# apply args using *
for x in range(*(1, 3)):
print(x)
for x in range(1, *(6, 2)):
print(x)
# apply args using **
try:
for x in range(**{'end':1}):
print(x)
except TypeError:
print('TypeError')
try:
for x in range(0, **{'end':1}):... |
from unittest.mock import Mock
import numpy
import pytest
import pyflo_suspect.processing as p
import pyflo.ports
import suspect
@pytest.fixture
def simple_data():
source_array = numpy.ones((4, 128), 'complex')
source_array[1, :] *= 2
source_array[2, :] *= 4
source_array[3, :] *= 8
data = suspec... |
"""Parser for command line options.
This module helps scripts to parse the command line arguments in
sys.argv. It supports the same conventions as the Unix getopt()
function (including the special meanings of arguments of the form `-'
and `--'). Long options similar to those supported by GNU software
may be used as ... |
"""
This is the Docutils (Python Documentation Utilities) package.
Package Structure
=================
Modules:
- __init__.py: Contains component base classes, exception classes, and
Docutils version information.
- core.py: Contains the ``Publisher`` class and ``publish_*()`` convenience
functions.
- frontend.... |
def match_ends(words):
# +++your code here+++
# LAB(begin solution)
count = 0
for word in words:
if len(word) >= 2 and word[0] == word[-1]:
count = count + 1
return count
# LAB(replace solution)
# return
# LAB(end solution)
# B. front_x
# Given a list of strings, return a list with the strin... |
"""Tests for MultivariateNormalFullCovariance."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
from scipy import stats
from tensorflow.contrib import distributions
from tensorflow.python.ops import array_ops
from tensorflow.python.ops ... |
from yowsup.structs import ProtocolEntity, ProtocolTreeNode
from yowsup.layers.protocol_receipts.protocolentities import OutgoingReceiptProtocolEntity
from yowsup.layers.axolotl.protocolentities.iq_keys_get_result import ResultGetKeysIqProtocolEntity
class RetryOutgoingReceiptProtocolEntity(OutgoingReceiptProtocolEntit... |
# encoding: utf-8
import datetime
from south.db import db
from south.v2 import DataMigration
from django.db import models
from django.contrib.auth.models import User,Group,Permission
class Migration(DataMigration):
def forwards(self, orm):
(g,created) = Group.objects.get_or_create(name='Valid Email')
... |
import unittest
from ploev import calc
from ploev.calc import Calc, GameCalc
from ploev.ppt import OddsOracle
class CalcModuleTest(unittest.TestCase):
def test_close_parenthesis(self):
self.assertEqual(calc.close_parenthesis('77,KK'), '(77,KK)')
self.assertEqual(calc.close_parenthesis('(77,KK)')... |
#!/usr/bin/env python
# coding=utf-8
"""
Problem Definition :
Starting with 1 and spiralling anticlockwise in the following way, a square spiral with side length 7 is formed.
37 36 35 34 33 32 31
38 17 16 15 14 13 30
39 18 5 4 3 12 29
40 19 6 1 2 11 28
41 20 7 8 9 10 27
42 21 22 23 24 25 26
43 44 45 46 47 ... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import os
import re
import time
import glob
from ansible.plugins.action.ce import ActionModule as _ActionModule
from ansible.module_utils._text import to_text
from ansible.module_utils.six.moves.urllib.parse import urlsplit
from a... |
import sys
import unittest2 as unittest
from mock import Mock
from social.utils import sanitize_redirect, user_is_authenticated, \
user_is_active, slugify, build_absolute_uri, \
partial_pipeline_data
PY3 = sys.version_info[0] == 3
class SanitizeRedirectTest(unitte... |
from core import perf_benchmark
from benchmarks import silk_flags
from telemetry import benchmark
from telemetry.timeline import tracing_category_filter
from telemetry.web_perf.metrics import gpu_timeline
from telemetry.web_perf import timeline_based_measurement
import page_sets
TOPLEVEL_CATEGORIES = ['disabled-by-... |
# -*- coding: utf-8 -*-
"""
Created on Tue Aug 30 15:26:13 2016
@author: jtara1
General syntax for subreddits.txt:
: (colon character) denotes folder name
subreddit url or word denotes subreddit
For more examples see https://github.com/jtara1/RedditImageGrab/commit/8e4787ef9ac43ca694fc663be026f69a568bb622
Example o... |
"""Deals with creating the normal mode representation arrays.
Copyright (C) 2013, Joshua More and Michele Ceriotti
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... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import markupfield.fields
class Migration(migrations.Migration):
dependencies = [
('schedule', '0006_slotkind_plenary'),
]
operations = [
migrations.AlterField(
model_nam... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.