code
stringlengths
1
199k
import unittest from app.md5py import MD5 class TddInPythonExample(unittest.TestCase): def test_object_program(self): m = MD5() m.update("1234") hexdigest = m.hexdigest() self.assertEqual("81dc9bdb52d04dc20036dbd8313ed055", hexdigest) if __name__ == '__main__': unittest.main()
from django.db.models import Q from django.forms.fields import CharField, MultiValueField from django.forms.widgets import MultiWidget, TextInput from django.utils import timezone from django.utils.translation import ugettext_lazy as _ from django_filters.filters import DateFilter, MethodFilter, ModelChoiceFilter from ...
import re try: from setuptools import setup, find_packages except ImportError: from ez_setup import use_setuptools use_setuptools() from setuptools import setup, find_packages PYPI_RST_FILTERS = ( # Replace code-blocks (r'\.\.\s? code-block::\s*(\w|\+)+', '::'), # Replace image (r'\.\.\s...
T = input() if T%2==0: print T/2 else: print ((T-1)/2)-T
""" distutils setup script for distributing Timbl Tools """ __authors__ = "Erwin Marsi <e.marsi@gmail.com>" from distutils.core import setup from glob import glob from os import walk, path, remove from os.path import basename, isdir, join, exists from shutil import rmtree if exists('MANIFEST'): remove('MANIFEST') if ex...
from setuptools import setup, find_packages import sys, os version = '1.3' long_description = """The raisin.restyler package is a part of Raisin, the web application used for publishing the summary statistics of Grape, a pipeline used for processing and analyzing RNA-Seq data.""" setup(name='raisin.restyler', ver...
import sys from functools import partial from uuid import UUID from hashlib import sha1 from os import path, listdir from zipfile import ZipFile from subprocess import Popen, TimeoutExpired import nacl.utils import nacl.secret def isValidUUID(uid): """ Validate UUID @param uid: UUID value to be verfied, can...
''' ' configurationGui.py ' Author: Iker Pedrosa ' ' License: ' This file is part of orderedFileCopy. ' ' orderedFileCopy 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 the Licens...
class Shape: def __init__(self): return def draw(self): return class Circle(Shape): def draw(self): print("Inside Circle::draw() method.") class Rectangle(Shape): def draw(self): print("Inside Rectangle::draw() method.") class Square(Shape): def draw(self): pr...
import mutagen import os import re import sys from optparse import OptionParser music_file_exts = ['.mp3', '.wav', '.ogg'] seconds_re = re.compile('(\d+)(\.\d+)? seconds') def main(argv): (options, args) = build_parser().parse_args(argv) validate_options(options) print('playlist(s) will be written to ', opt...
"""Configuration for a load testing using Locust. To start load testing, run `make server` and `make test-load`. """ import random from json.decoder import JSONDecodeError from django.urls import reverse from locust import HttpLocust, TaskSet, task class SolvingTaskBehavior(TaskSet): """Describes interaction of a s...
""" Module implementing templates for the documentation generator (lists style). """ from __future__ import unicode_literals headerTemplate = \ '''<!DOCTYPE html> <html><head> <title>{{Title}}</title> <meta charset="UTF-8"> </head> <body style="background-color:{BodyBgColor};color:{BodyColor}">''' footerTemplate = ''' ...
from flask import render_template from app import app, db, models import json @app.route('/') @app.route('/index') def index(): # obtain today's words # words = models.Words.query.all() # words = list((str(word[0]), word[1]) for word in db.session.query(models.Words, db.func.count(models.Words.id).label("to...
''' Copyright 2015 Travel Modelling Group, Department of Civil Engineering, University of Toronto This file is part of the TMG Toolbox. The TMG Toolbox 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 Found...
""" Compatibility module. This module contains duplicated code from Python itself or 3rd party extensions, which may be included for the following reasons: * compatibility * we may only need a small subset of the copied library/module """ import _inspect import py3k from _inspect import getargspec, formatargspec fr...
import sys from tqdm import tqdm from common.helpers.output import log from scenario import Scenario, SwitchAttr, Flag class GolangDepsUpdate(Scenario): ''' update dependencies of Golang projects packaged in Fedora ''' max_depth = SwitchAttr("--max-depth", int, default=None, help="...
""" matstat docstrings """
from math import sqrt from bisect import bisect_left import scipy.stats as st maxlong = 9223372036854775807 class RunningStat(object): '''Gather single-pass statistical data from an iterable''' __slots__ = ('count', 'moments', 'min', 'max') def __init__(object, moments=1, buckets=1, sorted=False): s...
import sys import optparse from ovirtsdk.xml import params description = """ RHEV-nagios-table-host-mem output is a script for querying RHEVM via API to get host status It's goal is to output a table of host/vm status for simple monitoring via external utilities """ p = optparse.OptionParser("rhev-nagios-table-host-me...
def get_perm_argparser(self, args): args = args.split(" ") if args[0] == "nick": self.conman.gen_send("Permission level for %s: %s" % (args[1], self.permsman.get_nick_perms(args[1]))) elif args[0] == "cmd": if args[1].startswith("."): args[1] = args[1][1:] self.conman.gen...
from .base import BaseInterface import eventlet from watchdog.observers import Observer from watchdog.events import PatternMatchingEventHandler from flask import Flask, render_template, session, request, send_from_directory from flask_socketio import SocketIO, emit, join_room, leave_room, close_room, rooms, disconnect ...
import re from pyquery import PyQuery from novel import serial, utils BASE_URL = 'http://www.sto.cc/{}-1/' PAGE_URL = 'http://www.sto.cc/{}-{}/' class StoTool(utils.Tool): def __init__(self): super().__init__() word_list = ( 's思s兔s網s文s檔s下s載s與s在s線s閱s讀s', 's本s作s品s由s思s兔s網s提s供s下s...
""" Convert wiggle data to a binned array. This assumes the input data is on a single chromosome and does no sanity checks! usage: %prog score_file out_file < wiggle_data -c, --comp=type: compression type (none, zlib, lzo) """ from __future__ import division import sys import psyco_full import bx.wiggle from bx.bin...
from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('problems', '0018_origintag_helptexts...
from __future__ import unicode_literals import DjangoUeditor.models from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('blogadmin', '0006_auto_20170827_1142'), ] operations = [ migrations.CreateModel( name='BookReview', f...
from twisted.trial import unittest from rtpmidi.engines.midi.recovery_journal_chapters import * class TestNote(unittest.TestCase): def setUp(self): self.note = Note() def test_note_on(self): #simple note_to_test = self.note.note_on(100, 90) #Testing type assert(type(note_...
""" user data tab """ try: from taurus.external.qt import Qt except Exception: from taurus.qt import Qt from .EdListDlg import EdListWg import logging logger = logging.getLogger(__name__) class Data(Qt.QObject): """ User data tab widget """ #: (:class:`taurus.qt.Qt.pyqtSignal`) dirty signal dirt...
import json import sys import os import urllib import logging import re import time import errno import uuid import datetime from bs4 import BeautifulSoup import geoserver import httplib2 from urlparse import urlparse from urlparse import urlsplit from threading import local from collections import namedtuple from iter...
import os yt=https://youtu.be/ mp3list = '/home/steakwipe/git/ytdl-namer' #i'd like this to be a runtime option later def mp3gen(): for root, dirs, files in os.walk('.'): for filename in files: if os.path.splitext(filename)[1] == ".mp3": yield os.path.join(root, filename) for mp3...
import gzip import os import pickle import matplotlib import matplotlib.pyplot as plt import numpy as np matplotlib.use('TKagg') def show_attention(): # Load attentions print('Loading attentions to pickle file') with gzip.open( os.path.join('training_results', 'torch_train', 'attentions.pkl.gz'), 'r')...
import datetime from kivy.app import App from kivy.uix.widget import Widget import random from kivy.clock import Clock from kivy.properties import StringProperty, NumericProperty from webScrape import webScraper class MirrorWindow(Widget): dayPrint = ['Sön', 'Mån', 'Tis', 'Ons', 'Tors', 'Fre', 'Lör'] secondsAni...
from unittest import TestCase from gnomon import MagneticField class MockG4ThreeVector(): x = 0 y = 0 z = 0 class TestWandsToroidField(TestCase): def setUp(self): self.field_minus = MagneticField.WandsToroidField('-') self.field_plus = MagneticField.WandsToroidField('+') self.fie...
import errno import logging import os import re from django.conf import settings from pootle.core.log import STORE_RESURRECTED, store_log from pootle.core.utils.timezone import datetime_min from pootle_app.models.directory import Directory from pootle_language.models import Language from pootle_store.models import Stor...
import hid from typing import TYPE_CHECKING, Dict, Tuple, Optional, List, Any, Callable from electrum_grs import bip32, constants from electrum_grs.i18n import _ from electrum_grs.keystore import Hardware_KeyStore from electrum_grs.transaction import PartialTransaction from electrum_grs.wallet import Standard_Wallet, M...
""" Parent classes for all parser classes """ __author__ = "Felix Simkovic" __date__ = "04 Oct 2016" __version__ = "0.1" import abc ABC = abc.ABCMeta("ABC", (object,), {}) from conkit.core.contact import Contact from conkit.core.contactmap import ContactMap from conkit.core.contactfile import ContactFile from conkit.co...
import os import sys import random import time import json import wikiquote import tuitear from threading import Thread CONGIG_JSON = 'bots.json' INTERVALO = 1 stop = False def start_bot(bot): """ Hilo que inicia el bot pasado como argumento (diccionario) """ citas = [] for pagina in bot['paginas']: ...
'''This is a testcase for the SmartOS datasource. It replicates a serial console and acts like the SmartOS console does in order to validate return responses. ''' from __future__ import print_function from binascii import crc32 import json import multiprocessing import os import os.path import re import signal import s...
import os import logging import tornado.options as opt from motherbrain.base import conf from motherbrain.base.conf import get_config SITE_CONF = conf.site_conf(os.getcwd()) DATADIR = SITE_CONF.get('env.motherbrain_data', '/tmp') API_URL = SITE_CONF.get('env.api_url') WEBCLIENT_URL = SITE_CONF.get('env.webclient_url') ...
import imp from flask.config import ConfigAttribute, Config as ConfigBase # noqa class Config(ConfigBase): "Configuration without the root_path" def __init__(self, defaults=None): dict.__init__(self, defaults or {}) def from_pyfile(self, filename): """ Updates the values in the conf...
""" Here, we need some documentation... """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import sys import os import types import threading import time import six from DIRAC import gLogger from DIRAC.Core.Utilities.DIRACSingleton import DIRACSingleton @six...
import sys import os import logging import threading try: # first we try system wide import treewatcher except ImportError: # if it fails, we try it from the project source directory sys.path.insert(0, os.path.join(os.path.dirname(__file__), os.path.pardir)) import treewatcher from treewatcher impor...
import sys import os import argparse import zipfile import tarfile def make_zipfile(outname, filenames, prefix): with zipfile.ZipFile(outname, "w", zipfile.ZIP_DEFLATED) as z: for filename in filenames: z.write(filename, prefix+filename) def make_tarfile(outname, filenames, prefix, mode="w"): ...
from upqjob import UpqJob from upqdb import UpqDB from time import time import os import shutil import requests class Download(UpqJob): """ "download url:$url" """ def run(self): url=self.jobdata['url'] filename=os.path.basename(url) tmpfile=os.path.join(self.getcfg('temppath', '/tmp'), filename) self.jobd...
from bdchecker.api import NewDatabaseTaskChecker from bdcheckerapp.autograding.zaj5.unit5.utils import Zaj5TaskChecker, UserList class TaskChecker(NewDatabaseTaskChecker): display_stdout = True class TestSuite(Zaj5TaskChecker): def test_has_procedure(self): self.assert_has_procedure("add_use...
import os import requests canary = 'mwtask111' serverlist = ['mw101', 'mw102', 'mw111', 'mw112', 'mw121', 'mw122'] def check_up(server: str) -> bool: headers = {'X-Miraheze-Debug': f'{server}.miraheze.org'} req = requests.get('https://meta.miraheze.org/w/api.php?action=query&meta=siteinfo&formatversion=2&format...
import gettext import os def get_parent_dir(filepath, level=1): '''Get parent dir.''' parent_dir = os.path.realpath(filepath) while(level > 0): parent_dir = os.path.dirname(parent_dir) level -= 1 return parent_dir LOCALE_DIR=os.path.join(get_parent_dir(__file__, 2), "locale") if not os.p...
"""Module for calling Artist related last.fm web services API methods""" __author__ = "Abhinav Sarkar <abhinav@abhinavsarkar.net>" __version__ = "0.2" __license__ = "GNU Lesser General Public License" __package__ = "lastfm" from lastfm.base import LastfmBase from lastfm.mixin import mixin from lastfm.decorators import ...
__author__ = 'shahbaz' import sys from functools import wraps from logging import StreamHandler from bitstring import BitArray def singleton(f): """ :param f: :return: """ return f() def cached(f): """ :param f: :return: """ @wraps(f) def wrapper(*args): """ :...
import sys import os from PyQt5 import QtCore, QtWidgets, QtGui, QtMultimedia from PyQt5 import QtNetwork from irish_dictionary import irish_dictionary, gaeilge_gaeilge from audio_grabber import entry_search, related_matches class Text(QtWidgets.QWidget): """ This class creates the text widget""" def __init__(s...
from HowOldWebsite.estimators.estimator_sex import EstimatorSex from HowOldWebsite.models import RecordSex __author__ = 'Hao Yu' def sex_estimate(database_face_array, feature_jar): success = False database_record = None try: n_faces = len(database_face_array) result_estimated = __do_estimate...
from FaustBot.Communication import Connection from FaustBot.Model.RemoteUser import RemoteUser from FaustBot.Modules.MagicNumberObserverPrototype import MagicNumberObserverPrototype from FaustBot.Modules.ModuleType import ModuleType from FaustBot.Modules.PingObserverPrototype import PingObserverPrototype from FaustBot....
__all__ = ['pleth_analysis', 'ekg_analysis']
import numpy as np from nose.tools import assert_raises from horton import * def test_typecheck(): m = IOData(coordinates=np.array([[1, 2, 3], [2, 3, 1]])) assert issubclass(m.coordinates.dtype.type, float) assert not hasattr(m, 'numbers') m = IOData(numbers=np.array([2, 3]), coordinates=np.array([[1, 2...
from pyrocko import pz, io, trace from pyrocko.example import get_example_data get_example_data('STS2-Generic.polezero.txt') get_example_data('test.mseed') zeros, poles, constant = pz.read_sac_zpk('STS2-Generic.polezero.txt') zeros.append(0.0j) rest_sts2 = trace.PoleZeroResponse( zeros=zeros, poles=poles, c...
from setup import ExtensionInstaller def loader(): return ProcessMonitorInstaller() class ProcessMonitorInstaller(ExtensionInstaller): def __init__(self): super(ProcessMonitorInstaller, self).__init__( version="0.2", name='pmon', description='Collect and display proce...
from distutils.core import setup import py2exe import os, sys from glob import glob import PyQt5 data_files=[('',['C:/Python34/DLLs/sqlite3.dll','C:/Python34/Lib/site-packages/PyQt5/icuuc53.dll','C:/Python34/Lib/site-packages/PyQt5/icudt53.dll','C:/Python34/Lib/site-packages/PyQt5/icuin53.dll','C:/Python34/Lib/site-pac...
from django.core.cache import cache from django.conf import settings from django.template.loader import render_to_string from tendenci.apps.navs.cache import NAV_PRE_KEY def cache_nav(nav, show_title=False): """ Caches a nav's rendered html code """ keys = [settings.CACHE_PRE_KEY, NAV_PRE_KEY, str(nav.i...
from Estructura import espaceado class Arbol_Sintactico_Abstracto: def __init__(self,alcance,hijos): self.hijos = hijos self.alcance = alcance self.cont = 1 def imprimir(self,tabulacion): if (len(self.hijos) > 1): print tabulacion + "SECUENCIA" for hijo in self.hijos: hijo.nivel = 1 hijo.imprimir(e...
from __future__ import with_statement import datetime import os import sys import re import urllib2 import copy import itertools import operator import collections import sickbeard from sickbeard import helpers, classes, logger, db from sickbeard.common import Quality, MULTI_EP_RESULT, SEASON_RESULT#, SEED_POLICY_TIME,...
""" Functional tests of the RabbitMQ Workers """ import mock import json import unittest import ADSDeploy.app as app from ADSDeploy.pipeline.workers import IntegrationTestWorker, \ DatabaseWriterWorker from ADSDeploy.webapp.views import MiniRabbit from ADSDeploy.models import Base, Deployment RABBITMQ_URL = 'amqp:/...
from __future__ import unicode_literals import datetime from django.db import models from django.utils import timezone from django.utils.encoding import python_2_unicode_compatible @python_2_unicode_compatible # only if you need to support Python 2 class Question(models.Model): question_text = models.CharField(max...
class Solution: # @param root, a tree link node # @return nothing def connect(self, root): def find_next(parent, child): parent = parent.next while parent: if parent.left: child.next = parent.left return ...
x0 = 1.0 y0 = 0.1 b = 1.0 p = 1.0 r = 1.0 d = 1.0 T = 30 dt = 0.01 noise = 0.1 import modex log = modex.log() import random t=0 x=x0 y=y0 while t<T: f = b - p*y + random.gauss(0, noise) g = r*x - d + random.gauss(0, noise) x += x*f*dt y += y*g*dt if x<0: x = 0 if y<0: y = 0 t+=dt log.tim...
class Word: def __init__(self, data, index): self.data = data self.index = index def printAnagrams(arr): dupArray = [] size = len(arr) for i in range(size): dupArray.append(Word(arr[i], i)) for i in range(size): dupArray[i].data = ''.join(sorted(dupArray[i].data)) dupArray = sorted(dupArray, key=lambda x:...
from optparse import make_option from optparse import OptionParser import logging import contextlib import datetime from django.core.management.base import BaseCommand from django.conf import settings import dateutil import netCDF4 from lizard_neerslagradar import netcdf logger = logger = logging.getLogger(__name__) cl...
class DrawingDimensioningWorkbench (Workbench): # Icon generated using by converting linearDimension.svg to xpm format using Gimp Icon = ''' /* XPM */ static char * linearDimension_xpm[] = { "32 32 10 1", " c None", ". c #000000", "+ c #0008FF", "@ c #0009FF", "# c #000AFF", "$ c ...
import os, shutil, xbmc, xbmcgui pDialog = xbmcgui.DialogProgress() dialog = xbmcgui.Dialog() Game_Directories = [ "E:\\Games\\", "F:\\Games\\", "G:\\Games\\", "E:\\Applications\\", "F:\\Applications\\", "G:\\Applications\\", "E:\\Homebrew\\", "F:\\Homebrew\\", "G:\\Homebrew\\", "E:\\Apps\\", "F:\\Apps\\", "G:\\Apps\\"...
""" This module provides classes that describe banks of waveforms """ import types import logging import os.path import h5py from copy import copy import numpy as np from ligo.lw import table, lsctables, utils as ligolw_utils import pycbc.waveform import pycbc.pnutils import pycbc.waveform.compress from pycbc import DY...
""" scraping the utility functions for the actual web scraping """ import ssl import datetime import requests import re QUERY_URL = "https://www.wawa.com/Handlers/LocationByStoreNumber.ashx" POSSIBLE_STORE_NUMS = list(range(5000, 6000)) POSSIBLE_STORE_NUMS.extend(list(range(0, 1000))) POSSIBLE_STORE_NUMS.extend(list(ra...
__docformat__ = "epytext" import sys import os import random import tempfile from datetime import date class GenName(): """ @authors: Brigitte Bigi @contact: brigitte.bigi@gmail.com @license: GPL @summary: A class to generates a random file name of a non-existing file. """ def __init__(self,...
from netzob.Common.Type.Endianess import Endianess from common.NetzobTestCase import NetzobTestCase class test_Endianess(NetzobTestCase): def test_BIG(self): self.assertEqual(Endianess.BIG, "big-endian") def test_LITTLE(self): self.assertEqual(Endianess.LITTLE, "little-endian")
""" Copyright (C) 2013 Stanislav Bobovych 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 the License, or (at your option) any later version. This program is distributed in the hop...
from django.contrib.auth.models import User, Group, Permission from django.core.exceptions import ValidationError from django.core.management import call_command from django.test import TestCase from django.utils.encoding import force_text from weblate.lang.models import Language from weblate.trans.models import Projec...
""" 聚类和EM算法 ~~~~~~~~~~~~~~~~ 聚类 :copyright: (c) 2016 by the huaxz1986. :license: lgpl-3.0, see LICENSE for more details. """ import numpy as np import matplotlib.pyplot as plt from sklearn.datasets.samples_generator import make_blobs from chapters.Cluster_EM.gmm import test_GMM,test_GMM_cov_type,tes...
from scapy.all import * from scapy.layers import dhcp6 from time import time def duid(ll_addr): return DUID_LLT(lladdr=ll_addr, timeval=time()) def ias(requested, iface, T1=None, T2=None): return map(lambda r: __build_ia(r, iface, T1, T2), requested) def options(requested): return map(__build_option_by_code...
''' @file freq_scale.py @brief Sandbox for various frequency scale generators @author gm @copyright gm 2014 This file is part of Chartreuse Chartreuse 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...
from PyQt4 import QtGui, QtCore import sys import math import numpy as np from mpl_toolkits.axes_grid import make_axes_locatable, Size from stamp.plugins.groups.AbstractGroupPlotPlugin import AbstractGroupPlotPlugin, TestWindow, ConfigureDialog from stamp.plugins.groups.plots.configGUI.extendedErrorBarUI import Ui_Exte...
"""autogenerated by genpy from loadcell_calibration/GetFactorRequest.msg. Do not edit.""" import sys python3 = True if sys.hexversion > 0x03000000 else False import genpy import struct class GetFactorRequest(genpy.Message): _md5sum = "36d09b846be0b371c5f190354dd3153e" _type = "loadcell_calibration/GetFactorRequest"...
LOTSANNO_LAYER="LotsAnno" LOTSANNO_QD="\"MapNumber\" = '*MapNumber*'OR \"MapNumber\" is NULL OR \"MapNumber\" = ''" PLATSANNO_LAYER="PlatsAnno" PLATSANNO_QD="\"MapNumber\" = '*MapNumber*' OR \"MapNumber\" is NULL OR \"MapNumber\" = ''" TAXCODEANNO_LAYER="TaxCodeAnno" TAXCODEANNO_QD="\"MapNumber\" = '*MapNumber*' OR \"M...
''' Rigidity is a simple wrapper to the built-in csv module that allows for validation and correction of data being read/written from/to CSV files. This module allows you to easily construct validation and correction rulesets to be applied automatically while preserving the csv interface. This allows you to easily upgr...
'''enable run-time addition and removal of master link, just like --master on the cnd line''' ''' TO USE: link add 10.11.12.13:14550 link list link remove 3 # to remove 3rd output ''' from pymavlink import mavutil import time, struct, math, sys, fnmatch, traceback, json, os from MAVProxy.modules.lib im...
"""572. Idempotent matrices https://projecteuler.net/problem=572 A matrix $M$ is called idempotent if $M^2 = M$. Let $M$ be a three by three matrix : $M=\begin{pmatrix} a & b & c\\\ d & e & f\\\ g &h &i\\\ \end{pmatrix}$. Let C(n) be the number of idempotent three by three matrices $M$ with integer elements such that $...
from __future__ import division from __future__ import print_function import tensorflow as tf import numpy as np from keras.datasets import mnist, cifar10, cifar100 from sklearn.preprocessing import LabelBinarizer from nets import LeNet, LeNetVarDropout, VGG, VGGVarDropout sess = tf.Session() def main(): dataset = 'ci...
from sqlalchemy.sql import functions from sqlalchemy.sql.selectable import FromClause from sqlalchemy.sql.elements import ColumnClause from sqlalchemy.ext.compiler import compiles class FunctionColumn(ColumnClause): def __init__(self, function, name, type_=None): self.function = self.table = function ...
import discord from discord.ext import commands from .utils.chat_formatting import escape_mass_mentions, italics, pagify from random import randint from random import choice from enum import Enum from urllib.parse import quote_plus import datetime import time import aiohttp import asyncio settings = {"POLL_DURATION" : ...
import _thread import RPi.GPIO as GPIO import socket import time from time import sleep from sys import exit import datetime Zones = [5, 6, 13, 19] StatusLED = 16 CancelButton = 18 WaterSensor = 10 Sensor = False isRaining = False defaultWaitDuration = 0 def setup(): global serversocket,t # Setup GPIO GPIO.setmode(G...
import os import re from time import sleep from ansible.module_utils.cloud import CloudRetry try: import boto import boto.ec2 #boto does weird import stuff HAS_BOTO = True except ImportError: HAS_BOTO = False try: import boto3 import botocore HAS_BOTO3 = True except: HAS_BOTO3 = False tr...
from setuptools import setup, find_packages from codecs import open from os import path here = path.abspath(path.dirname(__file__)) def readfile(fn): """Read fn and return the contents.""" with open(path.join(here, fn), "r", encoding="utf-8") as f: return f.read() setup( name="usfm2osis", packag...
import unittest from tempfile import NamedTemporaryFile import os import numpy as np from Orange.data import ContinuousVariable, DiscreteVariable from Orange.data.io import CSVFormat tab_file = """\ Feature 1\tFeature 2\tFeature 3 1.0 \t1.3 \t5 2.0 \t42 \t7 """ csv_file = """\ Feature 1, Featu...
from __future__ import unicode_literals import unicodecsv from datetime import datetime, timedelta from pytz import timezone from django.core.urlresolvers import reverse from django.http import HttpResponse from django.views.generic import UpdateView, FormView, TemplateView, CreateView from neonet.views import LoggedIn...
''' Scheduler essential class ''' import types, socket job_state = ['waiting','running','error','finished'] queue_state = ['active', 'hold'] host_state = ['up', 'down', 'error'] class BaseScheduler(object) : ''' Base scheduler class ''' def __init__(self, conf={}, **kw) : ''' Initializat...
"""Provides utilities to preprocess images in CIFAR-10. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow as tf _PADDING = 4 slim = tf.contrib.slim def preprocess_for_train(image, output_height, ...
"""Provide various handy Python functions. Running this script directly will execute the doctests. Functions: int2bin(i, n) -- Convert integer to binary string. bin2int(bin_string) -- Convert binary string to integer. reverse(input_string) -- Reverse a string. transpose(matrix) -- Transpose a list of lists. polygon_are...
""" Copyright 2017 Ryan Wick (rrwick@gmail.com) https://github.com/rrwick/Unicycler This module contains functions relating to BLAST, which Unicycler uses to rotate completed circular replicons to a standard starting point. This file is part of Unicycler. Unicycler is free software: you can redistribute it and/or modif...
import sys import os import re def human_size_to_byte(number): """ Convert number of these units to bytes, ignore case: b : 512 kB : 1000 K : 1024 mB : 1000*1000 m : 1024*1024 MB : 1000*1000 M : 1024*1024 GB : 1000*1000*1000 G : 1024*1024*1024 TB : 1000*100...
from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('api', '0008_auto_20150405_1435'), ] operations = [ migrations.AddField( model_name='brewpispark', name='spark_time', ...
import logging from mimeprovider.documenttype import get_default_document_types from mimeprovider.client import get_default_client from mimeprovider.exceptions import MimeException from mimeprovider.exceptions import MimeBadRequest from mimeprovider.mimerenderer import MimeRenderer from mimeprovider.validators import g...
import zmq from crpropa import Module class SendCandidateProperties( Module ): """ Sends candidate proporties given by the function ```extract_func( candidate )``` over the network to the server on ```ip_port``` """ def __init__( self, ip_port, extract_func ): Module.__init__( self )...
""" A basic example of loading YAML Make sure you use the "safe_load" method and not the "load" method that will give you warnings. References: - https://stackoverflow.com/questions/1773805/how-can-i-parse-a-yaml-file-in-python """ import yaml with open("data_samples/basic.yaml", 'r') as stream: try: data=y...
import threading from systemd import journal from threading import Thread import smtplib import email.utils from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText class Mailer(threading.Thread): """ Mailer :desc: Class that sends an email Extends Thread """ def __ini...