code stringlengths 1 199k |
|---|
"""
Set operations for 1D numeric arrays based on sorting.
:Contains:
ediff1d,
unique,
intersect1d,
setxor1d,
in1d,
union1d,
setdiff1d
:Notes:
For floating point arrays, inaccurate results may appear due to usual round-off
and floating point comparison issues.
Speed could be gained in some operations by a... |
import math
import m5
from m5.objects import *
from m5.defines import buildEnv
class Cache(RubyCache):
latency = 3
def define_options(parser):
return
def create_system(options, system, piobus, dma_ports, ruby_system):
if buildEnv['PROTOCOL'] != 'MI_example':
panic("This script requires the MI_exampl... |
"""Assorted commands.
"""
import os
import threading
import sublime
import sublime_plugin
from Vintageous.state import _init_vintageous
from Vintageous.state import State
from Vintageous.vi import settings
from Vintageous.vi import cmd_defs
from Vintageous.vi.dot_file import DotFile
from Vintageous.vi.utils import mode... |
import urllib
from allmydata.scripts.common_http import do_http, check_http_error
from allmydata.scripts.common import get_alias, DEFAULT_ALIAS, UnknownAliasError
from allmydata.util.encodingutil import quote_output
def mkdir(options):
nodeurl = options['node-url']
aliases = options.aliases
where = options.... |
from __future__ import print_function
try:
# Python 2 version
import ConfigParser
except ImportError:
# Python 3 version
import configparser as ConfigParser
import json
import argparse
import copy
import os
import re
import sys
from time import time
from collections import defaultdict
from distutils.ver... |
from telepathy._generated.interfaces import *
CONN_MGR_INTERFACE = CONNECTION_MANAGER
CONN_INTERFACE = CONNECTION
CHANNEL_INTERFACE = CHANNEL
CHANNEL_HANDLER_INTERFACE = CHANNEL_HANDLER
CONN_INTERFACE_ALIASING = CONNECTION_INTERFACE_ALIASING
CONN_INTERFACE_AVATARS = CONNECTION_INTERFACE_AVATARS
CONN_INTERFACE_CAPABILIT... |
"""Generated message classes for storage version v1.
Stores and retrieves potentially large, immutable data objects.
"""
from apitools.base.protorpclite import message_types as _message_types
from apitools.base.protorpclite import messages as _messages
from apitools.base.py import encoding
from apitools.base.py import ... |
import pygraph.algorithms.generators as gen
import pygraph.algorithms.accessibility as acc
import pygraph.algorithms.minmax as minmax
graph = gen.generate(5000, 10000, weight_range=(50, 2000))
components = acc.connected_components(graph)
nodes = [g for g in graph if components[g] == 1]
print "GRAPH NODES"
for n in grap... |
from pandas.compat import range, zip
from pandas import compat
import itertools
import numpy as np
from pandas.core.series import Series
from pandas.core.frame import DataFrame
from pandas.core.sparse import SparseDataFrame, SparseSeries
from pandas.sparse.array import SparseArray
from pandas._sparse import IntIndex
fr... |
import numpy as np
import numpy.testing as npt
from dipy.reconst.peaks import default_sphere, peaks_from_model
def test_PeaksAndMetricsDirectionGetter():
class SillyModel(object):
def fit(self, data, mask=None):
return SillyFit(self)
class SillyFit(object):
def __init__(self, model):... |
"""
A Python "serializer". Doesn't do much serializing per se -- just converts to
and from basic Python data types (lists, dicts, strings, etc.). Useful as a basis for
other serializers.
"""
from __future__ import unicode_literals
from collections import OrderedDict
from django.apps import apps
from django.conf import ... |
import json
import logging
import pytz
import datetime
import dateutil.parser
from django.contrib.auth.decorators import login_required
from django.http import HttpResponse
from django.shortcuts import redirect
from django.conf import settings
from mitxmako.shortcuts import render_to_response
from django_future.csrf im... |
"""A `Predictor constructed from a `tf.contrib.learn.Estimator`."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.contrib.learn.python.learn.utils import saved_model_export_utils
from tensorflow.contrib.predictor import predictor
from tensor... |
import unittest
from perfkitbenchmarker import sample
class SampleTestCase(unittest.TestCase):
def testMetadataOptional(self):
instance = sample.Sample(metric='Test', value=1.0, unit='Mbps')
self.assertDictEqual({}, instance.metadata)
def testProvidedMetadataSet(self):
metadata = {'origin': 'unit test'}... |
from __future__ import unicode_literals
import datetime
import hashlib
import random
import re
from django.conf import settings
from django.core.mail import EmailMultiAlternatives
from django.db import models
from django.template import RequestContext, TemplateDoesNotExist
from django.template.loader import render_to_s... |
"""Camino top level namespace
"""
from .connectivity import Conmat
from .convert import (Image2Voxel, FSL2Scheme, VtkStreamlines, ProcStreamlines,
TractShredder, DT2NIfTI, NIfTIDT2Camino, AnalyzeHeader,
Shredder)
from .dti import (DTIFit, ModelFit, DTLUTGen, PicoPDFs, Track, ... |
"""Top-level import for all CLI-related functionality in apitools.
Note that importing this file will ultimately have side-effects, and
may require imports not available in all environments (such as App
Engine). In particular, picking up some readline-related imports can
cause pain.
"""
from googlecloudapis.apitools.ba... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = '''
---
module: cloudwatchlogs_log_group_info
short_description: Get informatio... |
from keystone.endpoint_policy.core import * # noqa
from keystone.endpoint_policy import routers # noqa |
import Gaffer
import GafferScene
Gaffer.Metadata.registerNode(
GafferScene.Encapsulate,
"description",
"""
Encapsulates a portion of the scene by collapsing the hierarchy
and replacing it with a procedural which will be evaluated at
render time.
This has two primary uses :
- To optimise scene generation. Downst... |
from numpy.random import random
from bokeh.plotting import figure, show, output_file
def mscatter(p, x, y, marker):
p.scatter(x, y, marker=marker, size=15,
line_color="navy", fill_color="orange", alpha=0.5)
def mtext(p, x, y, text):
p.text(x, y, text=[text],
text_color="firebrick", text... |
import micropython
try:
def stackless():
pass
micropython.heap_lock()
stackless()
micropython.heap_unlock()
except RuntimeError:
print("SKIP")
raise SystemExit
try:
micropython.alloc_emergency_exception_buf(256)
except AttributeError:
pass
def main():
# create an exception wi... |
"""Logging Operations."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.python.framework import ops
from tensorflow.python.ops import common_shapes
from tensorflow.python.ops import gen_logging_ops
from tensorflow.python.ops.gen_logging_ops ... |
from operator import itemgetter
import time
from openerp import SUPERUSER_ID
from openerp.osv import fields, osv
from openerp import api
class account_fiscal_position(osv.osv):
_name = 'account.fiscal.position'
_description = 'Fiscal Position'
_order = 'sequence'
_columns = {
'sequence': fields.... |
g = 2
i = 2
<warning descr="Non-ASCII character 'ɡ' in the file, but no encoding declared">ɡ</warning> = 1
a = g + i |
def func():
value = "not-none"
# pylint: disable=unused-argument1
<caret>if value is None:
print("None")
# pylint: disable=unused-argument2
print(value) |
from itertools import chain
from django.contrib.contenttypes.models import ContentType
from django.core.exceptions import ValidationError
from django.test import TestCase
import guardian
from guardian.backends import ObjectPermissionBackend
from guardian.exceptions import GuardianError
from guardian.exceptions import N... |
import numpy as np
import pandas as pd
from bokeh import mpl
from bokeh.plotting import show
ts = pd.Series(np.random.randn(1000), index=pd.date_range('1/1/2000', periods=1000))
ts = ts.cumsum()
df = pd.DataFrame(np.random.randn(1000, 4), index=ts.index, columns=list('ABCD'))
df = df.cumsum()
df.plot(legend=False)
show... |
import audioop
import sys
import unittest
def pack(width, data):
return b''.join(v.to_bytes(width, sys.byteorder, signed=True) for v in data)
def unpack(width, data):
return [int.from_bytes(data[i: i + width], sys.byteorder, signed=True)
for i in range(0, len(data), width)]
packs = {w: (lambda *data... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
ANSIBLE_METADATA = {'status': ['preview'],
'supported_by': 'community',
'metadata_version': '1.1'}
DOCUMENTATION = '''
---
module: fortios_system_replacemsg_traffic_quota
short_description: Re... |
{
'name': "Purchase orders - Force number",
'version': '0.1',
'category': 'Purchase Management',
'summary': "Force purchase orders numeration",
'description': """
This simple module allows to specify the number to use when creating purchase
orders. If user does not change the default value ('/'), th... |
from lib.action import PyraxBaseAction
from lib.formatters import to_dns_zone_dict
__all__ = [
'CreateDNSZoneAction'
]
class CreateDNSZoneAction(PyraxBaseAction):
def run(self, name, email_address, ttl=None, comment=None):
cdns = self.pyrax.cloud_dns
zone = cdns.create(name=name, emailAddress=em... |
import migrate
import sqlalchemy
from heat.db.sqlalchemy import utils as migrate_utils
def upgrade(migrate_engine):
if migrate_engine.name == 'sqlite':
upgrade_sqlite(migrate_engine)
return
meta = sqlalchemy.MetaData()
meta.bind = migrate_engine
tmpl_table = sqlalchemy.Table('raw_templat... |
"""Mixin classes for custom array types that don't inherit from ndarray."""
from numpy.core import umath as um
__all__ = ['NDArrayOperatorsMixin']
def _disables_array_ufunc(obj):
"""True when __array_ufunc__ is set to None."""
try:
return obj.__array_ufunc__ is None
except AttributeError:
re... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ["preview"], 'supported_by': 'community'}
DOCUMENTATION = '''
---
module: gcp_resourcemanager_project
description:
- Represents a GCP Project. A project is a container for ACLs,... |
"""Functions to make unit testing easier."""
import StringIO
import numpy as np
from PIL import Image as PILImage
import tensorflow as tf
def create_random_image(image_format, shape):
"""Creates an image with random values.
Args:
image_format: An image format (PNG or JPEG).
shape: A tuple with image shape (... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import datetime
import os
import tarfile
import tempfile
import yaml
from distutils.version import LooseVersion
from shutil import rmtree
import ansible.constants as C
from ansible.errors import AnsibleError
from ansible.module_util... |
import numpy
import os
class ByteOrder:
LittleEndian, BigEndian = range(2)
class FeatureException(Exception):
def __init__(self,msg):
self.msg = msg
def __str__(self):
return repr(self.msg)
def ReadLabel(filename):
labels = numpy.loadtxt(filename, ndmin=1)
return labels.astype(numpy.int32)
class BaseReader(... |
from openerp import pooler, SUPERUSER_ID
from openerp.openupgrade import openupgrade, openupgrade_80
@openupgrade.migrate()
def migrate(cr, version):
pool = pooler.get_pool(cr.dbname)
uid = SUPERUSER_ID
openupgrade_80.set_message_last_post(
cr, uid, pool, ['fleet.vehicule']
) |
from oslo_log import log as logging
from tempest.api.compute import base
from tempest import config
from tempest import test
CONF = config.CONF
LOG = logging.getLogger(__name__)
class ExtensionsTestJSON(base.BaseV2ComputeTest):
@test.idempotent_id('3bb27738-b759-4e0d-a5fa-37d7a6df07d1')
def test_list_extensions... |
from django.conf import settings
from django.contrib.sites.models import Site
from celery import task
from tower import ugettext as _
from kitsune.sumo.decorators import timeit
from kitsune.sumo import email_utils
@task()
@timeit
def send_award_notification(award):
"""Sends the award notification email
:arg awa... |
'''
Button Behavior
===============
The :class:`~kivy.uix.behaviors.button.ButtonBehavior`
`mixin <https://en.wikipedia.org/wiki/Mixin>`_ class provides
:class:`~kivy.uix.button.Button` behavior. You can combine this class with
other widgets, such as an :class:`~kivy.uix.image.Image`, to provide
alternative buttons tha... |
from __future__ import absolute_import, division, print_function, with_statement
import contextlib
import datetime
import functools
import sys
import textwrap
import time
import platform
import weakref
from tornado.concurrent import return_future, Future
from tornado.escape import url_escape
from tornado.httpclient imp... |
from __future__ import print_function
import copy
import errno
import gc
import logging
import os
import pprint
import socket
import sys
import traceback
import eventlet.backdoor
import greenlet
from oslo_config import cfg
from neutron.openstack.common._i18n import _LI
help_for_backdoor_port = (
"Acceptable values ... |
"""
runtests.py [OPTIONS] [-- ARGS]
Run tests, building the project first.
Examples::
$ python runtests.py
$ python runtests.py -s {SAMPLE_SUBMODULE}
$ python runtests.py -t {SAMPLE_TEST}
$ python runtests.py --ipython
$ python runtests.py --python somescript.py
$ python runtests.py --bench
Run ... |
ANSIBLE_METADATA = {'metadata_version': '1.0',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = '''
---
module: nxos_vpc_interface
extends_documentation_fragment: nxos
version_added: "2.2"
short_description: Manages interface VPC configuration
description:
... |
class Buffer(object):
"""
A Buffer is a simple FIFO buffer. You write() stuff to it, and you
read() them back. You can also peek() or drain() data.
"""
def __init__(self, data=''):
"""
Initialize a buffer with 'data'.
"""
self.buffer = bytes(data)
def read(self, n... |
"""
Write the collected stats to a locally stored log file. Rotate the log file
every night and remove after 7 days.
"""
from Handler import Handler
import logging
import logging.handlers
class ArchiveHandler(Handler):
"""
Implements the Handler abstract class, archiving data to a log file
"""
def __ini... |
"""
Tests for django.core.servers.
"""
from __future__ import unicode_literals
import os
import socket
try:
from urllib.request import urlopen, HTTPError
except ImportError: # Python 2
from urllib2 import urlopen, HTTPError
from django.core.exceptions import ImproperlyConfigured
from django.test import Live... |
import gyp
import gyp.common
import gyp.SCons as SCons
import os.path
import pprint
import re
WriteList = SCons.WriteList
generator_default_variables = {
'EXECUTABLE_PREFIX': '',
'EXECUTABLE_SUFFIX': '',
'STATIC_LIB_PREFIX': '${LIBPREFIX}',
'SHARED_LIB_PREFIX': '${SHLIBPREFIX}',
'STATIC_LIB_SUFFIX':... |
"""Core event interfaces."""
from . import event, exc
from .pool import Pool
from .engine import Connectable, Engine, Dialect
from .sql.base import SchemaEventTarget
class DDLEvents(event.Events):
"""
Define event listeners for schema objects,
that is, :class:`.SchemaItem` and other :class:`.SchemaEventTarg... |
import datetime
from nova.openstack.common import timeutils
class ViewBuilder(object):
"""OpenStack API base limits view builder."""
def build(self, rate_limits, absolute_limits):
rate_limits = self._build_rate_limits(rate_limits)
absolute_limits = self._build_absolute_limits(absolute_limits)
... |
DOCUMENTATION = '''
---
module: openvswitch_bridge
version_added: 1.4
author: "David Stygstra (@stygstra)"
short_description: Manage Open vSwitch bridges
requirements: [ ovs-vsctl ]
description:
- Manage Open vSwitch bridges
options:
bridge:
required: true
description:
- Name of brid... |
import unittest
from koans.about_asserts import AboutAsserts
from koans.about_strings import AboutStrings
from koans.about_none import AboutNone
from koans.about_lists import AboutLists
from koans.about_list_assignments import AboutListAssignments
from koans.about_dictionaries import AboutDictionaries
from koans.about_... |
import unittest
from coalib.core.CircularDependencyError import CircularDependencyError
class CircularDependencyErrorTest(unittest.TestCase):
def test_default_message(self):
with self.assertRaises(CircularDependencyError) as cm:
# test the default case (names is None)
raise CircularD... |
import re
import unittest
from urlparse import urlsplit, urlunsplit
from xml.dom.minidom import parseString, Node
from django.conf import settings
from django.core import mail
from django.core.management import call_command
from django.core.urlresolvers import clear_url_caches
from django.db import transaction
from dja... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = '''
---
module: tower_credential
author: "Wayne Witzel III (@wwitzel3)"
version... |
"""This module provides the components needed to build your own __import__
function. Undocumented functions are obsolete.
In most cases it is preferred you consider using the importlib module's
functionality over this module.
"""
from _imp import (lock_held, acquire_lock, release_lock,
get_frozen_obj... |
"""Tests for embedding layers."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.python.keras._impl import keras
from tensorflow.python.keras._impl.keras import testing_utils
from tensorflow.python.platform import test
class EmbeddingTest(tes... |
name1_1_1_0_0_1_0 = None
name1_1_1_0_0_1_1 = None
name1_1_1_0_0_1_2 = None
name1_1_1_0_0_1_3 = None
name1_1_1_0_0_1_4 = None |
from hashlib import sha1
import logging
from lxml import etree, objectify
from pprint import pformat
import time
from urllib import urlencode
import urllib2
import urlparse
from openerp.addons.payment.models.payment_acquirer import ValidationError
from openerp.addons.payment_ogone.controllers.main import OgoneControlle... |
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = r'''
---
module: win_msg
version_added: "2.3"
short_description: Sends a message to logged in users on Windows hosts.
description:
- Wraps the msg.exe command in... |
import warnings
warnings.warn('gevent.coros has been renamed to gevent.lock', DeprecationWarning, stacklevel=2)
from gevent.lock import *
from gevent.lock import __all__ |
from __future__ import print_function
import os
import sys
from functools import wraps
from django.conf import settings
from south.hacks import hacks
try:
# easiest and best is unittest included in Django>=1.3
from django.utils import unittest
except ImportError:
# earlier django... use unittest from stdlib... |
""" Python Character Mapping Codec generated from 'VENDORS/APPLE/ARABIC.TXT' with gencodec.py.
"""#"
import codecs
class Codec(codecs.Codec):
def encode(self,input,errors='strict'):
return codecs.charmap_encode(input,errors,encoding_map)
def decode(self,input,errors='strict'):
return codecs.char... |
from __future__ import unicode_literals
from django.contrib.gis.db.models import F, Collect, Count, Extent, Union
from django.contrib.gis.geometry.backend import Geometry
from django.contrib.gis.geos import GEOSGeometry, MultiPoint, Point
from django.db import connection
from django.test import TestCase, skipUnlessDBFe... |
import urlparse,urllib2,urllib,re
import os
from core import scrapertools
from core import logger
from core import config
def get_long_url( short_url ):
logger.info("servers.adfly get_long_url(short_url='%s')" % short_url)
request_headers = []
request_headers.append(["User-Agent","Mozilla/5.0 (Macintosh; U;... |
"""
18. Using SQL reserved names
Need to use a reserved SQL name as a column name or table name? Need to include
a hyphen in a column or table name? No problem. Django quotes names
appropriately behind the scenes, so your database won't complain about
reserved-name usage.
"""
from django.db import models
from django.ut... |
from . import common
from .common import * |
from test import support
import unittest
import codecs
import locale
import sys, _testcapi, io
class Queue(object):
"""
queue: write bytes at one end, read bytes from the other end
"""
def __init__(self, buffer):
self._buffer = buffer
def write(self, chars):
self._buffer += chars
... |
import logging, sys, os, re
from PyKDE4.kdeui import *
from PyKDE4.kdecore import i18n
from PyQt4.QtGui import *
from PyQt4.QtCore import SIGNAL, Qt, QRegExp
__all__ = ["validate", "EMPTY_FIELD_REGEX", "AbbrSettingsDialog", "HotkeySettingsDialog", "WindowFilterSettingsDialog", "RecordDialog"]
import abbrsettings, hotke... |
import tarfile as tf
import zipfile as zf
import os, re, shutil, sys, platform
pyversion = platform.python_version()
islinux = platform.system().lower() == 'linux'
if pyversion[:3] in ['2.6', '2.7']:
import urllib as urllib_request
import codecs
open = codecs.open
_unichr = unichr
if sys.maxunicode ... |
import os, sys, json, urlparse, urllib
def get_template(template_basename):
script_directory = os.path.dirname(os.path.abspath(__file__))
template_directory = os.path.abspath(os.path.join(script_directory,
"..",
... |
"""
postgresql.conf configuration file reader
Module contents:
readfile() - Read postgresql.conf file
class gucdict - Container for postgresql.conf settings
class setting - Holds one setting
class ConfigurationError - a subclass of EnvironmentError
Example:
import lib.pgconf as pgconf
d = pgconf... |
try:
from urllib.parse import urlencode
except ImportError:
from urllib import urlencode
from .filepost import encode_multipart_formdata
__all__ = ['RequestMethods']
class RequestMethods(object):
"""
Convenience mixin for classes who implement a :meth:`urlopen` method, such
as :class:`~urllib3.conne... |
from django.conf import settings
from django.db.backends.postgresql_psycopg2.creation import DatabaseCreation
from django.utils.functional import cached_property
class PostGISCreation(DatabaseCreation):
geom_index_type = 'GIST'
geom_index_ops = 'GIST_GEOMETRY_OPS'
geom_index_ops_nd = 'GIST_GEOMETRY_OPS_ND'
... |
from django.conf.urls import patterns
from django.conf.urls import url
from openstack_dashboard.dashboards.admin.defaults import views
urlpatterns = patterns(
'openstack_dashboard.dashboards.admin.defaults.views',
url(r'^$', views.IndexView.as_view(), name='index'),
url(r'^update_defaults$',
views.U... |
'''
TZlibTransport provides a compressed transport and transport factory
class, using the python standard library zlib module to implement
data compression.
'''
from __future__ import division
import zlib
from cStringIO import StringIO
from TTransport import TTransportBase, CReadableTransport
class TZlibTransportFactor... |
from btcommon import *
raise NotImplementedError |
import sys
from m2ext import SSL
from M2Crypto import X509
print "Validating certificate %s using CApath %s" % (sys.argv[1], sys.argv[2])
cert = X509.load_cert(sys.argv[1])
ctx = SSL.Context()
ctx.load_verify_locations(capath=sys.argv[2])
if ctx.validate_certificate(cert):
print "valid"
else:
print "invalid" |
"""email package exception classes."""
class MessageError(Exception):
"""Base class for errors in the email package."""
class MessageParseError(MessageError):
"""Base class for message parsing errors."""
class HeaderParseError(MessageParseError):
"""Error while parsing headers."""
class BoundaryError(Messag... |
try:
import json
except ImportError:
import simplejson as json
import socket
import ssl
try:
from httplib import HTTPConnection, HTTPSConnection
except ImportError:
# Python 3
from http.client import HTTPConnection, HTTPSConnection
class UnixHTTPConnection(HTTPConnection):
def __init__(self, pat... |
from south.db import db
from south.v2 import SchemaMigration
try:
from django.contrib.auth import get_user_model
except ImportError: # django < 1.5
from django.contrib.auth.models import User
else:
User = get_user_model()
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model... |
"""
Django Administration forms module
"""
from student.forms import PasswordResetFormNoActive |
"""
Cached, database-backed sessions.
"""
from django.conf import settings
from django.contrib.sessions.backends.db import SessionStore as DBStore
from django.core.cache import cache
KEY_PREFIX = "django.contrib.sessions.cached_db"
class SessionStore(DBStore):
"""
Implements cached, database backed sessions.
... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
from ansible.plugins.action import ActionBase
from ansible.plugins.action.net_config import ActionModule as NetActionModule
class ActionModule(NetActionModule, ActionBase):
pass |
from __future__ import print_function
from pyspark.ml.feature import SQLTransformer
from pyspark.sql import SparkSession
if __name__ == "__main__":
spark = SparkSession\
.builder\
.appName("SQLTransformerExample")\
.getOrCreate()
# $example on$
df = spark.createDataFrame([
(0... |
"""
The server module is responsible for managng the threaded UDP socket server.
This server is used to communicate with Matlab/Simulink simulations. It will be renamed appropriately soon
@todo: rename this module to indicate it's role in any Matlab connections
"""
from __future__ import absolute_import, division, prin... |
from io import StringIO
from pcrunner.configuration import (
read_check_commands,
read_check_commands_txt,
read_check_commands_yaml,
)
def test_read_check_commmands_txt_with_extra_lines():
fd = StringIO(
u'''SERVICE|CHECK_01|check_dummy.py|0 OK -s 0
SERVICE|CHECK_02|check_dummy.py|1 WARNING -s 1... |
import sys, socket
import os
from time import time
DEFAULT_PORT = 52423
PROGRESSBAR_WIDTH = 50
BUFSIZE = 1024*1024
CONNECTION_TIMEOUT = 3.0
RECEIVE_TIMEOUT = 5.0
if os.name == "nt":
sep = "\\"
else:
sep = '/'
def main():
if len(sys.argv)<2:
usage()
return
if sys.argv[1]=='-s' and len(sys.argv) >= 4:
try:
s... |
"""
--------------------------------------------------------------------------------
Created: Jackson Lee 11/4/14
This script reads in a tab delimited file of annotations and queries
asynchronously the MGRAST REST API to parse back the original ncbi tax_id entry.
This script then uses the ncbi tax_id to query the taxo... |
"""Implementation of Pearson collaborative filtering algorithm"""
from math import sqrt, pow
from mlcollection.lib.collaborativefiltering.collaborativefilterbase import \
AbstractCollaborativeFilter
from operator import itemgetter
from scipy import stats, isnan
__author__ = 'Paul Osborne <osbpau@gmail.com>'
class P... |
from django.shortcuts import render
from django.utils.translation import activate
def index(request):
# latest_question_list = Question.objects.order_by('-pub_date')[:5]
# context = {'latest_question_list': latest_question_list}
# activate('pt-br')
# print(request.LANGUAGE_CODE)
context = {}
ret... |
import os
import sys
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
import smatrix
import scattering
import g1
import g2
import generators |
from setuptools import setup, find_packages
with open('pyluno/meta.py') as f:
exec(f.read())
setup(
name='pyluno',
version=__version__,
packages=find_packages(exclude=['tests']),
description='A Luno API for Python',
author='Cayle Sharrock/Grant Stephens',
author_email='grant@stephens.co.za',... |
import re
from django.db.models import fields
from django.template.defaultfilters import slugify
def _unique_slugify(instance, value, slug_field_name='slug', queryset=None, slug_separator='-'):
slug_field = instance._meta.get_field(slug_field_name)
slug_len = slug_field.max_length
# Sort out the initial slu... |
import _plotly_utils.basevalidators
class VsrcValidator(_plotly_utils.basevalidators.SrcValidator):
def __init__(self, plotly_name="vsrc", parent_name="cone", **kwargs):
super(VsrcValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
edit_type=kwarg... |
""" hmacHash.py
Implemention of Request for Comments: 2104
HMAC: Keyed-Hashing for Message Authentication
HMAC is a mechanism for message authentication
using cryptographic hash functions. HMAC can be used with any
iterative cryptographic hash function, e.g., MD5, SHA-1, in
combination with a s... |
from __future__ import absolute_import
import six
if six.PY3:
from unittest import TestCase, mock
else:
import sys
if sys.version_info < (2, 7, 0):
from unittest2 import TestCase
else:
from unittest import TestCase
import mock
from BacklogPy.base import BacklogBase
class TestBacklogB... |
import matplotlib.pyplot as plt
import numpy as np
T = 2
mu = 0.1
sigma = 0.1
S0 = 10
dt = 0.01
alpha = 0.1
N = round(T/dt)
t = np.linspace(0, T, N)
W = np.random.standard_normal(size = N)
W = np.cumsum(W)*np.sqrt(dt) ### standard brownian motion ###
X = ((mu + alpha * W)-0.5*sigma**2)*t + sigma*W
S = S0*np.exp(X) ### ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.