content stringlengths 4 20k |
|---|
import unittest
import sys
import os
try:
profile
except NameError:
def profile(f):
return f
# Add the directory containing 'grendel' to the sys.path
sys.path.append(os.path.join(os.path.dirname(__file__), os.pardir, os.pardir, os.pardir))
# Add the directory containing the 'grendel_tests' package to... |
from django.http import HttpResponseRedirect
from django.shortcuts import render
# Creation of object
def new(request, instance, form_class, template_path, ok_url, extra_form_parameters=None):
if extra_form_parameters is None:
extra_form_parameters = {}
if request.method == "POST":
form = for... |
"""Commands: !tip <USERNAME> <AMOUNT>"""
import time
from bot.commands.abstract.command import Command
from bot.utilities.permission import Permission
from bot.utilities.tools import replace_vars
class Tip(Command):
"""Tip spampoints to another user."""
perm = Permission.User
def __init__(self, bot):
... |
# -*- coding: utf-8 -*-
import bitarray
from solver import simplify_clauses, pycosat_solve, assignment_to_clauses, \
lits_to_assignment
from propositional_logic import UnassignedSymbol
class Claused(object):
relevant_io = {}
def __init__(self, formula, relevant_io=None):
if releva... |
from os.path import join
import numpy
import warnings
def configuration(parent_package='', top_path=None):
from numpy.distutils.misc_util import Configuration
from numpy.distutils.system_info import get_info, BlasNotFoundError
config = Configuration('svm', parent_package, top_path)
config.add_subpa... |
import os
import re
import mimetypes
from base64 import b64encode
from compressor.conf import settings
from compressor.filters import FilterBase
class DataUriFilter(FilterBase):
"""Filter for embedding media as data: URIs.
Settings:
COMPRESS_DATA_URI_MAX_SIZE: Only files that are smaller than this
... |
import sys, os, arcgisscripting, subprocess
def check_output(command,console):
if console == True:
process = subprocess.Popen(command)
else:
process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, universal_newlines=True)
output,error = proce... |
from msrest.serialization import Model
class CheckNameResponse(Model):
"""CheckNameResponse.
:param name_available: Specifies a Boolean value that indicates whether
the specified Power BI Workspace Collection name is available to use.
:type name_available: bool
:param reason: Reason why the work... |
"""Invenio module to match JSON records against the record database."""
import os
from setuptools import find_packages, setup
readme = open('README.rst').read()
history = open('CHANGES.rst').read()
tests_require = [
'check-manifest>=0.25',
'coverage>=4.0',
'mock>=1.0.0',
'pydocstyle>=1.0.0',
'py... |
import numpy as np
def distribute_vector(v_sub, comm, G, src_proc):
my_id = comm.Get_rank()
if my_id == src_proc:
for i in G.nodes():
if G.node[i]['owner'] != my_id:
comm.Send(v_sub[i], dest=G.node[i]['owner'])
if my_id != src_proc:
v_sub = dict()
for i... |
# 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):
# Adding field 'Feed.active_premium_subscribers'
db.add_column('feeds', 'active_premium_subscribers', self... |
from django.shortcuts import render, redirect, get_object_or_404
from django.core.urlresolvers import reverse
from django.utils.translation import ugettext as _
from django.views.decorators.vary import vary_on_headers
from wagtail.utils.pagination import paginate
from wagtail.wagtailsearch import forms as search_form... |
import traceback
from bs4 import BeautifulSoup
from couchpotato.core.helpers.encoding import toUnicode
from couchpotato.core.helpers.variable import tryInt
from couchpotato.core.logger import CPLog
from couchpotato.core.media._base.providers.torrent.base import TorrentProvider
log = CPLog(__name__)
class Base(Torr... |
from __future__ import absolute_import, division, print_function
class FrozenInstanceError(AttributeError):
"""
A frozen/immutable instance has been attempted to be modified.
It mirrors the behavior of ``namedtuples`` by using the same error message
and subclassing :exc:`AttributeError`.
.. vers... |
"""argvemulator - create sys.argv from OSA events. Used by applets that
want unix-style arguments.
"""
import sys
import traceback
from Carbon import AE
from Carbon.AppleEvents import *
from Carbon import Evt
from Carbon.Events import *
import aetools
class ArgvCollector:
"""A minimal FrameWork.Application-like ... |
# coding: utf-8
"""Attribute scoping support for symbolic API."""
from __future__ import absolute_import
from ._base import string_types
class AttrScope(object):
"""Attribute manager for scoping.
User can also inherit this object to change naming behavior.
Parameters
----------
kwargs
Th... |
"""Base interface for metrics to implement.
To create a new metric:
1. Subclass `Metric` or `PercentMetric`
2. Implement `_score_value`, `_compute_value`, and (unless you're using
`PercentMetric`) `_format_value` and define the UNIT (for history plots)
3. Call `metrics.base.Metric.register(YourNewMetric)`
4. Import... |
# -*- coding: utf-8 -*-
from south.utils import datetime_utils as 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 'Booking.refrigerator'
db.add_column(u'booking_booking', '... |
"""GDAL backend for GSDView."""
import shutil
from gsdview.gdalbackend.info import *
from gsdview.gdalbackend.info import __version__, __requires__
from gsdview.gdalbackend.core import GDALBackend
__all__ = [
'init', 'close', 'loadSettings', 'saveSettings',
'name', 'version', 'short_description', 'descripti... |
import tkinter
from random import choice, randint
ball_initial_number = 20
ball_minimal_radius = 15
ball_maximal_radius = 40
ball_available_colors = ['green', 'blue', 'red', 'lightgray', '#FF00FF', '#FFFF00']
def click_ball(event):
"""
Обработчик событий для игрового холста canvas
:param event: события с... |
"""Mocks for powerwall."""
import json
import os
from unittest.mock import MagicMock, Mock
from tesla_powerwall import (
DeviceType,
GridStatus,
MetersAggregates,
Powerwall,
PowerwallStatus,
SiteInfo,
SiteMaster,
)
from tests.common import load_fixture
async def _mock_powerwall_with_fix... |
import cStringIO
import functools
import multiprocessing
import optparse
import os
import re
import shutil
import subprocess
import sys
import common
import pngdiffer
import suppressor
class KeyboardInterruptError(Exception): pass
# Nomenclature:
# x_root - "x"
# x_filename - "x.ext"
# x_path - "path/to/a/b/c/... |
"""The :xfile:`models.py` module for :mod:`lino_noi`.
Defines a handler for :data:`lino.modlib.smtpd.signals.mail_received`.
"""
from email.parser import Parser
from lino.api import dd
# from lino.modlib.smtpd.signals import mail_received
# @dd.receiver(mail_received)
# def process_message(sender=None, peer=None,... |
"""
Test robust handling of input arguments to plotSpectrum, plotBin, and plotMD
All these functions should throw a ValueError exception when, for example:
- the specified workspaces don't exist
- the index(es) of spectra, bin or dimension is wrong
"""
from __future__ import (absolute_import, division, print_functio... |
from worldengine.simulations.basic import find_threshold_f
import numpy
class WatermapSimulation(object):
@staticmethod
def is_applicable(world):
return world.has_precipitations() and (not world.has_watermap())
def execute(self, world, seed):
assert seed is not None
data, thresho... |
from datetime import timedelta
import mock
from oslo_utils import timeutils
from cinder import context as ctxt
from cinder.image import cache as image_cache
from cinder import test
class ImageVolumeCacheTestCase(test.TestCase):
def setUp(self):
super(ImageVolumeCacheTestCase, self).setUp()
self... |
import sys, os
sys.path.insert(1, os.path.join("..","..",".."))
import h2o
from tests import pyunit_utils
from h2o.estimators.deeplearning import H2ODeepLearningEstimator
def checkpoint_new_category_in_predictor():
sv1 = h2o.upload_file(pyunit_utils.locate("smalldata/iris/setosa_versicolor.csv"))
sv2 = h2o.uploa... |
#!/usr/bin/env python3
"""
gftools lang
Generates Language/Region metadata.
CLDR info is supplemented with Hyperglot
(https://github.com/rosettatype/hyperglot), which pulls from other data sources
and consequently has a more complete set of language metadata.
Usage:
# Standard usage. Output lang metadata to a dir. ... |
# -*- coding: utf-8 -*-
#------------------------------------------------------------
import urlparse,urllib2,urllib,re
import os, sys
from platformcode import config, logger
from core import scrapertools
from core.item import Item
from core import servertools
from core import httptools
host = 'http://hd.xtapes.to'
#... |
"""objective: Learning addition. Input: "53+61", Expect output: "114" """
from __future__ import print_function
from keras.models import Sequential
from keras import layers
import numpy as np
MAX_DIGIT = 2
TRAINING_SIZE = 5000 # < 10**(MAX_DIGIT*2)
STOP_ACCURACY = 0.9 # fit until this percentage
print(__doc__, '. Lea... |
"""
* Copyright 2007,2008,2009 John C. Gunther
* Copyright (C) 2009 Luke Kenneth Casson Leighton <<EMAIL>>
*
* Licensed under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at:
*
* http:#www.apache.org/licenses/... |
"This is the locale selecting middleware that will look at accept headers"
from django.conf import settings
from django.conf.urls.i18n import is_language_prefix_patterns_used
from django.http import HttpResponseRedirect
from django.urls import get_script_prefix, is_valid_path
from django.utils import translation
from ... |
import gobject
import gtk
import utils
import TextBufferMarkup
import pango
MODE_EDITING = 0
MODE_IMAGE = 1
MODE_DRAW = 2
class BaseThought (gobject.GObject):
''' The basic class to derive other thoughts from. \
Instructions for creating derivative thought types are \
given as comments'''
# ... |
"""
This is incomplete
"""
import numpy as np
from sklearn.ensemble.forest import BaseForest
from sklearn.tree.tree import BaseDecisionTree
from sklearn.ensemble.weight_boosting import AdaBoostClassifier
from sklearn.tree._tree import DTYPE
from sklearn.utils import check_X_y
class AdaBoostAbstainingClassifier(AdaBo... |
import os
from flask import Flask
from flask.json import JSONEncoder
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager
from flask_openid import OpenID
from flask_mail import Mail
from flask_babel import Babel, lazy_gettext
from config import basedir, ADMINS, MAIL_SERVER, MAIL_PORT, MAIL_USERN... |
#!/usr/bin/python
"""
generate_fuel_table_data.py
:author: Brandon Arrendondo
:license: MIT
"""
import sys
import argparse
import logging
import math
from src.factory import build_technology
from src.model.enumerations import TechnologyId
from src.language import Language_Map
from src.language import load... |
# -*- coding: utf-8 -*-
from south.utils import datetime_utils as 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 'Photo'
db.create_table(u'hotels_photo', (
(u'... |
import timeit
import unittest
import sys
from StringIO import StringIO
import time
from textwrap import dedent
from test.test_support import run_unittest
from test.test_support import captured_stdout
from test.test_support import captured_stderr
# timeit's default number of iterations.
DEFAULT_NUMBER = 1000000
# tim... |
# -*- coding: utf-8 -*-
"""This file contains the text format specific event object classes."""
from plaso.events import time_events
from plaso.lib import eventdata
class TextEvent(time_events.TimestampEvent):
"""Convenience class for a text format-based event."""
DATA_TYPE = 'text:entry'
def __init__(self, ... |
"""Feature Pyramid Networks.
Feature Pyramid Networks were proposed in:
[1] Tsung-Yi Lin, Piotr Dollar, Ross Girshick, Kaiming He, Bharath Hariharan,
, and Serge Belongie
Feature Pyramid Networks for Object Detection. CVPR 2017.
"""
from __future__ import absolute_import
from __future__ import division
from _... |
# -*- coding: utf-8 -*-
"""
Catch-up TV & More
Copyright (C) 2016 SylvainCecchetto
This file is part of Catch-up TV & More.
Catch-up TV & More 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 Foundat... |
"""
byceps.services.board.topic_query_service
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:Copyright: 2006-2019 Jochen Kupperschmidt
:License: Modified BSD, see LICENSE for details.
"""
from datetime import datetime
from typing import Optional, Set
from ...database import db, Pagination, Query
from ..authentication.s... |
from katello.client.api.base import KatelloAPI
from katello.client.lib.utils.encoding import u_str
from katello.client.lib.utils.data import update_dict_unless_none
class ChangesetAPI(KatelloAPI):
def changesets(self, orgName, envId):
path = "/api/organizations/%s/environments/%s/changesets/" % (orgName, ... |
# freda (todo) :
import os, time, sys, math
import subprocess, shutil
from os.path import *
import numpy as np
from inspect import isclass
from pytz import timezone
from datetime import datetime
import inspect
import torch
def datestr():
pacific = timezone('US/Pacific')
now = datetime.now(pacific)
return... |
from oslo_context import context as oslo_context
REQUEST_CONTEXT_ENV = 'keystone.oslo_request_context'
def _prop(name):
return property(lambda x: getattr(x, name),
lambda x, y: setattr(x, name, y))
class RequestContext(oslo_context.RequestContext):
def __init__(self, **kwargs):
... |
"""Tests for resource tracker claims."""
import uuid
import mock
from oslo_serialization import jsonutils
from nova.compute import claims
from nova import context
from nova import db
from nova import exception
from nova import objects
from nova.pci import manager as pci_manager
from nova import test
from nova.tests.... |
#!/usr/bin/env python
"""Benchmarks for Python's regex engine.
These are some of the original benchmarks used to tune Python's regex engine
in 2000 written by Fredrik Lundh. Retreived from
http://mail.python.org/pipermail/python-dev/2000-August/007797.html and
integrated into Unladen Swallow's perf.py in 2009 by Davi... |
import scipy.io
from sklearn import cross_validation
from sklearn import svm
from sklearn.metrics import accuracy_score
from skfeature.function.similarity_based import fisher_score
def main():
# load data
mat = scipy.io.loadmat('../data/COIL20.mat')
X = mat['X'] # data
X = X.astype(float)
y = m... |
import warnings
import sqlalchemy as sa
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base, synonym_for
from sqlalchemy.ext.hybrid import hybrid_property
from sqlalchemy.orm import sessionmaker
from sqlalchemy_utils import (
aggregates,
coercion_listener,
i18n,
... |
from __future__ import absolute_import, division, print_function
import pytest
from _pytest.main import EXIT_NOTESTSCOLLECTED
class SessionTests(object):
def test_basic_testitem_events(self, testdir):
tfile = testdir.makepyfile(
"""
def test_one():
pass
... |
"""
:mod:`plainbox.impl.commands.special` -- special sub-command
============================================================
.. warning::
THIS MODULE DOES NOT HAVE STABLE PUBLIC API
"""
from logging import getLogger
from plainbox.impl.commands.checkbox import CheckBoxCommandMixIn
from plainbox.impl.commands im... |
from __future__ import unicode_literals
import re
from .common import InfoExtractor
from ..utils import (
int_or_none,
unescapeHTML,
find_xpath_attr,
smuggle_url,
determine_ext,
ExtractorError,
)
from .senateisvp import SenateISVPIE
class CSpanIE(InfoExtractor):
_VALID_URL = r'https?://(... |
from getpass import getpass
from telethon import TelegramClient
from telethon.errors import SessionPasswordNeededError
from telethon.tl.types import UpdateShortChatMessage, UpdateShortMessage
from telethon.utils import get_display_name
def sprint(string, *args, **kwargs):
"""Safe Print (handle UnicodeEncodeError... |
#!/usr/bin/env python
__all__ = ['ipn_download']
from ..common import *
from bs4 import BeautifulSoup
def ipn_download(url, output_dir='.', info_only=False, limit='0,10'):
l = limit.split(',')
l_begin = 0 if len(l)==1 else int(l[0])
l_end = int(l[0]) if len(l)==1 else int(l[1])
html = get_con... |
""" StorageManagerHandler is the implementation of the StorageManagementDB in the DISET framework """
__RCSID__ = "$Id$"
from types import IntType, DictType, ListType, StringTypes, LongType
from DIRAC import gLogger, S_OK
from DIRAC.Core.DISET.RequestHandler ... |
from PyQt4.QtCore import Qt, QUrl, pyqtSignal, QSettings
from PyQt4.QtGui import QLabel, QVBoxLayout, QColor, QDesktopServices, QDialog, QMainWindow, QWidget
from ert_gui.tools import HelpCenter
class HelpWindow(QMainWindow):
help_prefix = None
default_help_string = "No help available!"
validation_templa... |
import salome
salome.salome_init()
import GEOM
from salome.geom import geomBuilder
geompy = geomBuilder.New(salome.myStudy)
import SMESH, SALOMEDS
from salome.smesh import smeshBuilder
smesh = smeshBuilder.New(salome.myStudy)
# Geometry
# ========
# an assembly of a box, a cylinder and a truncated cone meshed with ... |
from django.conf import settings
import os.path
class FSStorage(object):
def __init__(self, home=None):
self.home = home
if not self.home:
self.home = settings.DAVVY_STORAGE_PATH
def store(self, dav, request, resource, chunk_size=32768):
directory = os.path.join(self.home... |
"""nvp_netbinding
Revision ID: 1d76643bcec4
Revises: 3cb5d900c5de
Create Date: 2013-01-15 07:36:10.024346
"""
# revision identifiers, used by Alembic.
revision = '1d76643bcec4'
down_revision = '3cb5d900c5de'
# Change to ['*'] if this migration applies to all plugins
migration_for_plugins = [
'neutron.plugins.n... |
import json
import xbmc
import xbmcaddon
import xbmcvfs
class SharedData:
__DEFAULT_JSON_CONTENT = {}
def __init__(self):
self.__folder = xbmc.translatePath(xbmcaddon.Addon().getAddonInfo('profile')).decode('utf-8')
if not xbmcvfs.exists(self.__folder):
xbmcvfs.mkdir(self.__fold... |
import sys
sys.path.insert(1,"../../../")
import h2o
from tests import pyunit_utils
def offset_gamma():
# Connect to a pre-existing cluster
insurance = h2o.import_file(pyunit_utils.locate("smalldata/glm_test/insurance.csv"))
insurance["offset"] = insurance["Holders"].log()
gbm = h2o.gbm(x=in... |
"""This code example gets all contacts that aren't invited yet.
To create contacts, run create_contacts.py.
The LoadFromStorage method is pulling credentials and properties from a
"googleads.yaml" file. By default, it looks for this file in your home
directory. For more information, see the "Caching authentication in... |
from odoo import fields
from odoo.tests.common import TransactionCase
from odoo.exceptions import UserError
from odoo.tests.common import Form
class TestPurchaseDeposit(TransactionCase):
def setUp(self):
super(TestPurchaseDeposit, self).setUp()
self.product_model = self.env['product.product']
... |
__title__="Lattice ArrayFromShape object: creates an array of placements from a compound."
__author__ = "DeepSOIC"
__url__ = ""
import math
import FreeCAD as App
import Part
from latticeCommon import *
import latticeBaseFeature
import latticeCompoundExplorer as LCE
import latticeGeomUtils as Utils
import latticeExec... |
#!/usr/bin/env python
"""
figure.py, module definition of Figure class.
"""
# modules loading
# standard library modules: these should be present in any recent python distribution
import re
# modules not in the standard library
from yattag import Doc
# MaTiSSe.py modules
from ..utils.source_editor import obfuscate_code... |
# -*- coding: utf-8 -*-
from django import forms
from django.conf import settings
from django.utils.translation import gettext as _
from resumable_uploads.forms import PlUploadFormField
from resumable_uploads.models import ResumableFile
from core.editor.models import IssueSubmission
class IssueSubmissionForm(forms.... |
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['deprecated'],
'supported_by': 'network'}
import re
from copy import deepcopy
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.network.common.utils import remove_default_spec
from ansible.... |
import os
from .add_channel_command import AddChannelCommand
from .add_repository_command import AddRepositoryCommand
from .create_binary_package_command import CreateBinaryPackageCommand
from .create_package_command import CreatePackageCommand
from .disable_package_command import DisablePackageCommand
from .discover_... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# tip: access from browser via http://localhost:9200/sg/articles/1
from elasticsearch import Elasticsearch
import json
import os
es = Elasticsearch([{'host': 'localhost', 'port': 9200}])
# list all indices
_cmd = """curl http://localhost:9200/_aliases?pretty=1"""
os.system... |
"""Test suite for phlsys_tryloop."""
from __future__ import absolute_import
import datetime
import itertools
import unittest
import phlsys_tryloop
# =============================================================================
# TEST PLAN
# -----------------------------------------... |
from glider_binary_data_reader import GliderBDReader
import argparse
import csv
import sys
import os
def main():
parser = argparse.ArgumentParser(
description="Produce a dataset from targeted glider datatypes"
)
parser.add_argument(
'--timestamp_field',
help='Field to use for time... |
"""Support for Vanderbilt (formerly Siemens) SPC alarm systems."""
import logging
from pyspcwebgw.const import ZoneInput, ZoneType
from homeassistant.components.binary_sensor import BinarySensorEntity
from homeassistant.core import callback
from homeassistant.helpers.dispatcher import async_dispatcher_connect
from .... |
# coding=UTF8
# Строчка выше нужна на случай использования Non-ASCII символов, например кириллицы.
ms_RxTx = {
# RX .1.3.6.1.2.1.31.1.1.1.6 ifHCInOctets
'~RX.1' : '.1.3.6.1.2.1.31.1.1.1.6.1',
'~RX.2' : '.1.3.6.1.2.1.31.1.1.1.6.2',
'~RX.3' : '.1.3.6.1.2.1.31.1.1.1.6.3',
'~RX... |
# -*- coding: utf-8 -*-
"""
WidgetGroup.py - WidgetGroup class for easily managing lots of Qt widgets
Copyright 2010 Luke Campagnola
Distributed under MIT/X11 license. See license.txt for more infomation.
This class addresses the problem of having to save and restore the state
of a large group of widgets.
"""
from... |
from __future__ import unicode_literals
from django.contrib.localflavor.nl.forms import (NLPhoneNumberField,
NLZipCodeField, NLSoFiNumberField, NLProvinceSelect)
from django.test import SimpleTestCase
class NLLocalFlavorTests(SimpleTestCase):
def test_NLProvinceSelect(self):
f = NLProvinceSelect()
... |
#! /usr/bin/env python
import sys
import os.path
try:
from subprocess import check_output
except ImportError:
from subprocess import Popen, PIPE, CalledProcessError
# Compatibility function for Python 2.6 and earlier
def check_output(*args, **kwds):
process = Popen(stdout=PIPE, *args, **kwds)
... |
from app.models import db
class Permission(db.Model):
"""Role-Service Permissions
"""
__tablename__ = 'permissions'
__table_args__ = (db.UniqueConstraint('role_id', 'service_id', name='role_service_uc'),)
id = db.Column(db.Integer, primary_key=True)
role_id = db.Column(db.Integer, db.Foreign... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
# import cloudstack common
from ansible.module_utils.basic import AnsibleModule
from ansible... |
import feedparser
import twitter
# Twitter API Values
api = twitter.Api(consumer_key='Paste Consumer Key Here',
consumer_secret='Paste Consumer Secret Here',
access_token_key='Paste Access Token Key Here',
access_token_secret='Paste Access Token Secret Here')
# parseURL() takes a url to an RSS feed and pa... |
"""
Google OpenID and OAuth support
OAuth works straightforward using anonymous configurations, username
is generated by requesting email to the not documented, googleapis.com
service. Registered applications can define settings GOOGLE_CONSUMER_KEY
and GOOGLE_CONSUMER_SECRET and they will be used in the auth process.
... |
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'status': ['preview'],
'supported_by': 'community',
'metadata_version': '1.1'}
import traceback
from time import time, sleep
from ansible.module_utils._text import to_nativ... |
"""This code example archives a proposal line item.
To determine which proposal line items exist, run
get_all_proposal_line_items.py.
"""
# Import appropriate modules from the client library.
from googleads import dfp
# Set the id of the proposal line item to archive.
PROPOSAL_LINE_ITEM_ID = 'INSERT_PROPOSAL_LINE_I... |
"""
ROS message source code generation for Python
Converts ROS .msg files in a package into Python source code implementations.
"""
import os
import sys
import genpy.generator
import genpy.genpy_main
if __name__ == "__main__":
genpy.genpy_main.genmain(sys.argv, 'genmsg_py.py', genpy.generator.MsgGenerator()) |
# -*- encoding: utf-8 -*-
"""
The :py:mod:`pamqp.body` module contains the :py:class:`Body` class which is
used when unmarshalling body frames. When dealing with content frames, the
message body will be returned from the library as an instance of the body
class.
"""
class ContentBody:
"""ContentBody carries the ... |
"""
kombu.serialization
===================
Serialization utilities.
:copyright: (c) 2009 - 2011 by Ask Solem
:license: BSD, see LICENSE for more details.
"""
import codecs
import sys
import pickle as pypickle
try:
import cPickle as cpickle
except ImportError:
cpickle = None # noqa
from kombu.utils.encodi... |
from __future__ import unicode_literals
from .grammar import COMMAND_GRAMMAR
__all__ = (
'CommandPreviewer',
)
class CommandPreviewer(object):
"""
Already show the effect of Vi commands before enter is pressed.
"""
def __init__(self, editor):
self.editor = editor
def save(self):
... |
from django.conf import settings
from django.contrib.auth import login, authenticate as strava_authenticate
from django import http
from django.shortcuts import redirect
from django.views import generic
class StravaRedirect(generic.RedirectView):
"""
Redirects to the Strava oauth page
"""
def get_... |
import bpy
from mathutils import Vector
def iterActiveSpacesByType(type):
for space in iterActiveSpaces():
if space.type == type:
yield space
def iterActiveSpaces():
for area in iterAreas():
yield area.spaces.active
def getAreaWithType(type):
for area in iterAreasByType(type)... |
"""
Support for Rflink components.
For more details about this component, please refer to the documentation at
https://home-assistant.io/components/rflink/
"""
import asyncio
from collections import defaultdict
import functools as ft
import logging
import async_timeout
import voluptuous as vol
from homeassistant.con... |
""" Log module with colored logging feature. Common usage of this module can
be only importing it and calling one of the available functions: debug,
warning, info, critical, error.
"""
import os
import logging
from logging import getLogger
from brisa import __enable_logging__
from brisa.core import config
BLACK, R... |
"""
Task computing tool
Used to compute invoice, estimation or cancelinvoice totals
"""
import operator
from autonomie.models.tva import Tva
from autonomie.compute import math_utils
def get_default_tva():
"""
Return the default tva
"""
try:
default_tva = Tva.get_default()
excep... |
#!/usr/bin/python
import math
import sys
from scipy import array, exp
from scipy.signal import firwin
from scipy.fftpack import fft, ifft
def fir_minphase(table, pad_size=8):
table = list(table)
# table should be a real-valued table of FIR coefficients
convolution_size = len(table)
table += [0] * (con... |
from oslo.messaging._executors import base
class BlockingExecutor(base.ExecutorBase):
"""A message executor which blocks the current thread.
The blocking executor's start() method functions as a request processing
loop - i.e. it blocks, processes messages and only returns when stop() is
called from ... |
# encoding: UTF-8
'''
本文件中实现了风控引擎,用于提供一系列常用的风控功能:
1. 委托流控(单位时间内最大允许发出的委托数量)
2. 总成交限制(每日总成交数量限制)
3. 单笔委托的委托数量控制
4. 总仓位控制
todo:本风控模块仅支持一个gateway的连接。如果超过多个gateway的连接,仓位模块就会无效啦。
'''
import json
import os
import platform
from eventEngine import *
from vtConstant import *
from vtGateway import VtLogData
from datetime imp... |
import json
import os
import requests
import shutil
from invoke import task, run
from osfoffline.polling_osf_manager.remote_objects import RemoteNode
from osfoffline.polling_osf_manager.api_url_builder import api_url_for, NODES, USERS
from osfoffline import settings
@task
def flake():
run('flake8 . --config=./se... |
"""Placement API handlers for setting and deleting allocations."""
import collections
import jsonschema
from oslo_log import log as logging
from oslo_serialization import jsonutils
import webob
from nova.api.openstack.placement import util
from nova import exception
from nova.i18n import _, _LE
from nova import obje... |
@auth.requires_membership('Clients')
def profile():
import supert
Supert = supert.Supert()
orders_data = Supert.SUPERT(db.sale_order.id_client == auth.user.id,
fields=['id', 'is_ready'], searchable=False,
options_func=lambda r: supert.OPTION_BTN('receipt', URL('ticket', 'get', vars=dict(id_... |
import Gaffer
import GafferUI
Gaffer.Metadata.registerNode(
Gaffer.DependencyNode,
"description",
"""
Base class for nodes where input plugs have an
effect on output plugs.
""",
plugs = {
"enabled" : (
"description",
"""
Turns the node on and off.
""",
"layout:index", -2, # Last but one
... |
# vim: set ts=4 sw=4 expandtab:
import puremvc.patterns.proxy
from vo.TimeVO import TimeVO
import time
class TimeProxy(puremvc.patterns.proxy.Proxy):
NAME = "TimeProxy"
def __init__(self):
super(TimeProxy, self).__init__(TimeProxy.NAME, [])
self.clear()
def clear(self):
sel... |
#!/usr/bin/python
# -*- coding: utf8 -*-
import numpy as np
import numpy.ma as ma
from flowmaker_2 import *
from scipy.io import readsav as restore
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
from correlation import divergen
from astropy.io import fits
def flow(cube):
"""
Programa para gen... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.