content stringlengths 4 20k |
|---|
'''
Tests correctness of branch and bound algorithm. Optimal values of problems are
hard-coded. This will be valid until python decides to change its random number
generator. See test_bb_pulp.py for comparing branch and bound results with
optimal values given by PuLP.
Script raises exceptions if the bb solution is not... |
import unittest
from datetime import datetime
from pyprint.NullPrinter import NullPrinter
from pyprint.Printer import Printer
from pyprint.StringPrinter import StringPrinter
from coalib.misc import Constants
from coalib.output.printers.LogPrinter import LogPrinter
from coalib.processes.communication.LogMessage import... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from setuptools import setup, find_packages
import setuptools.command.install as _install
import subprocess
class install(_install.install):
def run(self):
subprocess.check_call(["make"])
... |
"""
Expectation Maximization Framework
==================================
Usage example::
import pulp.em as em
from pulp.em.LinCA import LinCA
from pulp.utils.dlog import dlog
# Prepare Model
model = LinCA()
anneal = em.LinearAnneal([ (200, 2, 50) ])
# Prepare training data
... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import os
from types import NoneType
from ansible.errors import AnsibleError
from ansible.parsing import DataLoader
from ansible.plugins.action import ActionBase
class ActionModule(ActionBase):
TRANSFERS_FILES = False
... |
"""
Logistic regression using MLlib.
This example requires NumPy (http://www.numpy.org/).
"""
from __future__ import print_function
import sys
from pyspark import SparkContext
from pyspark.mllib.regression import LabeledPoint
from pyspark.mllib.classification import LogisticRegressionWithSGD
def parsePoint(line):
... |
#!/usr/bin/env python
import sys, os, random, sigproc
import psr_utils as pu
def spigot_samples_per_file(spigot_filenm):
"""
spigot_samples_per_file(spigot_filenm,):
Return the number of samples present in the Spigot FITs file.
"""
hdrlen = 184320
bytes_per_sample = 2048
filelen = os.st... |
"""Conferences model definition."""
from ..schema import SchemaOverdo
conferences = SchemaOverdo(schema="conferences.json") |
from __future__ import unicode_literals
import json
import datetime
import mimetypes
import os
import frappe
from frappe import _
import frappe.model.document
import frappe.utils
import frappe.sessions
import werkzeug.utils
from werkzeug.local import LocalProxy
from werkzeug.wsgi import wrap_file
from werkzeug.wrappers... |
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
unicode_literals, with_statement)
import subprocess
from contextlib import contextmanager
from textwrap import dedent
from pants.backend.python.tasks.python_task import PythonTask
from pants.util.cont... |
import os, sys, traceback
import Ice
slice_dir = Ice.getSliceDir()
if not slice_dir:
print(sys.argv[0] + ': Slice directory not found.')
sys.exit(1)
Ice.loadSlice('"-I' + slice_dir + '" Test.ice')
import AllTests
def run(args, communicator):
thrower = AllTests.allTests(communicator)
thrower.shutdown(... |
from __future__ import unicode_literals
import contextlib
import re
import warnings
# Messages used in deprecation warnings are collected here so we can target
# them easily when ignoring warnings.
_MESSAGES = {
# Deprecated features mpd:
'mpd.protocol.playback.pause:state_arg':
'The use of pause comm... |
from io import StringIO
from django.http import HttpResponse
from arches.app.utils.betterJSONSerializer import JSONSerializer
class JSONResponse(HttpResponse):
def __init__(self, content=b'', *args, **kwargs):
kwargs['content_type'] = 'text/json'
ensure_ascii = kwargs.pop("ensure_ascii", True)... |
from __future__ import absolute_import
from __future__ import with_statement
import logging
import sys
from collections import defaultdict
from kombu.tests.utils import redirect_stdouts
from celery import beat
from celery import platforms
from celery.app import app_or_default
from celery.bin import celerybeat as ce... |
"""
Verifies that device and simulator bundles are built correctly.
"""
import TestGyp
import TestMac
import collections
import sys
if sys.platform == 'darwin':
test = TestGyp.TestGyp(formats=['ninja', 'xcode'])
test_cases = [
('Default', 'TestArch32Bits', ['i386']),
('Default-iphoneos', 'TestArch32Bit... |
from haversine import haversine, haversine_vector, Unit
from numpy.testing import assert_allclose
LYON = (45.7597, 4.8422)
PARIS = (48.8567, 2.3508)
LONDON = (51.509865, -0.118092)
NEW_YORK = (40.7033962, -74.2351462)
EXPECTED_LYON_PARIS = {Unit.KILOMETERS: 392.2172595594006,
Unit.METERS: 392217.259559400... |
import atexit
import contextlib
import sys
from .ansitowin32 import AnsiToWin32
orig_stdout = None
orig_stderr = None
wrapped_stdout = None
wrapped_stderr = None
atexit_done = False
def reset_all():
if AnsiToWin32 is not None: # Issue #74: objects might become None at exit
AnsiTo... |
__revision__ = '$Id: models.py 28 2009-10-22 15:03:02Z jarek.zgoda $'
import re
from django.db import models
from django.core.urlresolvers import reverse
from django.core.mail import send_mail
from django.conf import settings
from django.template import loader, Context
from django.contrib.sites.models import Site
fro... |
# -*- coding: utf-8 -*-
"""
Core: The core functionality for Vincent to map to Vega grammar
"""
from __future__ import (print_function, division)
import json
from string import Template
from pkg_resources import resource_string
try:
import pandas as pd
except ImportError:
pd = None
try:
import numpy as ... |
# Code to extract organization names from the 'waarde' field of Parlement.com position data
# @author Frank Takes - <EMAIL>
# @dependencies: Python 2, Pandas
# @run code using: python details.csv
# after running once iconv -f utf8 -t ascii//TRANSLIT originalfile > details.csv replace all x with umlaut/accent/etc b... |
import platform
from virttest import utils_misc
ARCH = platform.machine()
if ARCH in ('ppc64', 'ppc64le'):
# From include/linux/sockios.h
SIOCSIFHWADDR = 0x8924
SIOCGIFHWADDR = 0x8927
SIOCGIFFLAGS = 0x8913
SIOCSIFFLAGS = 0x8914
SIOCGIFADDR = 0x8915
SIOCSIFADDR = 0x8916
SIOCGIFNETMASK =... |
"""The Normal (Gaussian) distribution class."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import math
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import ops
from ... |
# encoding: utf-8
# module sys
# from (built-in)
# by generator 1.135
"""
This module provides access to some objects used or maintained by the
interpreter and to functions that interact strongly with the interpreter.
Dynamic objects:
argv -- command line arguments; argv[0] is the script pathname if known
path -- mod... |
import time
from oslo_log import log as logging
from oslo_utils import excutils
from tempest_lib.common.utils import data_utils
from tempest_lib import exceptions as lib_exc
from tempest import clients
from tempest.common import credentials
from tempest.common import fixed_network
from tempest import config
from temp... |
"""`Evaluable` interface (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 __future__ import prin... |
from collections import defaultdict
RED = '\033[0;1;31m'
GREEN = '\033[0;1;32m'
YELLOW = '\033[0;1;33m'
BLUE = '\033[0;1;34m'
MAGENTA = '\033[0;1;35m'
CYAN = '\033[0;1;36m'
WHITE = '\033[0;1;37m'
DARK_MAGENTA = '\033[0;35m'
ANSI_RESET = '\033[0m'
def colorme(bval, colormap, colorkey):
if colormap is None:
... |
import time
def format_date(then):
if then is None:
return ""
try:
now = time.time()
delta = now - then
return format_delta(delta)
except (TypeError, ValueError):
return ""
def format_delta(delta):
days = delta / (60 * 60 * 24)
hours = delta / (60 * 60)
... |
import sys, string, os
from xml.etree import ElementTree as ET
manifestFile = sys.argv[1]
pluginStr = sys.argv[2]
pluginsDir = sys.argv[3]
androidNS = 'http://schemas.android.com/apk/res/android'
sourceCfgFile = '/android/ForManifest.xml'
def doModify(sourceFile, root):
bRet = False
sourceTree = ET.parse(sou... |
"""
This module implements functions and classes for spatial statistics.
"""
import numpy as np
import math
class RipleysKEstimator:
"""
Estimators for Ripley's K function for two-dimensional spatial data.
See [1]_, [2]_, [3]_, [4]_, [5]_ for detailed mathematical and
practical aspects of those esti... |
from rally.common import objects
from rally import consts
from rally.deployment import engine
@engine.configure(name="ExistingCloud")
class ExistingCloud(engine.Engine):
"""Just use an existing OpenStack deployment without deploying anything.
To use ExistingCloud, you should put endpoint information to the c... |
"""Test for the BigQuery side input example."""
import logging
import unittest
import apache_beam as beam
from apache_beam.examples.cookbook import bigquery_side_input
from apache_beam.testing.test_pipeline import TestPipeline
from apache_beam.testing.util import assert_that
from apache_beam.testing.util import equal... |
from rdflib import URIRef, BNode, Literal
from rdflib.query import ResultSerializer
def _termString(t, namespace_manager):
if t == None:
return "-"
if namespace_manager:
if isinstance(t, URIRef):
return namespace_manager.normalizeUri(t)
elif isinstance(t, BNode):
... |
# -*- coding: utf-8 -*-
import re
from django import forms
from django.template import loader, Context
from django.utils.translation import ugettext as _
from django.utils.translation import activate, deactivate
from .base import CrispyTestCase
from .forms import CheckboxesTestForm, TestForm
from crispy_forms.bootstr... |
import wx
from timelinelib.wxgui.dialogs.eraseditor.controller import ErasEditorDialogController
from timelinelib.wxgui.framework import Dialog
class ErasEditorDialog(Dialog):
"""
<BoxSizerVertical>
<ListBox name="lb_eras" border="ALL" proportion="1" height="250"
event_EVT_LISTBOX_DCLICK... |
"""Changed ExamTaken.date_taken from Date to DateTime
Revision ID: 6723848870f0
Revises:
Create Date: 2017-11-24 14:25:44.434000
"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import mysql
# revision identifiers, used by Alembic.
revision = '6723848870f0'
down_revision = None
branch_lab... |
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
unicode_literals, with_statement)
import os
import unittest
from functools import partial
from pants.base.build_root import BuildRoot
from pants.bin.repro import Reproducer
from pants.fs.archive impor... |
import os
curdir = os.path.join(os.getcwd(), os.path.dirname(__file__))
import cherrypy
from cherrypy.test import helper
import nose
class RoutesDispatchTest(helper.CPWebCase):
def setup_server():
try:
import routes
except ImportError:
raise nose.SkipTest('Install routes... |
"""
ID-specific Form helpers
"""
from __future__ import absolute_import
import re
import time
from django.core.validators import EMPTY_VALUES
from django.forms import ValidationError
from django.forms.fields import Field, Select
from django.utils.translation import ugettext_lazy as _
from django.utils.encoding impor... |
# -*- coding: utf-8 -*-
"""
werkzeug.contrib.wrappers
~~~~~~~~~~~~~~~~~~~~~~~~~
Extra wrappers or mixins contributed by the community. These wrappers can
be mixed in into request objects to add extra functionality.
Example::
from werkzeug.wrappers import Request as RequestBase
fr... |
import inspect
import struct
import base64
import six
from . import packet_base
from . import ethernet
from ryu import utils
from ryu.lib.stringify import StringifyMixin
# Packet class dictionary
mod = inspect.getmembers(utils.import_module("ryu.lib.packet"),
lambda cls: (inspect.ismodule(... |
"""Registers new hosts in chromoting directory.
It asks for username/password and then writes these settings to config file.
"""
import base64
import getpass
import hashlib
import hmac
import json
import os
import random
import socket
import sys
import urllib
import urllib2
import gaia_auth
import keygen
def random... |
# -*- coding: utf-8 -*-
from bs4 import BeautifulSoup
from pprint import pprint
import requests, random, re, os
from lxml import html
#https://elpais.com/hemeroteca/elpais/2017/01/01/m/portada.html
def downloadOneUrl(url, name):
res = requests.get(url)
file = open(name, "w")
file.write(res.text)
def dow... |
import os, sys
from pip.req import InstallRequirement, RequirementSet
from pip.req import parse_requirements
from pip.log import logger
from pip.locations import build_prefix, src_prefix
from pip.basecommand import Command
from pip.index import PackageFinder
from pip.exceptions import InstallationError
class InstallC... |
"""
Tools for the instructor dashboard
"""
import dateutil
import json
from django.conf import settings
from django.contrib.auth.models import User
from django.http import HttpResponseBadRequest
from django.utils.timezone import utc
from django.utils.translation import ugettext as _
from courseware.models import Stud... |
#!/usr/bin/env python
from pyrf.devices.thinkrf import WSA
from pyrf.sweep_device import SweepDevice
from pyrf.numpy_util import calculate_channel_power
import sys
import time
import math
from matplotlib.pyplot import plot, figure, axis, xlabel, ylabel, show
import numpy as np
def smooth(list,degree=1):
new_lis... |
import os
import sys
import time
import tempfile
import subprocess
from cStringIO import StringIO
from redistrib import command
def launch():
template = '''
daemonize yes
port {port}
cluster-node-timeout 5000
pidfile {tmpdir}/redis_cluster_node-{port}.pid
logfile {tmpdir}/redis_cluster_node-{p... |
import copy
import sys
import unittest
from typing import Dict, TypeVar
import hypothesis as hyp
import hypothesis.strategies as st
sys.path.insert(0, "../scripts")
import deep_dict # noqa
K = TypeVar("K")
V = TypeVar("V")
FEW_EXAMPLES = 15
class TestDeepDict(unittest.TestCase):
@hyp.given(
st.dict... |
# coding: utf-8
from __future__ import unicode_literals
import json
import re
from .common import InfoExtractor
from ..utils import (
ExtractorError,
unified_strdate,
urlencode_postdata,
xpath_element,
xpath_text,
update_url_query,
js_to_json,
)
class Laola1TvEmbedIE(InfoExtractor):
... |
#!/usr/bin/python
# coding=utf-8
################################################################################
from test import CollectorTestCase
from test import get_collector_config
from test import unittest
from mock import Mock
from mock import patch
from diamond.collector import Collector
from monit import M... |
'''
Audio Gstplayer
===============
.. versionadded:: 1.8.0
Implementation of a VideoBase with Kivy :class:`~kivy.lib.gstplayer.GstPlayer`
This player is the prefered player, using Gstreamer 1.0, working on both Python
2 and 3.
'''
from kivy.lib.gstplayer import GstPlayer, get_gst_version
from kivy.core.audio import... |
from __future__ import unicode_literals
import sys
from importlib import import_module
from django.apps import apps
from django.core.management.base import BaseCommand, CommandError
from django.core.management.color import no_style
from django.core.management.sql import emit_post_migrate_signal, sql_flush
from django... |
import requests
import logging
from django.conf import settings
from article_metrics import models, handler, utils
from article_metrics.utils import first, flatten, simple_rate_limiter, lmap, lfilter, isint, ParseError, ensure
LOG = logging.getLogger(__name__)
URL = "https://api.elsevier.com/content/search/scopus"
M... |
#! CCSD dipole with user-specified basis set
import psi4
psi4.set_output_file("output.dat", False)
h2o = psi4.geometry("""
0 1
H
O 1 0.957
H 2 0.957 1 104.5
""")
psi4.set_options({'freeze_core': 'false'})
psi4.basis_helper("""
# Sadlej-pVTZ
spherical
****
H 0
S 4 1.00
33.8650140000 0.00606... |
import hashlib
from nova.api.openstack import common
from nova.api.openstack.compute.views import addresses as views_addresses
from nova.api.openstack.compute.views import flavors as views_flavors
from nova.api.openstack.compute.views import images as views_images
from nova import log as logging
from nova import utils... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
d2lstat.py
python d2lstat.py usage_data.csv full_time.csv part_time.csv semester_name number_of_courses_running
Given a correct data set and lists of full- and part-time teachers, this program will generate usage statistics on a
given template, which can be edited u... |
# -*- coding: utf-8 -*-
"""
Greedy graph coloring using various strategies.
"""
# Copyright (C) 2014 by
# Christian Olsson <<EMAIL>>
# Jan Aagaard Meier <<EMAIL>>
# Henrik Haugbølle <<EMAIL>>
# All rights reserved.
# BSD license.
import networkx as nx
import random
import itertools
from . import greed... |
# -*- coding: utf-8 -*-
"""
sphinx.builders.texinfo
~~~~~~~~~~~~~~~~~~~~~~~
Texinfo builder.
:copyright: Copyright 2007-2014 by the Sphinx team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
from os import path
from docutils import nodes
from docutils.io import FileOutput
from docutil... |
import sys
import unittest
from libcloud.dns.drivers.vultr import VultrDNSDriver
from libcloud.dns.types import RecordType
from libcloud.utils.py3 import httplib
from libcloud.test import MockHttp
from libcloud.test.secrets import VULTR_PARAMS
from libcloud.test.file_fixtures import DNSFileFixtures
from libcloud.dns.t... |
import logging
from odoo import api, fields, models
_logger = logging.getLogger(__name__)
class SurveyCodeRenew(models.TransientModel):
_description = 'Survey Code Renew'
_name = 'clv.survey.code_renew'
def _default_survey_ids(self):
return self._context.get('active_ids')
survey_ids = field... |
import xml.sax
import xml.sax.handler
START_ELEMENT = "START_ELEMENT"
END_ELEMENT = "END_ELEMENT"
COMMENT = "COMMENT"
START_DOCUMENT = "START_DOCUMENT"
END_DOCUMENT = "END_DOCUMENT"
PROCESSING_INSTRUCTION = "PROCESSING_INSTRUCTION"
IGNORABLE_WHITESPACE = "IGNORABLE_WHITESPACE"
CHARACTERS = "CHARACTERS"
class PullDOM(... |
import codecs, logging, os, util
from tokenizer import Tokenizer
from tokenparser import Parser
from api import Document
def setup_logging():
logger=logging.getLogger("W2L")
logger.setLevel(logging.DEBUG)
console_formatter = logging.Formatter("%(asctime)s - %(levelname)s"
... |
"""Simple textbox editing widget with Emacs-like keybindings."""
import curses
import curses.ascii
def rectangle(win, uly, ulx, lry, lrx):
"""Draw a rectangle with corners at the provided upper-left
and lower-right coordinates.
"""
win.vline(uly+1, ulx, curses.ACS_VLINE, lry - uly - 1)
win.hline(u... |
"""
Tag editing module for Gramps.
"""
#-------------------------------------------------------------------------
#
# GNOME modules
#
#-------------------------------------------------------------------------
from gi.repository import Gtk
#-------------------------------------------------------------------------
#
# G... |
"""Main python file."""
import os
import time
import json
from flask import Flask
from vtdb import vtgate_client
# Register gRPC protocol.
from vtdb import grpc_vtgate_client # pylint: disable=unused-import
app = Flask(__name__)
# conn is the connection to vtgate.
conn = None
@app.route('/')
def index():
ret... |
# -*- coding: utf-8 -*-
print "=================================="
# 3-1
print 45678 + 0x12fd2
print 'Learn Python in imooc'
print 100 < 99
print 0xff == 255
print "=================================="
# 3-2
print 'hello, python'
print "hello, python"
print """hello, python"""
print 'hello,', 'python'
print 'hello', ... |
import datetime
import logging
import os
import threading
from devil.android import device_blacklist
from devil.android import device_errors
from devil.android import device_utils
from devil.android import logcat_monitor
from devil.utils import parallelizer
from pylib import constants
from pylib.base import environmen... |
#!/usr/bin/env python
'''
This file is part of speedtest-reporter.
Speedtest-reporter 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 ... |
"""
Common spice test utility functions.
"""
import os
import logging
import time
import sys
from avocado.core import exceptions
from aexpect import ShellCmdError, ShellStatusError
from . import utils_net, utils_misc
class RVConnectError(Exception):
"""Exception raised in case that remote-viewer fails to con... |
from abc import abstractmethod
from neutron.api import extensions
from neutron.api.v2 import base
from neutron.api.v2 import resource
from neutron.common import constants
from neutron.extensions import agent
from neutron import manager
from neutron.plugins.common import constants as plugin_const
from neutron import po... |
import os
import unittest
from tests.utils import (
setup_test_env,
)
setup_test_env()
from softwarecenter.backend.ubuntusso import (UbuntuSSOAPIFake,
UbuntuSSO,
get_ubuntu_sso_backend,
... |
from random import random
from math import sqrt, exp, log, sin, cos,pi,factorial
class continuas:
"""Clase para simular variables aleatorias Continuas. Incluye las distribuciones: normal (metodo polar y muller), exponencial, gamma."""
def polar(self):
S=2
while S > 1:
v1=2*random()-1
v2=2*random()-1
S=v... |
import sys
import os
import shutil
import datetime
import glob
import zipfile
import argparse
import re
QLXL = "QuantLibXL"
VERSION = "1.8.0"
VERSION_ = "1_8_0"
#VC_VERSION = "vc120"
VC_VERSION = "vc90"
QLXL_VERSION = QLXL + "-" + VERSION
ROOT_DIR = QLXL_VERSION + "\\"
class ZipFile:
root = None
zipFile = No... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {
'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'
}
try:
from pyVmomi import vim, vmodl
except ImportError as e:
pass
from ansible.module_utils.basic import Ansib... |
try:
from urllib.parse import urlencode
except ImportError: # Python 2
from urllib import urlencode
from xml.dom.minidom import parseString
from django.contrib.auth.decorators import login_required, permission_required
from django.core import mail
from django.forms import fields
from django.forms.forms imp... |
# -*- coding: utf-8 -*-
"""QGIS Unit tests for QgsMapLayer
.. note:: 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 2 of the License, or
(at your option) any later version.
"""
__auth... |
from dionaea.core import *
import logging
global handler
global logger
class DionaeaLogHandler(logging.Handler):
def __init__(self):
logging.Handler.__init__(self, logging.DEBUG)
def emit(self,record):
dlhfn(record.name, record.levelno, record.pathname, record.lineno, record.msg)
def start():
pass
def new():... |
from nose.tools import * # noqa
from tests.base import OsfTestCase
import json
from modularodm import Q
from framework.mongo.utils import to_mongo
from website.project.model import ensure_schemas, MetaSchema, Node
from tests import factories
from scripts.migration.migrate_registered_meta import (
main as do_mig... |
# -*- 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 model 'Community'
db.create_table(u'communities_community', (
(u'id', self.gf('django.d... |
import time
import uuid
try:
import boto
import boto.ec2
from boto import route53
from boto.route53 import Route53Connection, exception
from boto.route53.healthcheck import HealthCheck
HAS_BOTO = True
except ImportError:
HAS_BOTO = False
# Things that can't get changed:
# protocol
# ip_a... |
import urlparse
from openerp import SUPERUSER_ID
from openerp import http
from openerp.addons.web.http import request
from openerp.addons.website_mail.controllers.main import WebsiteMail
class WebsiteMailController(WebsiteMail):
@http.route(['/website_mail/post/json'], type='json', auth='public', website=True)... |
# uncompyle6 version 2.9.10
# Python bytecode 2.7 (62211)
# Decompiled from: Python 3.6.0b2 (default, Oct 11 2016, 05:27:10)
# [GCC 6.2.0 20161005]
# Embedded file name: ascii.py
"""Constants and membership tests for ASCII characters"""
NUL = 0
SOH = 1
STX = 2
ETX = 3
EOT = 4
ENQ = 5
ACK = 6
BEL = 7
BS = 8
TAB = 9
HT ... |
# -*- coding: utf-'8' "-*-"
import base64
try:
import simplejson as json
except ImportError:
import json
from hashlib import sha1
import hmac
import logging
import urlparse
from openerp.addons.payment.models.payment_acquirer import ValidationError
from openerp.addons.payment_adyen.controllers.main import Adye... |
"""
The module checks if system includes hardware mitigations for Speculative Execution Side Channel.
Specifically, it verifies that the system supports CPU mitigations for
Branch Target Injection vulnerability a.k.a. Spectre Variant 2 (CVE-2017-5715)
The module checks if the following hardware mitigations are support... |
# -*- coding: utf-8 -*-
"""
***************************************************************************
r_describe.py
---------------------
Date : December 2012
Copyright : (C) 2012 by Victor Olaya
Email : volayaf at gmail dot com
**************************... |
import pytest
import aiohttp
from aiohttp_json_rpc.client import JsonRpcClient
pytestmark = pytest.mark.asyncio(reason='Depends on asyncio')
async def test_client_connect_disconnect(rpc_context):
async def ping(request):
return 'pong'
rpc_context.rpc.add_methods(
('', ping),
)
cli... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import os
import json
import pytest
from mock import ANY
from ansible.module_utils.network.fortios.fortios import FortiOSHandler
try:
from ansible.modules.network.fortios import fortios_wanopt_webcache
except ImportError:
... |
import unittest
from mock import Mock, patch
import Adafruit_GPIO.Platform as Platform
class TestPlatformDetect(unittest.TestCase):
@patch('platform.platform', Mock(return_value='Linux-3.8.13-bone47-armv7l-with-debian-7.4'))
def test_beaglebone_black(self):
result = Platform.platform_detect()
... |
ANSIBLE_METADATA = {'metadata_version': '1.0',
'status': ['preview'],
'supported_by': 'community'}
def node_exists(api, address):
# hack to determine if node exists
result = False
try:
api.LocalLB.NodeAddressV2.get_object_status(nodes=[address])
resu... |
from trac.core import *
from trac.db import Table, Column, Index
from trac.db import DatabaseManager
from trac.env import IEnvironmentSetupParticipant
schema_version = 1
schema = [
Table('asa_version', key='id')[
Column('id', type='int64', auto_increment=True),
Column('time', type='int64'),... |
import sys
import os
root_dir = os.path.abspath(os.path.dirname(__file__))
lib_dir = os.path.join(root_dir, 'lib')
sys.path.insert(0, lib_dir)
from wubi.application import Wubi
try:
from version import application_name, version, revision
except:
application_name = "wubi"
version = "0.0"
revision = "0"... |
import converters
import math
import random
import sys
def random_real(a, b):
"""
Random real between a and b inclusively.
"""
return a + random.random() * (b - a)
def branch_length(depth):
"""
Somewhat random length of the branch. Play around
with this to achieve a desired tree structure... |
"""
Copyright (c) 2012-2014 RockStor, Inc. <http://rockstor.com>
This file is part of RockStor.
RockStor 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 2 of the License,
or (at your option) any la... |
"""
Example that sends a single message and exits using the simple interface.
You can use `simple_receive.py` (or `complete_receive.py`) to receive the
message sent.
"""
import eventlet
from kombu import Connection
eventlet.monkey_patch()
def send_many(n):
#: Create connection
#: If hostname, userid, pa... |
# coding: utf-8
import base64
from flask import request, Response
from oauthlib.common import to_unicode, bytes_type
def _get_uri_from_request(request):
"""
The uri returned from request.uri is not properly urlencoded
(sometimes it's partially urldecoded) This is a weird hack to get
werkzeug to retur... |
def connect_ec2(aws_access_key_id=None, aws_secret_access_key=None, **kwargs):
"""
:type aws_access_key_id: string
:param aws_access_key_id: Your AWS Access Key ID
:type aws_secret_access_key: string
:param aws_secret_access_key: Your AWS Secret Access Key
:rtype: :class:`boto.ec2.connection.E... |
from __future__ import with_statement
import hashlib
import os
import posixpath
import re
from urllib import unquote
from urlparse import urlsplit, urlunsplit, urldefrag
from django.conf import settings
from django.core.cache import (get_cache, InvalidCacheBackendError,
cache as default_... |
from __future__ import unicode_literals
import frappe
from frappe import _
from frappe.utils import now_datetime, cint
def set_new_name(doc):
"""Sets the `name`` property for the document based on various rules.
1. If amened doc, set suffix.
3. If `autoname` method is declared, then call it.
4. If `autoname` prop... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.openstack im... |
"""Tests for reduction operators."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
from tensorflow.compiler.tests.xla_test import XLATestCase
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import errors... |
# -*- coding: utf8 -*-
import django.contrib.admin as a
from django.contrib import admin
from django.contrib.auth.models import User
from lubico.django.contrib.gitana.models import Repository, UserKey
__author__ = 'sassman <<EMAIL>>'
__version__ = "1.0.1"
__license__ = "GNU Lesser General Public License"
__package__ ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.