code
stringlengths
1
199k
"""Tests for QGIS functionality. .. note:: This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. """ from __future__ im...
''' Created on 17/12/2011 @author: nicolas ''' import urllib2 import re import xml.dom.minidom import os base = 'http://www.cuentalo.com.uy' url_sitemap = [base + '/contacto', base + '/pagina/terminos', base + '/pagina/que_es'] url_no_sitemap = [] f = file('/home/cuentalo/cuentalo.com.uy/src/Mondel/CuentaloBundle/Resou...
from popen2 import popen3 from lxml import etree class NvidiaStats(dict): """Get the stats of the available nvidia devices via the nvidia-smi tool. In [1]: import gpu_info_parser as gip In [2]: info = gip.NvidiaStats() In [3]: print info {'driver': '340.32', 'ngpus': 2, 'serials': ['03222110...
from __future__ import unicode_literals from django.core.urlresolvers import reverse_lazy from django.core.files.storage import default_storage from django.views.generic import DetailView from django.views.generic.edit import CreateView, UpdateView from django.core.exceptions import PermissionDenied from models import ...
import sqlite3 as lite def in_db(repo_uuid): con = lite.connect('classnotes.db') with con: cur = con.cursor() cur.execute("SELECT * FROM Keys WHERE Repo_UUID='{0}'".format(repo_uuid)) row = cur.fetchone() print row if row is None: return False else: ...
from flask import Flask, render_template, request, redirect import sqlite3 import os import json with open("config.json") as f: conf = json.load(f) app = Flask(__name__, static_url_path = "") app.debug = True def init_db(dbpath): conn = sqlite3.connect(dbpath) cur = conn.cursor() sql_files = [ "sql/crea...
import json import base64 import functools import asyncio from urllib import request as http DEFAULT_AUTH_HEADER = 'Authorization' ASYNC_FUNCNAME_MARKER = "_async" class ClientError(Exception): pass class Client: """ Kanboard API client Example: from kanboard import Client kb = Client(ur...
class Solution: # @param root, a tree node # @return an integer def maxPathSum(self, root): self.res = root.val if root else 0 self.dfs(root) return self.res def dfs(self, root): if root is None: return 0 l_max = max(0, self.dfs(root.left)) r_m...
__author__ = 'hmizumoto' from flask import Blueprint, request, abort from app.utils import prep_response, parse_request from app.models import DOMAIN from app import app from app.decoretor import authorize_required from logging import getLogger, StreamHandler, DEBUG logger = getLogger(__name__) handler = StreamHandler(...
from .serialization import mkdir from .arrays import set_device
import context, testutils, unittest from docxperiments import experiment, dirdiff from docxperiments import operator from docxperiments.pathutils import data_rel, PROJECT_DIR, PACKAGE_DIR, DATA_DIR class OperatorTest(unittest.TestCase): maxDiff = None def setUp(self): self.op = operator.Operator() d...
"""Compute minibatch blobs for training a Fast R-CNN network.""" import numpy as np import numpy.random as npr import cv2 from fast_rcnn.config import cfg from utils.blob import prep_im_for_blob, im_list_to_blob import ipdb def get_minibatch(roidb, num_classes): """Given a roidb, construct a minibatch sampled from ...
import ezdxf def write_dxf_file(filename): doc = ezdxf.new("R12") doc.header["$HANDLING"] = 0 msp = doc.modelspace() msp.add_line((0, 0), (1, 0)) doc.saveas(filename) def test_read_file_without_handles(tmpdir): filename = tmpdir.join("r12_without_handles.dxf") write_dxf_file(filename) do...
from starcluster.clustersetup import ClusterSetup from starcluster.logger import log class STARFUSIONInstaller(ClusterSetup): def run(self, nodes, master, user, user_shell, volumes): for node in nodes: log.info("Installing STAR-FUSION 0.3.1 on %s" % (node.alias)) node.ssh.execute('wget -c -P /opt/software/star...
""" Removes double occupancies (leaves the first location found) from a PDB file. usage: python pdb_delocc.py <pdb file> example: python pdb_delocc.py 1CTF.pdb Author: {0} ({1}) This program is part of the PDB tools distributed with HADDOCK or with the HADDOCK tutorial. The utilities in this package can be used to quic...
""" WSGI config for startertest project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/1.8/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTIN...
from .appdirs import AppDirs from .misc import format_name, strftime, iso_date_to_six_char
"""test the general module """ import sftoolbox def test_sftoolbox_module(): assert sftoolbox assert sftoolbox.__version__ assert sftoolbox.engine
import math import fvh import datetime from wand.image import Image def getSS(listOfDictionarysOfPoints): currentMax=(0,0) for eachDictionary in listOfDictionarysOfPoints: for eachpoint in range(len(eachDictionary)): point=eachDictionary[eachpoint] #print point if (point[0]>currentMax[0]): ...
import numpy as np import random import permutation_test.ap as ap from operator import mul from fractions import Fraction import functools from operator import itemgetter import collections from numpy.random import normal def permutationtest(data, ref_data, detailed=False, n_combinations_max=20000, verbose=True, n_bins...
from __future__ import absolute_import from .base import Base class List(Base): def run(self): import pip result = pip.main(['list'])
import random import time import requests from lxml import html from .exceptions import ServerIpBlacklisted, BadStatusCode, ProfileNotFound def to_requests_format(ip, port): """ Returns the proxy format for requests package """ return {'http': 'http://{}:{}'.format(ip, port), 'https': 'http://{}:{}'...
from django.db.models.signals import post_save from django.dispatch import receiver from ...cooggerapp.models import send_mail from ..models import ThreadedComments @receiver(post_save, sender=ThreadedComments) def when_create_comment(sender, instance, created, **kwargs): if created: obj = instance.get_top_...
__version__ = "1.2.1" class MQTTException(Exception): def __init__(self, *args, **kwargs): Exception.__init__(self, *args, **kwargs)
from room import Room r = Room() r.roomname = 'elevatorroof' r.exits = {'elevator': 'elevator'} r.roomdesc = """ Good God its dirty, some one left their tool box up here. """ r.looktargets = {'tool box': 'Tools for tooling\n\n', 'talktargets': 'figure=slm\n\n'}
import wx import psi from ..component import Component from ..map_grid import MapGrid from psi.euclid import Vector2 __all__ = ['BaseRobot', 'BaseGridMapper'] class BaseRobot(Component): def __init__(self): super(BaseRobot, self).__init__() self.pos = Vector2(0, 0) self.th = 0.0 self...
''' Spark-Training Enterance quizzes. ''' import unittest def reverse_string_a(s): return s[::-1] def reverse_string_b(s): return ''.join(reversed(s)) def reverse_sentence(sentence): return ' '.join(reversed(sentence.split())) def find_max(my_list): _max = 0 for num in my_list: _max = num if...
""" ZMQ example using python3's asyncio Ion should be started with the command line arguments: iond -testnet -daemon \ -zmqpubhashblock=tcp://127.0.0.1:12705 \ -zmqpubrawtx=tcp://127.0.0.1:12705 \ -zmqpubhashtx=tcp://127.0.0.1:12705 \ -zmqp...
from dataclasses import dataclass from threading import Event from pymuse.utils.stoppablequeue import StoppableQueue @dataclass class SignalData(): """ Dataclass for a signal data point. Event_marker attribute is optional """ time: float values: list event_marker: list = None class Signal(): ...
'''Converts a cURL command to code for Python Requests''' import curl_to_requests curl_cmd = '''curl 'https://github.com/mosesschwartz/curl_to_requests' \\ -H 'Accept-Encoding: gzip, deflate, sdch' \\ -H 'Accept-Language: en-US,en;q=0.8' \\ -H 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_4) App...
import glob, os from lib import config # config.py import lib.es as es from lib.read import readfile import web.util.tools as tools from web.modules.post.services import config def create_acl(host, index): # add acl_readonly field configuration doc = { "id": 'acl_readonly', "name": 'acl_readonly...
from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('inventory', '0013_auto_20160915_1055'), ] operations = [ migrations.AddField( model_name='item', name='barcode', fiel...
import io, math import numpy import pandas import sqlite3 import util.main as main def unpack_qc(value): 'unpack a qc result from the db' try: qc = numpy.load(io.BytesIO(value), allow_pickle=True) except: print('failed to unpack qc data - check db for missing entries.') qc = numpy.ze...
from PyQt4 import QtCore, QtGui try: _fromUtf8 = QtCore.QString.fromUtf8 except AttributeError: def _fromUtf8(s): return s try: _encoding = QtGui.QApplication.UnicodeUTF8 def _translate(context, text, disambig): return QtGui.QApplication.translate(context, text, disambig, _encoding) exce...
""" Created on Tue Apr 11 15:30:08 2017 @author: camacho """ import Gedi as gedi import RV_function;reload(RV_function);RVfunc=RV_function import numpy as np; #np.random.seed(12042017) import matplotlib.pylab as pl import astropy.table as Table pl.close() RV_spots_data=[] #to contain all data in the end rdb_data=Table....
import os class IdGen: def __init__(self, starting_id): self.current_id = starting_id - 1 def next(self): self.current_id += 1 return self.current_id def yes_no_input(yes_msg, no_msg): cmd = input('Are you sure? [Yes/no]: ') if cmd.lower() in ['y', 'yes']: print(yes_msg) ...
import asyncio from base import Event from .imessage import IMessage class Message(IMessage): def __init__(self, chatService): super(Message, self).__init__() self._chatService = chatService # IMessage # Parent @property def chatService(self): return self._chatService # Message def postEditMessage(self, newC...
from django.http import HttpResponse from django.http import HttpResponseRedirect from django.shortcuts import render from dashboard.models import Wish, WishForm from notifier.models import Notifier def index(request): wish_list = Wish.objects.order_by('-date')[:] if request.method == 'POST': # If the form has been s...
import os import sys import time import availablePorts import serial def parseMarkdown(text): BOLD_CODE = chr(2) # will be sent to arduino to toggle bold UNDERLINE_CODE = chr(3) # sent to arduino to toggle underline '''We are looking for __underline__ and **bold** text. Nothing fancy, and we are expe...
""" Truncate csv file to remove unwanted columns. Warning: DO NOT USE IF YOU ARE NOT SURE WHY THIS MUST BE RUN. CONTACT AUTHOR. """ import os, sys from pdb import set_trace import pandas as pd from glob2 import glob def change_class_to_bool(fname): old = pd.read_csv(fname) old.loc[old[old.columns[-1]] > 0, old....
from __future__ import unicode_literals from django.apps import AppConfig class ProgConfig(AppConfig): name = 'prog'
from __future__ import print_function import sys import os import datetime import string import ctypes from .. import toggles from .. import mbusTime from ... import mbus MAX_ARRAY_SIZE = 32 MBUS_LOW_TOO_LONG_CODE = 16 MBUS_TIMEOUT_CODE = 17 MBUS_END_MSG_CODE = 18 def nibbleSeq2Str(nibbleSeq): resultList = [] f...
import Adafruit_BBIO.PWM as PWM import time import logging PRED = "P8_19" PBLUE = "P8_13" PGREEN = "P9_14" class LEDDriver(object): def __init__(self,r=0,g=0,b=0): self.red = PWMchannel(PRED,r) self.green = PWMchannel(PGREEN,g) self.blue = PWMchannel(PBLUE,b) def setColor(self,r,g,b,duration=0): stepsPerSecon...
from statistics import mean def fpr_score(y_true, y_pred): true_preds = sum(y_pred) or 1 return sum(yp and not yt for yt, yp in zip(y_true, y_pred)) / true_preds def filter_rate_score(y_pred): return 1 - (sum(y_pred) / len(y_pred)) def round_or_none(value, ndigits): if value is None: return None...
import win32gui from urllib.request import urlopen, urlretrieve from xml.dom import minidom from PIL import Image import os if __name__=="__main__": #Variables: saveDir = "C:\\BingWallPaper\\" if (not os.path.exists(saveDir)): os.mkdir(saveDir) i = 0 while i<1: try: usock...
import io import os import re import sys import optparse import platform import builtins class context: indent = '' srcdir = '' dstdir = '' buffer = None first = True variables = dict() colour_log = platform.system() != 'Windows' debug = False def parse_options...
import json import re from xmr.util import * def parse_entity_file(entities_file): f = open(entities_file, 'r') file_data = f.read() f.close() # Turn it into JSON file_data = re.sub(r'(".*") (".*")', r'\1: \2,', file_data) file_data = re.sub(r'(".*": ".*"),\n}', r'\1\n},', file_data) file_da...
from david.ext.admin import ModelAdmin from david.ext.babel import lazy_gettext as _ from .model import Artist class ArtistAdmin(ModelAdmin): column_labels = dict( name=_('Name'), id=_('ID'), uid=_('Slug'), summary=_('Short bio'), desc=_('Detail'), ...
'''display an image using opengl''' import sys import PySide from PySide.QtGui import * from PySide.QtCore import * from PySide.QtOpenGL import * from OpenGL.GL import * from OpenGL.GL import shaders import numpy as np from PIL import Image def shaderFromFile(shaderType, shaderFile): '''create shader from file''' ...
from data import JointStratifiedMNIST from training import Results from results import image_plot from runjoint import models experiment_name = "halfmnist" train_steps = 150000 save_steps = 30000 data = JointStratifiedMNIST(1000) tracker = Results.load(experiment_name) syntheses = ['reconstruct']#, 'sample'] for i in r...
from .base import BaseResult class StartUploadResult(BaseResult): @property def upload_id(self): return self._result['uploadID']
import _plotly_utils.basevalidators class TickvalssrcValidator(_plotly_utils.basevalidators.SrcValidator): def __init__( self, plotly_name="tickvalssrc", parent_name="layout.smith.realaxis", **kwargs ): super(TickvalssrcValidator, self).__init__( plotly_name=plotly_name, ...
import uuid from django.contrib import admin from django.contrib.contenttypes.models import ContentType from django.core.urlresolvers import reverse from django.http import HttpResponseRedirect from django.utils.translation import ugettext_lazy as _ def export_selected_objects(modeladmin, request, queryset): select...
from test_framework.test_framework import KoreTestFramework from test_framework.util import * class RawTransactionsTest(KoreTestFramework): def setup_chain(self): print(("Initializing test directory "+self.options.tmpdir)) initialize_chain_clean(self.options.tmpdir, 4) def setup_network(self, sp...
import json import time from collections import OrderedDict import etcd from etcd import EtcdKeyNotFound ETCD_CLIENT = None BASE_DIR = '/cowry' CONFIG_DIR = '/'.join((BASE_DIR, 'config')) + '/' WORKER_DIR = '/'.join((BASE_DIR, 'worker')) + '/' def etcd_client(): global ETCD_CLIENT if not ETCD_CLIENT: ET...
import sys import os import unittest import logging import inspect if __name__ == "__main__": jasyroot = os.path.normpath(os.path.join(os.path.abspath(sys.argv[0]), os.pardir, os.pardir, os.pardir, os.pardir)) sys.path.insert(0, jasyroot) print("Running from %s..." % jasyroot) import jasy.style.Engine as En...
from single import SinglePaymentProcessor from future import FuturePaymentProcessor
""" This module gathers tree-based methods, including decision, regression and randomized trees. Single and multi-output problems are both handled. """ from __future__ import division import numbers from abc import ABCMeta from abc import abstractmethod from math import ceil import numpy as np from scipy.sparse import ...
__author__ = 'Lstevens' import os import errno import re import argparse import textwrap from PIL import ImageFont from PIL import Image from PIL import ImageDraw from xlrd import open_workbook """ Creates image files with xlsform question text. Run on command line with "-f" parameter which is path to xlsform file. Ima...
import logging import sys logging.basicConfig(stream=sys.stdout, level=logging.INFO) from zabbix.api import ZabbixAPI if len(sys.argv)<5: print("Expecting 5 arguments, only got {}".format( len(sys.argv) )) print "USAGE: zabbixURL user pass host newDescrip" print "EXAMPLE: http://127.0.0.1/zabbix myid P4ssword myH...
import six from django.core.exceptions import PermissionDenied from django.http import HttpResponseForbidden from django.http.response import HttpResponse, HttpResponseBadRequest, HttpResponseNotFound, HttpResponseRedirectBase from django.shortcuts import redirect from django.views import View class ExceptionResponse(E...
import sqlite3 import readData def insertHighscore(ident, initials, score, time): # Only inserts into DB if initials are 3 characters if(len(initials) == 3): # Make a connection conn = sqlite3.connect('highscore.db') c = conn.cursor() # Insert into DB info = (ident, initials, score, time) c.execute("INSER...
from celery import Celery import time from random import randrange from redlock import RedLock import uuid from api.python.locks import ExecutionStatusLock, SharedWaitResource from tornado.options import options import pymongo app = Celery('proj', broker='amqp://localhost//', backend='redis://localhost') import config ...
from django.conf.urls import patterns, include, url from django.contrib import admin from django_ladon import urls as ladon_urls urlpatterns = patterns('', # Examples: # url(r'^$', 'example.views.home', name='home'), # url(r'^blog/', include('blog.urls')), url(r'^api', include(ladon_urls)), url(r'^a...
"""Utility functions for fmrest""" from typing import List, Dict, Any, Iterator import requests from .exceptions import RequestException from .const import TIMEOUT def request(*args, **kwargs) -> requests.Response: """Wrapper around requests library request call""" try: return requests.request(*args, ti...
from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar, Union import warnings from azure.core.async_paging import AsyncItemPaged, AsyncList from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error from azure.core.pip...
import sys, os import types from twisted.trial import unittest from twisted.python import rebuild import crash_test_dummy f = crash_test_dummy.foo class Foo: pass class Bar(Foo): pass class Baz(object): pass class Buz(Bar, Baz): pass class HashRaisesRuntimeError: """ Things that don't hash (raise an Exception) ...
import matplotlib.pyplot as plt import matplotlib.dates as mdates import pandas as pd import numpy as np import pandas.io.data as web from pandas.stats.api import ols import pprint import statsmodels.tsa.stattools as ts import datetime inst_x = raw_input("Enter X ticker symbol: ") inst_y = raw_input("Enter Y ticker sym...
import cv2 import os import sys sys.path.append("/home/syc/py-faster-rcnn/caffe-fast-rcnn/python") import caffe import numpy as np import random import time from math import * import dproc from utils import * video_dir = '/media/syc/My Passport/_dataset/tracking2013/' video_name = "Shaking/img" video_transpose = False ...
"""Implement a graph with weighted edges.""" class Graph(object): """Create Graph class.""" def __init__(self): """Initialization of node class.""" self.nodes = dict() def add_node(self, val): """Create node with value and all to all nodes list.""" if val in self.nodes: ...
from toontown.toonbase.ToontownBattleGlobals import * import types from direct.fsm import StateData from direct.fsm import ClassicFSM, State from direct.fsm import State import TownBattleAttackPanel import TownBattleWaitPanel import TownBattleChooseAvatarPanel import TownBattleSOSPanel import TownBattleSOSPetSearchPane...
from django.urls import path from . import api_views urlpatterns = [ path('spaces/', api_views.ParkingSpaceList.as_view(), name='parkingspace-list'), path('spaces/<int:pk>/', api_views.ParkingSpaceDetail.as_view(), name='parkingspace-detail'), path('spaces/<int:pk>/availability/', api_views.ParkingSpaceAvai...
try: frozenset except NameError: # Import from the sets module for python 2.3 from sets import ImmutableSet as frozenset try: # use functools.reduce to avoid DeprecationWarning with -3 from functools import reduce except ImportError: pass import gettext _ = gettext.gettext from html5lib.constant...
import os from molecule import config from molecule import interpolation from molecule import util def from_yaml(data): """ Interpolate the provided data and return a dict. Currently, this is used to reinterpolate the `molecule.yml` inside an Ansible playbook. If there were any interpolation errors, th...
"""Functions related to coordinate systems and transformations. This module complements :py:mod:`astropy.coordinates`. """ from math import sin, cos, sqrt import numpy as np import astropy.units as u from astropy.coordinates import get_body_barycentric_posvel, CartesianRepresentation, CartesianDifferential from poliast...
__author__ = 'kono' import warnings warnings.warn('\n\n\n**** data.util_network will be deprecated in the next py2cytoscape release. ****\n\n\n') class NetworkUtil(object): @staticmethod def name2suid(network, obj_type='node'): if obj_type is 'node': table = network.get_node_table() ...
__version__ = "0.0.1" import sys def main(): print("Executing wesovilabs_tensorflow_samples version %s." % __version__) print("List of argument strings: %s" % sys.argv[1:])
from rest_framework import generics from simpleTODO.models import Todo from simpleTODO.serializers import TodoSerializer class TodoList(generics.ListCreateAPIView): queryset = Todo.objects.all() serializer_class = TodoSerializer class TodoDetails(generics.RetrieveUpdateDestroyAPIView): queryset = Todo.objec...
from django.conf import settings from pprint import pformat def demo_middleware(get_response): results = [] DEMO = getattr(settings, 'DEMO', {}) def middleware(request): fake_datetime = DEMO.get('fake_datetime') if fake_datetime: pass if DEMO.get('dump_post_data'): ...
import necrobot.exception from necrobot.botbase.commandtype import CommandType from necrobot.league import leaguestats from necrobot.league.leaguemgr import LeagueMgr from necrobot.user import userlib from necrobot.util import strutil class LeagueFastest(CommandType): def __init__(self, bot_channel): Comman...
import numpy as np import csv import matplotlib.pyplot as plt import nltk from nltk.stem.porter import * import string from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.naive_bayes import BernoulliNB from sklearn.ensemble import RandomForestClassifier from sklearn.linear_model import LogisticRegr...
from django.conf.urls import url, include from django.conf import settings from django.contrib import admin from core.views import autocomplete_view, student_detail from index_view import HomePageView urlpatterns = [ url(r'^admin/doc/', include('django.contrib.admindocs.urls')), url(r'^admin/', include(admin.si...
""" Gauged - https://github.com/chriso/gauged Copyright 2014 (c) Chris O'Hara <cohara87@gmail.com> """ from random import random from math import floor, ceil from time import time from calendar import timegm from datetime import datetime, timedelta from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter from...
"""Test account RPCs. RPCs tested are: - getaccountaddress - getaddressesbyaccount - listaddressgroupings - setaccount - sendfrom (with account arguments) - move (with account arguments) """ from test_framework.test_framework import PlanbcoinTestFramework from test_framework.util import assert_e...
import warnings import logging from six import text_type import six from collections import OrderedDict try: import json except ImportError: import simplejson as json import requests from requests.auth import HTTPBasicAuth, AuthBase from requests_oauthlib import OAuth1 import mwclient.errors as errors import mw...
''' To run this file: python stutter.py stutter_code.stt > c_code.c ''' import itertools import re import string def is_integer(s_expression): return isinstance(s_expression, int) \ and not s_expression is True \ and not s_expression is False ESCAPE_CHARACTERS = { '\\' : '\\', 'n' ...
"""Send a reply from the proxy without sending any data to the remote server.""" from mitmproxy import http def request(flow: http.HTTPFlow) -> None: if flow.request.pretty_url == "http://example.com/path": flow.response = http.HTTPResponse.make( 200, # (optional) status code b"Hell...
<<<<<<< HEAD <<<<<<< HEAD """ This module tries to retrieve as much platform-identifying data as possible. It makes this information available via function APIs. If called from the command line, it prints the platform information concatenated as single string to stdout. The output format is useable as p...
from __future__ import print_function __author__ = """Alex "O." Holcombe, Wei-Ying Chen""" ## double-quotes will be silently removed, single quotes will be left, eg, O'Connor from psychopy import * import psychopy.info from psychopy import sound, monitors, logging import numpy as np import itertools #to calculate all s...
""" FILE: make.py AUTHOR: Cody Precord @summary: Lexer configuration module for Makefiles. """ __author__ = "Cody Precord <cprecord@editra.org>" __svnid__ = "$Id: _make.py 68798 2011-08-20 17:17:05Z CJP $" __revision__ = "$Revision: 68798 $" import wx.stc as stc import syndata SYNTAX_ITEMS = [ (stc.STC_MAKE_DEFAULT, ...
"""State variables for analysis solutions such as powerflow. """ from CIM15.IEC61970.StateVariables.SvVoltage import SvVoltage from CIM15.IEC61970.StateVariables.SvShortCircuit import SvShortCircuit from CIM15.IEC61970.StateVariables.SvShuntCompensatorSections import SvShuntCompensatorSections from CIM15.IEC61970.State...
"""Export the files needed by the KIM api.""" import os import glob import shutil import string from copy import copy import subprocess if not hasattr(subprocess, 'check_output'): # Pre-2.7 hack print "WARNING: Fixing pre Python 2.7 compatibility" from subprocess_py27 import check_output subprocess.chec...
import os from os import path from lxml.etree import parse, XSLT __all__ = ['STYLESHEETS'] xslt_dir = path.dirname(__file__) xslt_files = [ filename for filename in os.listdir(xslt_dir) if filename.endswith('.xsl') or filename.endswith('.xslt') ] class StylesheetDict(dict): def __init__(self): ...
import fsc from copy import copy from pdb import set_trace from pprint import pprint def determineRelevantSubwordLenghts(n, state): """ This function register states to their possible relevant subword lenghts. (See Definition 4.0.22 for "relevant subword") """ # Find the right-most position. The index of th...
from collections import Mapping def shorten(s, width=80): """ >>> shorten('a very very very very long sentence', 20) 'a very very ..(23)..' """ if not isinstance(s, str): s = str(s) length = len(s) if length < width: return s cut_length = length - width + 6 x = len(st...
from os import environ from dotenv import load_dotenv, find_dotenv load_dotenv(find_dotenv()) consumer_key = environ.get('CONSUMER_KEY') consumer_secret = environ.get('CONSUMER_SECRET') access_token = environ.get('ACCESS_TOKEN') access_secret = environ.get('ACCESS_SECRET') mysql_host = environ.get('MYSQL_HOST') mysql_d...
import scipy import VLTTools datadir = '/diska/data/SPARTA/2015-06-01/temp/' ciao = VLTTools.VLTConnection(simulate=False, datapath=datadir) ciao.measureBackground(9)
from django.db import models from django import forms from emencia.django.layout.designer.widgets import LayoutDesignerWidget class LayoutDesignerFormField(forms.fields.Field): widget = LayoutDesignerWidget def __init__(self, *args, **kwargs): kwargs.update({'widget': LayoutDesignerWidget}) supe...
BOT_NAME = 'www_123seguro_com' SPIDER_MODULES = ['www_123seguro_com.spiders'] NEWSPIDER_MODULE = 'www_123seguro_com.spiders' CONCURRENT_REQUESTS_PER_DOMAIN = 1 DOWNLOAD_TIMEOUT = 60
import pytest def test_default(): assert True