content
stringlengths
4
20k
# coding: utf-8 """ Management command to get user locations based on their IP address in the Tracker model """ import oppia.management.commands from django.core.management.base import BaseCommand from django.db.models import Count from django.utils.translation import ugettext_lazy as _ from oppia.models import Track...
"""`Chained Factories` pattern.""" from dependency_injector import containers, providers class SqlAlchemyDatabaseService: def __init__(self, session, base_class): self.session = session self.base_class = base_class class TokensService: def __init__(self, id_generator, database): s...
#!/usr/bin/env python # encoding: utf-8 """Verify that all OSF Storage files have Glacier backups and parity files, creating any missing backups. TODO: Add check against Glacier inventory Note: Must have par2 installed to run """ from __future__ import division import os import math import logging import pyrax imp...
#! /usr/bin/env python ''' sends request to action server train works add name works recognise continoulley works recognise once is not very good and switching between the 2 is not goodseems to work if only used short exit also works ''' import rospy import actionlib from face_recognition.msg import * def fi...
from django import template from django.template.defaultfilters import pluralize, filesizeformat from ..util import render_mustache from ..views import get_dataset_info from ..models.dataset import Dataset register = template.Library() @register.filter def dataset_tiles(experiment, include_thumbnails): # only s...
import sys import unittest from mantid.api import * import mantid.simpleapi as sapi class EnggCalibrateTest(unittest.TestCase): _data_ws = None _van_curves_ws = None _van_integ_tbl = None # Note not using @classmethod setUpClass / tearDownClass because that's not supported in the old # unittest ...
from __future__ import with_statement import os.path import sys from alembic import context from sqlalchemy import create_engine, pool from logging.config import fileConfig # This is the Alembic Config object, which provides access to the values within # the .ini file in use. config = context.config # Interpret the...
import re import pytest import pandas as pd @pytest.mark.filterwarnings( # openpyxl "ignore:defusedxml.lxml is no longer supported:DeprecationWarning" ) @pytest.mark.filterwarnings( # html5lib "ignore:Using or importing the ABCs from:DeprecationWarning" ) @pytest.mark.filterwarnings( # fastparqu...
import shopify from test.test_helper import TestCase from pyactiveresource.activeresource import ActiveResource class FulFillmentTest(TestCase): def setUp(self): super(FulFillmentTest, self).setUp() self.fake("orders/450789469/fulfillments/255858046", method='GET', body=self.load_fixture('fulfil...
import os import time from unittest.mock import Mock import asyncio import pytest import boto3 from ..base import Task, Status from ..storages import InMemoryStorage from ..runners import LocalRunService, ECSRunService from ..tasks import TaskProvider from ..environment import EnvironmentProvider from ..exceptions impo...
import signal exception = { signal.SIGINT:KeyboardInterrupt } class Signal: def __init__(self, sig): self.signal = sig self.oldhandler = signal.getsignal(sig) self.pending = False class SignalHandler: def __init__(self): self.signals = {} def signal_handler(self,...
# -*- coding: utf-8 -*- # ------------------------------------------------------------ # streamondemand.- XBMC Plugin # Canal para altadefinizioneone # http://blog.tvalacarta.info/plugin-xbmc/streamondemand. # ------------------------------------------------------------ import re import urlparse from core import confi...
from enigma import eActionMap class ActionMap: def __init__(self, contexts=None, actions=None, prio=0): if not actions: actions = {} if not contexts: contexts = [] self.actions = actions self.contexts = contexts self.prio = prio self.p = eActionMap.getInstance() self.bound = False self.exec_active = F...
# -*- coding:utf-8 -*- from flask import jsonify, request, g, url_for, current_app from .. import db from ..models import Post, Permission, Comment from . import api from .decorators import permission_required @api.route('/comments/') def get_comments(): page = request.args.get('page', 1, type=int) pagination...
from unittest import TestCase import pycqed as pq import os from pycqed.instrument_drivers.physical_instruments._controlbox \ import Assembler as asm class Test_single_qubit_seqs(TestCase): @classmethod def setUpClass(self): print('this is setting up the test') def setAssembler(self, qumis_f...
"""This module abstracts the database interface for common queries.""" from collections import defaultdict import textwrap import time from makani.lib.python import string_util from makani.lib.python.embedded import database # Timeout [s] before considering a TestRunner dead. WATCHDOG_TIMEOUT = 15.0 def Translate...
import time, math from gnuradio import gr import pmt class simple_synchroniser(gr.basic_block): """ docstring for block simple_synchroniser """ def __init__(self, target_period, alpha=1.0, jump_ratio=None, lock_sd=None, ratio=1.0, window_length=100, limit=None, verbose=False): gr.basic_block.__init__(self, n...
import GemRB from GUIDefines import * from ie_stats import * import CommonTables CommonTables.Load() NewLifeWindow = 0 TextArea = 0 TotLabel = 0 AcLabel = 0 HpLabel = 0 StatTable = 0 # maintain this order in all lists! #Stats = [ Str, Int, Wis, Dex, Con, Cha ] Stats = [ 0, 0, 0, 0, 0, 0 ] StatLimit = [ 23, 18, 18, ...
#!/usr/bin/env python3 """ Calculates the average measurement [0..359] Useful when trying to calibrate the angles for a new LIDAR position """ import sys import json import math import statistics import lidar_a1m8 as lidar_util RANGE = 360 # degrees OFFSET = 0 THRESHOLD = 500 # mm MM_TO_INCH = 0.0393701 def ad_to_x...
# coding: utf-8 from bluepy import btle import time import logging import globals from multiconnect import Connector import struct import utils class Yeelight(): def __init__(self): self.name = 'yeelight_bed' self.ignoreRepeat = True self.key = 'bbc123456789abc123456789abc12345' def isvalid(self,name,manuf=''...
from libcloud.compute.providers import get_driver from libcloud.compute.base import NodeSize from libcloud.compute.type import Provider cls = get_driver(Provider.GRIDSCALE) driver = cls('USER-UUID', 'API-TOKEN') # We don't feature packages containing a fix size so you will have to # built your own size object. Make s...
import os import re import tempfile import time import yaml from fabric.api import env, execute, get, hide, local, put, require, run, settings, sudo, task from fabric.contrib import files, project from fabric.utils import abort DEFAULT_SALT_LOGLEVEL = 'info' DEFAULT_SALT_LOGFMT = '%(asctime)s,%(msecs)03.0f [%(name)-...
import importlib from django.conf import settings from django.contrib.auth.models import User, Group from django.contrib.contenttypes import generic from django.contrib.contenttypes.models import ContentType from django.core import urlresolvers from django.db import models from django.utils.translation import ugettext...
from __future__ import absolute_import, print_function, unicode_literals # Stdlib Imports import os import time # Third Party Imports from tornado.web import addslash # First Party Imports import sickbeard from sickbeard import helpers from sickchill.helper.encoding import ek from sickchill.views.common import PageT...
from zeit.content.image.imagegroup import Thumbnails import json import transaction import zeit.cms.browser.view import zeit.content.image.interfaces import zeit.imp.browser.interfaces import zeit.imp.source import zope.app.pagetemplate import zope.cachedescriptors.property class NoMasterImageErrorView(object): ...
import sys sys.path.insert(0, '../Newby-tools/utilities') import math as ma import matplotlib.pyplot as plt import astro_coordinates as ac import operator import MetalicityUtilities as met if __name__ == "__main__": lbCuts = [[48.5, 52.], [68.5, 71.5], [92.5, 95.5], [108.5, 111.5], [128.5, 131.5], [148.5, 151.5],...
# -*- coding: utf-8 -*- """This module contains classes relating to Sonos Alarms.""" from __future__ import unicode_literals import logging import re import weakref from datetime import datetime from . import discovery from .core import PLAY_MODES from .xml import XML log = logging.getLogger(__name__) # pylint: d...
"""Run control manager.""" # This file is part of the ISIS IBEX application. # Copyright (C) 2012-2016 Science & Technology Facilities Council. # All rights reserved. # # This program is distributed in the hope that it will be useful. This program # and the accompanying materials are made available under the terms of ...
from __future__ import absolute_import # Copyright (c) 2010-2015 openpyxl """Write a .xlsx file.""" # Python stdlib imports from io import BytesIO from re import match from zipfile import ZipFile, ZIP_DEFLATED # package imports from openpyxl.xml.constants import ( ARC_SHARED_STRINGS, ARC_CONTENT_TYPES, A...
''' Created on Oct 5, 2010 @author: Mark V Systems Limited (c) Copyright 2010 Mark V Systems Limited, All rights reserved. ''' from arelle import ViewWinTree, XbrlConst from arelle.ModelDtsObject import ModelRelationship from arelle.ModelInstanceObject import ModelFact from collections import defaultdict def viewConc...
from __future__ import absolute_import import struct from collections import namedtuple from . import _enum_base ofp_oxm_class = type("ofp_oxm_class", (_enum_base,), { "prefix": "OFPXMC", "numbers": { "NXM_0": 0x0000, "NXM_1": 0x0001, "OPENFLOW_BASIC": 0x8000, "EXPERIMENTER": 0...
import copy from mongoengine import ValidationError from pecan import abort from pecan.rest import RestController import six from st2api.controllers import resource from st2common import log as logging from st2common.models.api.trigger import TriggerTypeAPI, TriggerAPI, TriggerInstanceAPI from st2common.models.api.ba...
from django.utils.translation import ugettext_lazy as _ from horizon import exceptions from horizon import forms from horizon import messages class FilterForm(forms.SelfHandlingForm): addr = forms.ChoiceField( label=_('Addr'), required=True, choices=[('ShangHai', _('ShangHai')), ...
from south.db import db from south.v2 import SchemaMigration class Migration(SchemaMigration): def forwards(self, orm): # Adding model 'Language' db.create_table('lang_language', ( ('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)), ('code', self.gf('dj...
#! /usr/bin/env python3 """Clean up the regtest environment from create_regnet. This can be run from the command line. main(): Go through each node and kill -9 bitcoind and lightningd based on their pid files. Then remove the regnet directory. """ import os import shutil import signal def stop(pid_path): """St...
from utils import * @login_required def get_all_messages(request): context = {} user = User.objects.get(username=request.user) context['messageto_form'] = MessageToForm() if request.method == 'POST': messageto_form = MessageToForm(request.POST) if messageto_form.is_valid(): print "haha" return redirect(r...
''' Define the sublayers in encoder/decoder layer ''' import torch import torch.nn as nn import torch.nn.init as init from transformer.Modules import BottleLinear as Linear from transformer.Modules import ScaledDotProductAttention #from transformer.Modules import BottleLayerNormalization as LayerNormalization from tra...
import os import json import random import shutil import unittest import tempfile from datetime import datetime import partialhash from dataserv_client.builder import Builder my_shard_size = 1024 * 1024 * 128 # 128 MB my_max_size = 1024 * 1024 * 256 # 256 MB height = int(my_max_size / my_shard_size) fixtures = json...
#!/usr/bin/env python """ 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...
""" This is the main file for the application. """ __author__ = 'coty' import sys import optparse def main(argv): """ This class is the entry point for the application. It takes the arguments, validates them, and passes them on to the appropriate classes to continue execution. There...
import pprint from urllib2 import urlopen def fetch_language_subtag_registry(url=None): """This should be called from a script and saved in data.py for further use""" if url is None: url = 'http://www.iana.org/assignments/language-subtag-registry' subtag_registry = urlopen(url).read().decode("utf-8...
"""Provides a web interface for dumping graph data as JSON. This is meant to be used with /load_from_prod in order to easily grab data for a graph to a local server for testing. """ import base64 import json from google.appengine.ext import ndb from google.appengine.ext.ndb import model from dashboard import reques...
from urllib import request import re from bs4 import BeautifulSoup # Search google, match links by regex, return the links, integration functions get names from links """ Function to return links from google search https://github.com/aviaryan/pythons/blob/master/Others/GoogleSearchLinks.py """ def googleSearchLinks(se...
#!/usr/bin/env python """ Copyright (c) 2006-2015 sqlmap developers (http://sqlmap.org/) See the file 'doc/COPYING' for copying permission """ class _Getch(object): """ Gets a single character from standard input. Does not echo to the screen (reference: http://code.activestate.com/recipes/134892/) ""...
from TileCache.Layer import MetaLayer import TileCache.Client as WMSClient class WMS(MetaLayer): config_properties = [ {'name':'name', 'description': 'Name of Layer'}, {'name':'url', 'description': 'URL of Remote Layer'}, {'name':'user', 'description': 'Username of remote server: used for basic-...
# flake8: noqa """ Learning to Play Pong ===================== In this example, we'll train a **very simple** neural network to play Pong using the OpenAI Gym. At a high level, we will use multiple Ray actors to obtain simulation rollouts and calculate gradient simultaneously. We will then centralize these gradients ...
# -*- coding: utf-8 -*- import copy import numbers # 二次同餘式類 # 由多項式式類衍生,型如x^2+y^2=p from .NTLCongruence import Congruence, Solution from .NTLExceptions import DefinitionError, PCError, PolyError from .NTLPolynomial import Polynomial from .NTLPrimeFactorisation import primeFactorisation from ...
from pysnmp.smi import view from pysnmp.smi.rfc1902 import * __all__ = ['CommandGeneratorVarBinds', 'NotificationOriginatorVarBinds'] class AbstractVarBinds: def getMibViewController(self, snmpEngine): mibViewController = snmpEngine.getUserContext('mibViewController') if not mibViewController: ...
import errno import os import logging import urllib2 import httplib import sys import argparse import mpd from bitreader import BitReader def download_url(uri, range=None): print("\tDownloading {url}, Range: {range}".format(url=uri, range=range)) opener = urllib2.build_opener(m3u8.getCookieProcessor()) i...
import discord from discord.ext import commands from bot import getShelfSlot class UserActions(): def __init__(self, client): self.client = client @commands.command(pass_context = True) async def op(self, ctx, member : discord.Member): operators = getShelfSlot(ctx.messa...
import FreeCAD import FreeCADGui import Path from PySide import QtCore, QtGui """Path Pocket object and FreeCAD command""" # Qt tanslation handling try: _encoding = QtGui.QApplication.UnicodeUTF8 def translate(context, text, disambig=None): return QtGui.QApplication.translate(context, text, disambig,...
from email.mime.text import MIMEText from email.mime.application import MIMEApplication from email.mime.multipart import MIMEMultipart import email.utils import smtplib #Configuracoes Credenciais conta = '<EMAIL>' senha = 'senha' #Configuracoes Email #Email apresentado para a vitima email_falso = '<EMAIL>' #Nome...
from odoo import api, fields, models class AccountBankStatementImportPayPalMapping(models.Model): _name = 'account.bank.statement.import.paypal.mapping' _description = 'Account Bank Statement Import PayPal Mapping' name = fields.Char( required=True, ) float_thousands_sep = fields.Selectio...
import simplegui import random #initialize global variables num_range = 100 num_of_guesses = 7 # helper function to start and restart the game def new_game(): global secret_number, num_of_guesses secret_number = random.randrange(num_range) print "NEW GAME" if num_range == 100: num_of_guesses =...
__author__ = "David Rusk <<EMAIL>>" try: import pyds9 as ds9 except: import ds9 ds9.DS9 = ds9.ds9 from .. import logger, config from ...fitsviewer.singletviewer import SingletViewer from ...fitsviewer.tripletviewer import TripletViewer class ImageViewManager(object): def __init__(self, mainframe, zoom=1...
# -*- coding:utf-8 -*- from flask_mongoengine import MongoEngine from flask_login import UserMixin from datetime import datetime db = MongoEngine() class User(UserMixin,db.Document): name = db.StringField(required=True, max_length=64) password = db.StringField(max_length=256) email = db.StringField(max_length=64) ...
#!/usr/bin/env python2 # vim: expandtab:tabstop=4:shiftwidth=4 ''' docker container DNS tester ''' # Adding the ignore because it does not like the naming of the script # to be different than the class name # pylint: disable=invalid-name import time import os from docker import AutoVersionClient from docker.err...
__all__ = ('WildcardMatcher', 'WildcardTrieMatcher') class _Node(dict): __slots__ = 'value', class WildcardTrieMatcher(object): def __init__(self): self._root = _Node() self._values = set() def __setitem__(self, key, value): node = self._root for sym in key.split('.'):...
import os import time import hmac import base64 import hashlib import logging from odoo.http import request from odoo.addons.muk_utils.tests import common _path = os.path.dirname(os.path.dirname(__file__)) _logger = logging.getLogger(__name__) class DownloadTestCase(common.HttpCase): def test_file_download...
import os from azure.cli.testsdk import (LiveScenarioTest, ResourceGroupPreparer, StorageAccountPreparer, JMESPathCheck, JMESPathCheckExists, NoneCheck, api_version_constraint) from azure.cli.core.profiles import ResourceType @api_version_constraint(ResourceType.MGMT_STORAGE, min_api='2...
"""4x5 character map. https://github.com/tompreston/4x5-Font http://clubweb.interbaun.com/~rc/Papers/microfont.pdf """ char_map = { '': [0x0, 0x0, 0x0, 0x0, 0x0], ' ': [0x0, 0x0, 0x0, 0x0, 0x0], '!': [0x4, 0x4, 0x4, 0x0, 0x4], '#': [0x6, 0xf, 0x6, 0xf, 0x6], '\'': [0x0, 0xa, 0x0, 0x0, 0x0], '%':...
''' A package of utilities for exporting NEURON models to NeuroML 2 & for analysing/comparing NEURON models to NeuroML versions Will use some some utilities from https://github.com/OpenSourceBrain/NEURONShowcase ''' from pyneuroml.pynml import validate_neuroml1 from pyneuroml.pynml import validate_neuroml2 from py...
from msrest.serialization import Model class OptionalClaims(Model): """Specifying the claims to be included in the token. :param id_token: Optional claims requested to be included in the id token. :type id_token: list[~azure.graphrbac.models.OptionalClaim] :param access_token: Optional claims request...
"""A representation of an Earth Engine image. See: https://sites.google.com/site/earthengineapidocs for more details. """ # Using lowercase function naming to match the JavaScript names. # pylint: disable=g-bad-name import apifunction import computedobject import data import ee_exception import ee_types import ele...
import json from django.contrib.auth.decorators import login_required from django.urls import reverse from django.http import HttpResponse, JsonResponse from django.shortcuts import render, Http404, HttpResponseRedirect, redirect from django.utils import timezone from django.contrib.contenttypes.models import ContentT...
from discord.ext.commands.errors import * def quoted_word(view): current = view.current if current is None: return None result = [current] while not view.eof: current = view.get() if not current: return ''.join(result) if current == '\\': next...
# Test the local one, not the installed one: import sys sys.path.insert(0, "..") import betools from betools import CmdLine # CmdLine appears to be global for all tests, # so you can't use the same letter flag throughout # the test suite (is this a py.test bug?) @CmdLine("n", "none") def test_noArgument(): """ ...
""" Test alias support. """ from servicetest import call_async, EventPattern from gabbletest import exec_test, make_result_iq, acknowledge_iq import constants as cs def test(q, bus, conn, stream): conn.Connect() _, event = q.expect_many( EventPattern('dbus-signal', signal='StatusChanged', ...
""" Tests for schema utilities """ from django.test import TestCase from mock import patch from opal.core import schemas from opal.tests.models import Colour, HatWearer, FamousLastWords colour_serialized = dict( name='colour', icon="fa fa-comments", display_name='Colour', single=False, advanced_se...
from django.contrib.contenttypes.models import ContentType def get_polymorphic_base_content_type(obj): """ Helper function to return the base polymorphic content type id. This should used with django-guardian and the GUARDIAN_GET_CONTENT_TYPE option. See the django-guardian documentation for more inf...
""" Problem Statement The running time of Quicksort will depend on how balanced the partitions are. If you are unlucky and select the greatest or the smallest element as the pivot, then each partition will separate only one element at a time, so the running time will be similar to Insertion Sort. However, Quicksort w...
from unittest import mock import yaml from neutronclient.common import exceptions from heat.common import exception from heat.common.i18n import _ from heat.common import template_format from heat.engine.resources.openstack.neutron.lbaas import l7rule from heat.tests import common from heat.tests.openstack.neutron im...
#============================================================================= # FILE: ghc.py #============================================================================= from .base import Base import deoplete.util import re class Source(Base): def __init__(self, vim): Base.__init__(self, vim) ...
from openerp.osv import osv, fields class Invoice(osv.Model): _inherit = 'account.invoice' _columns = { 'pricelist_id': fields.many2one('product.pricelist', string='Pricelist'), } class StockPicking(osv.Model): _inherit = 'stock.picking' def _invoice_hook(self, cr, uid, picking, invoic...
from __future__ import absolute_import from pychron.canvas.canvas2D.scene.extraction_line_scene import ExtractionLineScene from pychron.canvas.canvas2D.scene.primitives.dumper_primitives import Gate, Funnel from pychron.canvas.canvas2D.scene.primitives.rounded import RoundedRectangle KLASS_MAP = {'gate': Gate, 'funnel...
#!/usr/bin/env python from __future__ import division import tensorflow as tf import params_btn as params def weight_variable(shape): initial = tf.truncated_normal(shape, stddev=0.1) return tf.Variable(initial) def bias_variable(shape): initial = tf.constant(0.1, shape=shape) return tf.Variable(init...
import rospy from geometry_msgs.msg import Twist def timer_callback(event): pub.publish(twist_output) def simple_motion(twist, duration): global twist_output opposite_twist = Twist() opposite_twist.linear.x = -twist.linear.x opposite_twist.linear.y = -twist.linear.y opposite_twist.angular.z = -twist.angu...
''' Harsha Ashokan Copparam eval_agent.py The interface between the agent and the world generated. Tracks agent's position in the world. Gives him the percepts appropriate for each move. ''' import world_gen import agent_world_interface import agent #Defining a world to be used globally for function calls. en...
# stdlib from typing import Optional from typing import Union # third party from nacl.signing import SigningKey from nacl.signing import VerifyKey from typing_extensions import final # syft relative from ....logger import critical from ....logger import traceback_and_raise from ...common.message import SignedMessage ...
import datetime import subprocess from importlib import resources from pathlib import Path from . import migrations from .common import DBNAME, get_conn, run_sql """ Forward-only DB migration scheme held together by duct tape. - Uses `user_version` pragma to figure out what migrations are pending. - Migrations files...
#!/usr/bin/env python import argparse from arrangements import HopArch from algos import FireFlyGroup, TestFly, Flames from displays import arduino_based_displays import random class _DisplaysProbe(object): def __init__(self): available = {} try: from displays import graphics_based_disp...
"""Test logfiles with vibration output in cclib""" import os import unittest __filedir__ = os.path.realpath(os.path.dirname(__file__)) class GenericIRTest(unittest.TestCase): """Generic vibrational frequency unittest""" # Unit tests should normally give this value for the largest IR intensity....
from dwitter.models import Comment, Dweet from django.shortcuts import render from dwitter.permissions import IsAuthorOrReadOnly from dwitter.serializers import CommentSerializer, DweetSerializer from dwitter.serializers import UserSerializer from django.utils import timezone from django.contrib.auth.models import User...
from __future__ import absolute_import, division, print_function, \ with_statement import sys import os import logging import signal sys.path.insert(0, os.path.join(os.path.dirname(__file__), '../')) from shadowsocks import shell, daemon, eventloop, tcprelay, udprelay, \ asyncdns, manager def main(): sh...
from __future__ import unicode_literals import hashlib import re from datetime import datetime from random import random from botocore.exceptions import ParamValidationError from moto.core import BaseBackend, BaseModel, CloudFormationModel from moto.ec2 import ec2_backends from moto.ecr.exceptions import ImageNotFou...
# -*- coding: utf-8 -*- """ Example of calculation of fluid temperature profiles in a borehole with independent U-tubes. The fluid temperature profiles in a borehole with 4 independent U-tubes are calculated. The borehole has 4 U-tubes, each with different inlet fluid temperatures and different inlet f...
from django.contrib.admin.sites import site from django.core.urlresolvers import reverse from django.core.exceptions import ImproperlyConfigured from django.http import Http404 from django.views.generic.edit import CreateView from django.views.generic.base import View, TemplateView from jamsession.models import Sche...
# -*- coding: utf-8 -*- ''' Module for viewing and modifying sysctl parameters ''' import re # Import salt libs import salt.utils from salt.exceptions import CommandExecutionError # Define the module's virtual name __virtualname__ = 'sysctl' def __virtual__(): ''' Only run on NetBSD systems ''' retu...
"""Classifier registries.""" import os from flask.ext.registry import PkgResourcesDirDiscoveryRegistry, \ ModuleAutoDiscoveryRegistry, RegistryProxy from invenio.utils.datastructures import LazyDict classifierext = RegistryProxy( 'classifierext', ModuleAutoDiscoveryRegistry, 'classifierext' ) taxonomies_pro...
#! /usr/bin/env python """This module sets up the necessary database and tables in rethinkdb for stalkerd to operate""" import argparse import rethinkdb as r from rethinkdb.errors import ReqlDriverError import getpass def cliparse(): """sets up and parses the cli arguments""" parser = argparse.ArgumentParse...
""" Sample Template Component. Use this as the basis for your components! """ from Axon.Component import component, scheduler class CallbackStyleComponent(component): #Inboxes=["inbox","control"] List of inbox names if different #Outboxes=["outbox","signal"] List of outbox names if different #Usescomponents=[...
from __future__ import (absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement) import os import threading import six from pants.base.build_file_target_factory import BuildFileTargetFactory from pants.base.parse_context import ParseContext from ...
import math class Point(object): def __init__(self, x = None, y = None, tup = None): if tup is not None: self.x = tup[0] self.y = tup[1] else: self.x = x self.y = y def distance_to(self,other): return math.sqrt(math.pow(self.x - other.x,2)+ math.pow(self.y - other.y,2)) def angle_to(self,other):...
#!/usr/bin/env python # encoding: utf-8 import random import os import os.path import argparse import re import math import sys __LICENSE__ = """ Copyright (c) 2011 - 2017, Steven Tobin and Contributors. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitt...
# -*- coding: utf-8 -*- import requests import telebot from telebot import types from telebot import util logger = telebot.logger API_URL = "https://api.telegram.org/bot{0}/{1}" FILE_URL = "https://api.telegram.org/file/bot{0}/{1}" def _make_request(token, method_name, method='get', params=None, files=None, base_u...
from __future__ import (absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement) import os import shutil from pex.archiver import Archiver from pex.crawler import Crawler from pex.installer import EggInstaller from pex.interpreter import PythonIde...
#!/usr/bin/env python """Beaglebone Specialization Script Configures a flashed Beaglebone to be one of the six legs, three hips, or other computers. Usage: ./specializeBone.py [options] Options: -h, --help Show this help screen. --version Show the version. --leg=<leg> Indicat...
"""Getting graphs of NAV-collected data from Graphite""" import re from django.urls import reverse from django.utils import six from django.utils.six.moves.urllib.parse import urlencode TIMETICKS_IN_DAY = 100 * 3600 * 24 TARGET_TOKENS = re.compile(r'[\w\-*?]+|[(){}\[\]]|,|\.') def get_sensor_meta(metric_path): ...
from argparse import Namespace from pyplanet.contrib.command.exceptions import ( ParamValidateException, ParamParseException, ParamException, NotValidated, InvalidParamException) class ParameterParser: """ Parameter Parser. .. todo:: Write introduction + examples. """ def __init__(self, prog=None):...
from tkinter import * from StringData import * class App(Frame): def __init__(self, master): self.__round_num = 1 super().__init__(master) self.pack(padx=40, pady=20) self.create_widgets() def create_widgets(self): #self.entrys = [ [0 ]...