content stringlengths 4 20k |
|---|
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""This module defines a Print function to use with python 2.x or 3.x., so we can use the prompt with older versions of
Python too
It's interface is that of python 3.0's print. See
http://docs.python.org/3.0/library/functions.html?highlight=print#print
Shamelessly ripped... |
import string
import sys
import re
import traceback
import gobject
import gtk
import pango
from config import PythonConsoleConfig
__all__ = ('PythonConsole', 'OutFile')
class PythonConsole(gtk.ScrolledWindow):
__gsignals__ = {
'grab-focus' : 'override',
}
def __init__(self, namespace = {}):
... |
#!/usr/bin/env python
import vtk
from vtk.test import Testing
from vtk.util.misc import vtkGetDataRoot
VTK_DATA_ROOT = vtkGetDataRoot()
# create tensor ellipsoids
# Create the RenderWindow, Renderer and interactive renderer
#
ren1 = vtk.vtkRenderer()
renWin = vtk.vtkRenderWindow()
renWin.AddRenderer(ren1)
iren = vtk.v... |
from msrest.serialization import Model
class BatchLocationQuota(Model):
"""Quotas associated with a Batch region for a particular subscription.
Variables are only populated by the server, and will be ignored when
sending a request.
:ivar account_quota: The number of Batch accounts that may be create... |
import ocl
import pyocl
import camvtk
import time
if __name__ == "__main__":
myscreen = camvtk.VTKScreen()
a=ocl.Point(1,0,0)
myscreen.addActor(camvtk.Point(center=(1,0,0), color=(1,1,1)));
b=ocl.Point(0,1,0)
myscreen.addActor(camvtk.Point(center=(0,1,0), color=(1,1,1)));
c=ocl.Point... |
import os
# Configuration file for jupyterhub.
#------------------------------------------------------------------------------
# Configurable configuration
#------------------------------------------------------------------------------
#------------------------------------------------------------------------------
#... |
#!/bin/python
import os
import sys
from pymongo import MongoClient
from bson.objectid import ObjectId
def modifyConfig(expression, value):
print('Modifying server.properties '+expression+' with value '+str(value))
os.system("sed -i 's/"+str(expression)+"/"+str(value)+"/' server.properties")
def modifyLog(expr... |
import sys
import os
import wget
from util.download_image_post import DownloadImagePost
import json
from util.settings import BASE_DIR
def main(arguments):
profiles_path = arguments[1] if len(arguments) > 1 else "profiles"
profile_list = os.listdir(profiles_path)
for profile in profile_list:
fil... |
import collections
import json
import logging
from datetime import datetime
from html.parser import HTMLParser
import dateutil.parser
from django.conf import settings
from django.core.exceptions import ObjectDoesNotExist
from django.db import transaction
from django.template import Context, Template
from django.utils ... |
"""
Given a binary tree, flatten it to a linked list in-place.
For example,
Given
1
/ \
2 5
/ \ \
3 4 6
The flattened tree should look like:
1
\
2
\
3
\
4
\
5
\
6
"""
# Definition for a ... |
"""Tests of openedx.features.discounts.applicability"""
# -*- coding: utf-8 -*-
from datetime import datetime, timedelta
import ddt
import pytz
from django.contrib.sites.models import Site
from django.utils.timezone import now
from enterprise.models import EnterpriseCustomer, EnterpriseCustomerUser
from mock import ... |
"""
Emonoda -- A set of tools to organize and manage your torrents
Copyright (C) 2015 Devaev Maxim <<EMAIL>>
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 t... |
"""
"""
import sys
import logging
import os.path
import datetime
import platform
import pandas
import numpy
from sklearn.neural_network import MLPRegressor
from sklearn.metrics import mean_squared_error
from filter_weather_data import PROCESSED_DATA_DIR
from interpolation.interpolator.logger import StreamToLogger
... |
from django.contrib.syndication.views import Feed as BaseFeed
from django.utils.feedgenerator import Atom1Feed, Rss201rev2Feed
class GeoFeedMixin(object):
"""
This mixin provides the necessary routines for SyndicationFeed subclasses
to produce simple GeoRSS or W3C Geo elements.
"""
def georss_coor... |
#!/usr/bin/env python
"""
* FCKeditor - The text editor for Internet - http://www.fckeditor.net
* Copyright (C) 2003-2008 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the ... |
from __future__ import (absolute_import, division)
__metaclass__ = type
import copy
import json
import sys
from ansible.compat.tests import unittest
from ansible.module_utils import basic
from units.mock.procenv import swap_stdin_and_argv, swap_stdout
empty_invocation = {u'module_args': {}}
class TestAnsibleModul... |
"""Tests for PCI request."""
from nova import exception
from nova.pci import request
from nova import test
_fake_alias1 = """{
"name": "QuicAssist",
"capability_type": "pci",
"product_id": "4443",
"vendor_id": "8086",
"device_type": "ACCEL"
... |
"""
This module contains EXPERIMENTAL support for storing a Whoosh index's files in
the Google App Engine blobstore. This will use a lot of RAM since all files are
loaded into RAM, but it potentially useful as a workaround for the lack of file
storage in Google App Engine.
Use at your own risk, but please report any p... |
# -*- coding: utf-8 -*-
"""
Created on Mon Sep 29 22:53:20 2014
@author: warrenmorningstar
"""
# ======================================================================
from astropy import units, constants
from astropy.cosmology import FlatLambdaCDM
import numpy as np
import evillens as evil
from scipy.interpolate im... |
"""Records or runs web-page-replay data for InstantExtendedManualTests.*.
Typical usage is:
$ cd src/chrome/test/data/search/tools/
$ sudo instant_extended_manual_tests.py record \
../../../../../third_party/webpagereplay/replay.py \
../../../../../out/Debug/interactive_ui_tests \
../replay/archive.wp... |
from __future__ import division, absolute_import, print_function
from .info import __doc__
from numpy.version import version as __version__
import os
# disables OpenBLAS affinity setting of the main thread that limits
# python threads or processes to one core
env_added = []
for envkey in ['OPENBLAS_MAIN_FREE', 'GOTO... |
import itertools
from ..testproc.base import (
DROP_RESULT, DROP_OUTPUT, DROP_PASS_OUTPUT, DROP_PASS_STDOUT)
from ..local import statusfile
from ..testproc.result import Result
OUTCOMES_PASS = [statusfile.PASS]
OUTCOMES_FAIL = [statusfile.FAIL]
OUTCOMES_PASS_OR_TIMEOUT = [statusfile.PASS, statusfile.TIMEOUT]
OUT... |
"""Tests for checkpointing the SampleFromDatasets."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from absl.testing import parameterized
from tensorflow.python.data.experimental.ops import interleave_ops
from tensorflow.python.data.kernel_tests import c... |
"""
kicad_mod.py
Copyright 2015 Adam Greig
Licensed under the MIT licence, see LICENSE file for details.
Helper functions for generating KiCAD footprint files.
"""
from __future__ import print_function, division
CTYD_GAP = 0.25
CTYD_GRID = 0.05
CTYD_WIDTH = 0.01
SILK_WIDTH = 0.15
FAB_WIDTH = 0.01
FONT_SIZE = (1.0, 1... |
import numpy as np
from ase.atoms import Atoms
def write_plt(filename, atoms, data):
if isinstance(atoms, Atoms):
cell = atoms.get_cell()
else:
cell = np.asarray(atoms, float)
if cell.ndim == 2:
c = cell.copy()
cell = c.diagonal()
c.flat[::4] = 0.0
if c.any... |
"""This module contains `Property` attribute representing property objects which
implements getter and setter objects."""
# stdlib
from typing import Any
from typing import Callable as CallableT
from typing import Optional
from typing import Tuple
from typing import Union
# syft relative
from .. import ast
from ..log... |
"""
Legalese
--------
Copyright (c) 2015, 2016 Genome Research Ltd.
Author: Colin Nolan <<EMAIL>>
This file is part of HGI's common Python library
This program is free software: you can redistribute it and/or modify it
under the terms of the GNU Lesser General Public License as published by
the Free Software Foundat... |
"""Makes gravatar url for given email address"""
# Copyright 2010,2011 Good Energy Research Inc. <<EMAIL>>, <<EMAIL>>
#
# This file is part of Good Energy.
#
# Good Energy is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as publis... |
import tornado.httpclient
import ujson
import logging
from .. import cached
from .. internal import Internal
class APIError(Exception):
def __init__(self, code, body):
self.code = code
self.body = body
def __str__(self):
return str(self.code) + ": " + self.body
class AuthResponse(o... |
from decimal import Decimal as D
from django.test import TestCase
from oscar.apps.shipping.scales import Scale
from oscar.apps.basket.models import Basket
from oscar.test import factories
class TestScales(TestCase):
def test_weighs_uses_specified_attribute(self):
scale = Scale(attribute_code='weight')
... |
ANSIBLE_METADATA = {'metadata_version': '1.0',
'status': ['preview'],
'supported_by': 'community'}
import re
class VNIC(object):
UNICAST_MAC_REGEX = r'^[a-f0-9][2-9a-f0]:([a-f0-9]{2}:){4}[a-f0-9]{2}$'
def __init__(self, module):
self.module = module
... |
from __future__ import unicode_literals
import re
from django.core.exceptions import FieldDoesNotExist
from django.db.models.constants import LOOKUP_SEP
from django.db.models.expressions import Col, Expression
from django.db.models.lookups import Lookup
from django.utils import six
gis_lookups = {}
class GISLookup... |
import unittest
import mock
def _make_credentials():
import google.auth.credentials
return mock.Mock(spec=google.auth.credentials.Credentials)
class TestClient(unittest.TestCase):
@staticmethod
def _get_target_class():
from google.cloud.runtimeconfig.client import Client
return C... |
from __future__ import division, unicode_literals
from collections import defaultdict, namedtuple
from itertools import chain, groupby
from indico.modules.events.registration.models.registrations import RegistrationData
from indico.util.date_time import now_utc
from indico.util.i18n import _
class StatsBase(object)... |
from copy import copy
from django.core.exceptions import ImproperlyConfigured
from django.utils.importlib import import_module
from django.http import HttpRequest
# Cache of actual callables.
_standard_context_processors = None
# We need the CSRF processor no matter what the user has in their settings,
# because other... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['stableinterface'],
'supported_by': 'community'}
import datetime
import re
from ansible.module_utils.basic import AnsibleModule
fro... |
from osv import osv, fields
class stock_picking(osv.osv):
_inherit = 'stock.picking'
def _get_price_unit_invoice(self, cursor, user, move_line, type):
if not move_line.sale_line_id and not move_line.purchase_line_id:
if not move_line.picking_id.address_id:
return super(sto... |
import os
import genapi
from genapi import TypeApi, GlobalVarApi, FunctionApi, BoolValuesApi
import numpy_api
h_template = r"""
#ifdef _MULTIARRAYMODULE
typedef struct {
PyObject_HEAD
npy_bool obval;
} PyBoolScalarObject;
extern NPY_NO_EXPORT PyTypeObject PyArrayNeighborhoodIter_Type;
extern NPY_NO... |
import re
import json
import inspect
import types
from django.core.exceptions import ImproperlyConfigured, ObjectDoesNotExist
from django.contrib.admin.utils import display_for_value as admin_display_for_value
from django.core.serializers.json import DjangoJSONEncoder
from django.db.models import Model, QuerySet
from ... |
import os
from subprocess import PIPE, STDOUT, Popen
from tempfile import NamedTemporaryFile, TemporaryDirectory, gettempdir
from airflow.sensors.base_sensor_operator import BaseSensorOperator
from airflow.utils.decorators import apply_defaults
class BashSensor(BaseSensorOperator):
"""
Executes a bash comman... |
from openerp.osv import fields, osv
from openerp.tools.translate import _
class purchase_config_settings(osv.osv_memory):
_name = 'purchase.config.settings'
_inherit = 'res.config.settings'
_columns = {
'group_product_variant': fields.selection([
(0, "No variants on products"),
... |
# Django settings for testproject project.
import os
import multiprocessing
BASE_PATH = os.path.dirname(os.path.normpath(__file__))
FILE_STORAGE_DIR = os.path.join(BASE_PATH, 'tests_file_storage', str(os.getpid()))
DEBUG = True
TEMPLATE_DEBUG = DEBUG
DEBUG_PROPAGATE_EXCEPTIONS = True
ALLOWED_HOSTS = ['*']
ADMINS = ... |
"""This package contains packages that have information for Unit Commitment and Economic Dispatch of Hydro and Thermal Generating Units, Load Forecasting, Automatic Generation Control, and Unit Modeling for Dynamic Training Simulator.
"""
nsURI = "http://iec.ch/TC57/2009/CIM-schema-cim14?profile=http://iec.ch/TC57/20... |
import codecs
import os
import re
from pathlib import Path
import setuptools
here = Path(__file__).resolve().parent
def read(*parts):
# convert `here` to string for Python versions before 3.6
return codecs.open(os.path.join(str(here), *parts), "r", encoding="UTF-8").read()
def find_meta(*meta_file_parts,... |
# -*- coding: utf-8 -*-
"""
Copyright (C) 2013 Dariusz Suchojad <dsuch at zato.io>
Licensed under LGPLv3, see LICENSE.txt for terms and conditions.
"""
from __future__ import absolute_import, division, print_function, unicode_literals
# stdlib
from unittest import TestCase
from uuid import uuid4
# anyjson
from any... |
from dolfin import assemble, MixedFunctionSpace
import petsc4py
import sys
petsc4py.init(sys.argv)
from petsc4py import PETSc
import numpy as np
import P as PrecondMulti
import NSprecond
import MaxwellPrecond as MP
import CheckPetsc4py as CP
class BaseMyPC(object):
def setup(self, pc):
pass
def reset(s... |
from datetime import datetime, timedelta
import pytest
import pytz
from indico.core.settings import PrefixSettingsProxy, SettingsProxy
from indico.core.settings.converters import DatetimeConverter, TimedeltaConverter
from indico.modules.events.settings import EventSettingsProxy
from indico.modules.users import User
... |
from . import post
from .. import db
from ..models import Post, Notification, Solution, Tutorial
from ..forms import EditNotificationForm, EditTutorialForm, EditSolutionForm
from ..tools import privilege_required, count_page
from flask import render_template, url_for, request, redirect, flash, jsonify, session
from f... |
"""
parser.sql.objectadapter module (imdb.parser.sql package).
This module adapts the SQLObject ORM to the internal mechanism.
Copyright 2008-2010 Davide Alberani <<EMAIL>>
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 Fr... |
import os
import shutil
import time
def is_deployed(deploy_path, deployment):
return os.path.exists(os.path.join(deploy_path, "%s.deployed"%(deployment)))
def is_undeployed(deploy_path, deployment):
return os.path.exists(os.path.join(deploy_path, "%s.undeployed"%(deployment)))
def is_failed(deploy_path, depl... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Exercise 6.6 from Kane 1985."""
from __future__ import division
from sympy.physics.mechanics import ReferenceFrame, Point
from sympy.physics.mechanics import inertia, inertia_of_point_mass
from sympy.physics.mechanics import dot
from sympy import symbols
from sympy impo... |
from __future__ import absolute_import
import inspect
import warnings
class RemovedInDjango20Warning(PendingDeprecationWarning):
pass
class RemovedInNextVersionWarning(DeprecationWarning):
pass
class warn_about_renamed_method(object):
def __init__(self, class_name, old_method_name, new_method_name, d... |
from django.conf import settings
from django.utils.translation import ugettext_lazy as _
from django.db.models.fields import CharField
from django.contrib.localflavor.us.us_states import STATE_CHOICES
from django.contrib.localflavor.us.us_states import USPS_CHOICES
class USStateField(CharField):
description = _("... |
# -*- coding: utf-8 -*-
import os
import pygame
from GIFImage import GIFImage
from random import randint
imagePath = "img/pyramids gifs/disp/"
class GIFMode:
def __init__(self):
self.surface = None
self.currentGIF = None
self.nextGIF = None
self.loadingNextGIF = False
s... |
# coding:utf-8
"""这个程序用于进行字符串混淆加密,完美支持英文和中文。
可以加密所有字符串,例如账号、密码或者是一些敏感的词汇,甚至是一个文件。
最重要的是可以多次加密同一段字符,加密加密后的内容。
此版本为 Python3 ,base64 需要用 bytes 类型,如果是 Python2 不需要编码和解码.
这个程序同样也可以加密一个文件"""
__author__ = "JIMhackKING"
# this 的 d 很好的做了代码混淆的字典,可是在导入时会打印一段内容
# from this import d
import base64
import json
d = {'A': 'N', 'C': 'P... |
"""Test the DCAT serializer."""
from __future__ import absolute_import, print_function
from zenodo.modules.records.serializers import dcat_v1
def test_dcat_serializer(db, es, record_with_bucket):
"""Tests the DCAT XSLT-based serializer."""
pid, record = record_with_bucket
serialized_record = dcat_v1.ser... |
'''Collections of messages and their translations, called cliques. Also
collections of cliques (uber-cliques).
'''
import re
import types
from grit import constants
from grit import exception
from grit import lazy_re
from grit import pseudo
from grit import pseudo_rtl
from grit import tclib
class UberClique(object... |
"""Class representing an X.509 certificate."""
from .utils.ASN1Parser import ASN1Parser
from .utils.cryptomath import *
from .utils.keyfactory import _createPublicRSAKey
class X509:
"""This class represents an X.509 certificate.
@type bytes: L{array.array} of unsigned bytes
@ivar bytes: The DER-encoded ... |
from __future__ import division, absolute_import, print_function
import numpy.core as nx
import numpy.lib.ufunclike as ufl
from numpy.testing import (
run_module_suite, TestCase, assert_, assert_equal, assert_array_equal
)
class TestUfunclike(TestCase):
def test_isposinf(self):
a = nx.array([nx.... |
try:
import resource # pylint: disable=F0401
except ImportError:
resource = None # Not available on all platforms
def _ConvertKbToByte(value):
return int(value.replace('kB','')) * 1024
def _GetProcFileDict(contents):
retval = {}
for line in contents.splitlines():
key, value = line.split(':')
retv... |
# encoding: utf-8
from __future__ import unicode_literals
from .common import InfoExtractor
from ..compat import compat_urllib_parse_unquote
class XNXXIE(InfoExtractor):
_VALID_URL = r'^https?://(?:video|www)\.xnxx\.com/video(?P<id>[0-9]+)/(.*)'
_TEST = {
'url': 'http://video.xnxx.com/video1135332/li... |
# -*- coding: ascii -*-
import copy
import logging
from itertools import groupby
from lxml import etree, html
from openerp import SUPERUSER_ID, api, tools
from openerp.addons.website.models import website
from openerp.http import request
from openerp.osv import osv, fields
_logger = logging.getLogger(__name__)
cla... |
__revision__ = "$Id$"
import sys
if sys.version_info[0] == 2 and sys.version_info[1] == 1:
from Crypto.Util.py21compat import *
from Crypto.Util.py3compat import *
from binascii import b2a_hex
import time
import warnings
from Crypto.pct_warnings import ClockRewindWarning
import SHAd256
import FortunaGenerat... |
from m5.objects import *
from base_config import *
nb_cores = 4
root = BaseSESystem(mem_mode='atomic', cpu_class=AtomicSimpleCPU,
num_cpus=nb_cores).create_root() |
from __future__ import unicode_literals
from collections import namedtuple
from functools import partial
from pkg_resources import resource_stream # @UnresolvedImport
from .converters import ConverterManager
from . import basestr
COUNTRIES = {}
COUNTRY_MATRIX = []
#: The namedtuple used in the :data:`COUNTRY_MATRIX... |
"""
=====================================================
Multiclass sparse logisitic regression on newgroups20
=====================================================
Comparison of multinomial logistic L1 vs one-versus-rest L1 logistic regression
to classify documents from the newgroups20 dataset. Multinomial logistic
... |
from ginga import trcalc
from ginga.gw import Widgets
from ginga.util import action
from .base import Stage
class FlipSwap(Stage):
_stagename = 'flip-swap'
def __init__(self):
super(FlipSwap, self).__init__()
self._flip_x = False
self._flip_y = False
self._swap_xy = False
... |
# -*- coding: utf-8 -*-
import datetime
import factory
from factory.alchemy import SQLAlchemyModelFactory
from purchasing.database import db
from purchasing.users.models import User, Role, Department
from purchasing.data.contracts import ContractBase, ContractProperty, ContractType
from purchasing.data.companies im... |
"""Benchmark for the experimental `MatchingFilesDataset`."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import shutil
import tempfile
import time
import numpy as np
from tensorflow.python.client import session
from tensorflow.python.data.exp... |
# coding: utf8
{
'!langcode!': 'hi-in',
'!langname!': 'हिन्दी',
'"update" is an optional expression like "field1=\'newvalue\'". You cannot update or delete the results of a JOIN': '"update" is an optional expression like "field1=\'newvalue\'". You cannot update or delete the results of a JOIN',
'%s %%{row} deleted': '%... |
from pykickstart.errors import KickstartParseError
from pyanaconda.core.i18n import _
from pyanaconda.core.configuration.anaconda import conf
from pyanaconda.core.constants import TIME_SOURCE_SERVER, TIME_SOURCE_POOL
from pyanaconda.core.dbus import DBus
from pyanaconda.core.signal import Signal
from pyanaconda.module... |
from django import http
from django.conf import settings
from utils import next_redirect, confirmation_view
from django.core.exceptions import ObjectDoesNotExist, ValidationError
from django.db import models
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.template.... |
# coding: utf-8
from __future__ import unicode_literals
import re
from .common import InfoExtractor
from ..utils import (
decode_packed_codes,
determine_ext,
ExtractorError,
int_or_none,
NO_DEFAULT,
urlencode_postdata,
)
class XFileShareIE(InfoExtractor):
_SITES = (
(r'daclips\.(... |
#the maximum number of arguments for a function
maxArgs = 36
#stuff to import to be able to open files in the parent directory
import os.path
import sys
print("Generating rf_xmacro_def.h ...");
f = open(os.path.dirname(sys.argv[0]) + "/../include/Preprocessor/rf_xmacro_def.h","w");
#put some required definitions a... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import json
import os
import pytest
from units.compat import unittest, mock
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.network.meraki.meraki import MerakiModule, meraki_argument_spec, HTTPError,... |
# encoding: 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):
# NOTE (vshnayder): This constraint has the wrong field order, so it doesn't actually
# do anything in sqlite. M... |
# Scan an Apple header file, generating a Python file of generator calls.
import sys
from bgenlocations import TOOLBOXDIR, BGENDIR
sys.path.append(BGENDIR)
from scantools import Scanner
LONG = "Dialogs"
SHORT = "dlg"
OBJECT = "DialogPtr"
def main():
input = LONG + ".h"
output = SHORT + "gen.py"
defsoutp... |
import json
from django.views.generic import View
from django.utils.safestring import mark_safe
from django.shortcuts import render_to_response, RequestContext
from django.core.exceptions import PermissionDenied
from rest_framework.views import Response
from rest_framework_swagger.urlparser import UrlParser
from rest... |
import mock
from neutron.common import constants
from neutron import context as neutron_context
from neutron.tests import base as tests_base
# TODO(gsagie) use this until Ryu is in the requierments.txt
try:
from dragonflow.controller import l3_openflow_app as of_app
except Exception:
of_app = None
def ryu_e... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
API_GROUP_NAME = 'API Access Request Approvers'
def add_api_access_group(apps, schema_editor):
Group = apps.get_model('auth', 'Group')
Permission = apps.get_model('auth', 'Permission')
ContentType =... |
'''
PackageFile
'''
##
# Import Modules
#
import os.path
import zipfile
import tempfile
import platform
from Logger.ToolError import FILE_OPEN_FAILURE
from Logger.ToolError import FILE_CHECKSUM_FAILURE
from Logger.ToolError import FILE_NOT_FOUND
from Logger.ToolError import FILE_DECOMPRESS_FAILURE
from Logger.ToolErr... |
"""Spline fitters.
:author: Ludwig Schwardt
:license: Modified BSD
"""
from __future__ import division
from builtins import zip
from builtins import range
import numpy as np
import scipy.interpolate
from .generic import ScatterFit, GridFit, NotFittedError
from .utils import sort_grid, desort_grid
# ---------------... |
from __future__ import division, print_function, unicode_literals
from pysped.xml_sped import (ABERTURA, NAMESPACE_NFE, TagCaracter,
TagDecimal, TagInteiro, XMLNFe,
tira_abertura)
from pysped.nfe.leiaute import ESQUEMA_ATUAL_VERSAO_2 as ESQUEMA_ATUAL
from pyspe... |
from PyKDE4.kdeui import KMainWindow
from PyQt4 import uic
class MainWindow (KMainWindow):
def __init__ (self, parent=None):
KMainWindow.__init__ (self, parent)
# load the .ui file
# !!! __file__ can end with .py[co]!
uipath= __file__[:__file__.rfind ('.')]+'.ui'
(UIMainWin... |
from optparse import make_option
from django.core.management.base import BaseCommand, CommandError
from django.db import transaction
from reversion import revisions as reversion
from editorsnotes.auth.models import Project, User
class Command(BaseCommand):
args = '"<project_name>" <project_slug>'
label = ''... |
import logging
LOG = logging.getLogger(__name__)
logging.basicConfig(level=logging.DEBUG, format="%(asctime)-15s %(message)s")
try:
from idaapi import *
import idc
import idautils
import idaapi
if idaapi.IDA_SDK_VERSION >= 700:
import ida_bytes
except:
print("could not import IDA pytho... |
import angr
import select
######################################
# poll
######################################
class poll(angr.SimProcedure):
# pylint:disable=arguments-differ
def run(self, fds, nfds, timeout): # pylint: disable=unused-argument
try:
nfds_v = self.state.solver.eval_one(nf... |
import sys
if sys.version_info < (3, 0):
PY2 = True
PY3 = False
base_str = (str, unicode)
text_type = unicode
else:
PY2 = False
PY3 = True
base_str = (bytes, str)
text_type = str |
from django.contrib.postgres.signals import register_hstore_handler
from django.db.migrations.operations.base import Operation
class CreateExtension(Operation):
reversible = True
def __init__(self, name):
self.name = name
def state_forwards(self, app_label, state):
pass
def database... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
from os import close
from tempfile import mkstemp, mkdtemp
from traceback import format_exc
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils._text import to_native
def main():
module = AnsibleMod... |
"""
Copyright (c) 2016 Keith Sterling
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
documentation files (the "Software"), to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute,... |
"""
Represents a Subnet
"""
from boto.ec2.ec2object import EC2Object
class Subnet(EC2Object):
def __init__(self, connection=None):
EC2Object.__init__(self, connection)
self.id = None
self.state = None
self.cidr_block = None
self.available_ip_address_count = 0
self.... |
"""Support for Eufy switches."""
import logging
from homeassistant.components.switch import SwitchDevice
DEPENDENCIES = ['eufy']
_LOGGER = logging.getLogger(__name__)
def setup_platform(hass, config, add_entities, discovery_info=None):
"""Set up Eufy switches."""
if discovery_info is None:
return
... |
import os
import tarfile
import mxnet as mx
import numpy as np
from mxnet import gluon
def test_array_dataset():
X = np.random.uniform(size=(10, 20))
Y = np.random.uniform(size=(10,))
dataset = gluon.data.ArrayDataset(X, Y)
loader = gluon.data.DataLoader(dataset, 2)
for i, (x, y) in enumerate(load... |
"""
This module is part of Orion2GoogleSpreadsheet project.
Contains functionality used by Orion2GoogleSpreadsheet to Obtain credentials
and Authenticate clients for communication with Google Data API.
"""
import yaml
import logs
import httplib2
import gdata.spreadsheet.service
from googleapiclient.discovery import b... |
"""Samba 4."""
__docformat__ = "restructuredText"
import os
import sys
import samba.param
def source_tree_topdir():
"""Return the top level source directory."""
paths = ["../../..", "../../../.."]
for p in paths:
topdir = os.path.normpath(os.path.join(os.path.dirname(__file__), p))
if os... |
""" Detailed mehanistic model of BRAF based on Neal Rossen paper. """
from pysb import *
from pysb.util import alias_model_components
def monomers():
Monomer('BRAF', ['ras', 'd', 'vem', 'erk'])
Monomer('Vem', ['raf'])
# IC values
# --------
Parameter('BRAF_0', 1e5)
Parameter('Vem_0', 1000)
... |
import threading
from sqlobject import *
from sqlobject.tests.dbtest import *
from sqlobject.tests.dbtest import setSQLiteConnectionFactory
from test_basic import TestSO1
class SQLiteFactoryTest(SQLObject):
name = StringCol()
def test_sqlite_factory():
setupClass(SQLiteFactoryTest)
if SQLiteFactoryTest._... |
"""
Detects topology and streams it to Gephi
Gephi is a pretty awesome graph visualization/manipulation package. It has
a plugin for streaming graphs back and forth between it and something else.
We use that (by opening a listening socket -- port 8282 by default) and
sending detected switches, links, and (optionally)... |
from geopy.geocoders.base import Geocoder
from django.http import HttpRequest
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
from django.test import TestCase
from tastypie.test import ResourceTestCase, TestApiClient
from storybase.tests.base import (SettingsChangingTestCase,... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.