code
stringlengths
1
199k
from bottle import run import doc run(server="paste", host="0.0.0.0")
from django.db.models import FileField from django.forms import forms from django.template.defaultfilters import filesizeformat from django.utils.translation import ugettext_lazy as _ class ContentTypeRestrictedFileField(FileField): """ Same as FileField, but you can specify: * content_types - list containing allowe...
import redis try: import unittest2 as unittest except ImportError: import unittest from relationships import Relationship from relationships.relationship import default_key_list class RelationshipsTestCase(unittest.TestCase): def setUp(self): self.redis_connection = redis.StrictRedis( ho...
from .. import OratorTestCase from orator.support.collection import Collection class CollectionTestCase(OratorTestCase): def test_first_returns_first_item_in_collection(self): c = Collection(['foo', 'bar']) self.assertEqual('foo', c.first()) def test_last_returns_last_item_in_collection(self): ...
"""User forms""" from flask_wtf import Form from wtforms import PasswordField, StringField from wtforms.validators import DataRequired, Email, EqualTo, Length from .models import User class RegisterForm(Form): """Register form""" username = StringField('Username', validators=[DataRequ...
from .spell import main if __name__ == u"__main__": main()
try: # Python 2.7 from collections import OrderedDict except: # Python 2.6 from gluon.contrib.simplejson.ordered_dict import OrderedDict from gluon import current from gluon.storage import Storage def config(settings): """ Template settings All settings which are to configure a speci...
from steamweb.actions_base import GameEvent class TankPriceAdjustment(GameEvent): def condition(self, game, player): return True def resolution(self, game, player, arguments = None): game.tank_index += 1 class WaterOnPass(GameEvent): def condition(self, game, player): return not play...
import pkg_resources import argparse import logging import pushy import sys from . import exc from . import validate from . import sudo_pushy LOG = logging.getLogger(__name__) def parse_args(args=None, namespace=None): parser = argparse.ArgumentParser( description='Deploy Ceph', ) verbosity = pa...
import os import tensorflow as tf import numpy as np '''Routines for reading the CIFAR-10 python batch files.''' NUM_CLASSES = 10 NUM_EXAMPLES_PER_EPOCH_FOR_TRAIN = 50000 DEFALFT_DATASET_DIR = '/datasets/cifar-10-batches-py' def _load_cifar10(path=DEFALFT_DATASET_DIR): '''Read training and testing samples from CIFA...
from __future__ import unicode_literals from django.contrib.auth.models import User from django.utils import six from django.utils.six.moves import zip from djblets.testing.decorators import add_fixtures from djblets.webapi.errors import INVALID_FORM_DATA from reviewboard.reviews.models import DefaultReviewer, Group fr...
from django.http import HttpResponse from django.template import Context from django.template.loader import render_to_string from django.shortcuts import render import requests import uuid """ SENDER: ff8080813dab64c0013dcaf6c4ef0de6 USER LOGIN: ff8080813dab64c0013dcaf6c4f00dea USER PWD: jYBdGJ8a SECRET: eBnQ9rZSAWSENy...
import unittest2 as unittest from mock import Mock from mock import patch from tribe import util class TestUtil(unittest.TestCase): def setUp(self): self._servers = ['mocked-1.example.com', 'mocked-2.example.com', 'mocked-3.example.com'] self._addres...
import functools from typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar import warnings from azure.core.async_paging import AsyncItemPaged, AsyncList from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error from azur...
import numpy as np import wfdb from os import path import os.path from flask import Flask, Response from flask import request, current_app from flask import json from flask_jsonpify import jsonify def getData(database, record): fileName = path.join('database',database,record) record = wfdb.rdsamp(fileName, channels=[...
import urllib import re import sys from bs4 import BeautifulSoup reg = r'http.*zip"' page = urllib.urlopen('https://www.udacity.com/wiki/st101/downloads').read() soup = BeautifulSoup(page) for i in re.findall(reg,page): print i[:-1]
from fysom import Fysom from ..application.errorsubscribe import ErrorSubscribe import machinetalk.protobuf.types_pb2 as pb from machinetalk.protobuf.message_pb2 import Container class ErrorBase(object): def __init__(self, debuglevel=0, debugname='Error Base'): self.debuglevel = debuglevel self.debu...
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 'Blog.head' db.add_column('blogs_blog', 'head', self.gf('django.db.models.fields.TextField')(defau...
''' Script to generate list of seed nodes for chainparams.cpp. This script expects two text files in the directory that is passed as an argument: nodes_main.txt nodes_test.txt These files must consist of lines in the format <ip> <ip>:<port> [<ipv6>] [<ipv6>]:<port> <onion>.onion 0xDDBBCC...
from distutils.core import setup from keynote_api import __version__ setup(name = 'python-keynote', version = __version__, description = 'Apple Keynote 09 Parser', license = 'MIT', author = 'Paul Hildebrandt', author_email = 'paul_hildebrandt@yahoo.com', py_modules = ['keynote_api'],...
""" Creates Payment object """ class Payment(): """ Create a new payment object from a json object in Venmo Webhook response format """ def __init__(self, json): self.json = json """ Checks whether or not json object is a payment @param json json object to check """ @staticmethod def checkPayment(json): i...
from argparse import ArgumentParser import ast import json from pathlib import Path from pprint import pprint from subprocess import check_call from typing import NamedTuple, Optional, Sequence, Set, Tuple import networkx as nx from . import ( create_output_path, data_consumer_names, data_producer_names, ...
def assert_type(item, types): if not isinstance(item, types): if not isinstance(types, tuple): types = [types] raise TypeError('expected {types}, got {type}'.format( types=' or '.join(_.__name__ for _ in types), type=type(item).__name__ )) def assert_subcl...
class Sample_Storage(): def __init__(self, l): self.samples = list(l) def append_samples(self, l): self.samples.extend(l) class Sample_Storage_Window(): """Wrap Sample_Storage() so that it's simpler to keep track of how many samples you've looked at so far.""" def __init__(self, stor): self.stor = stor self...
from untwisted.network import xmap from untwisted.utils.stdio import LOAD class Accumulator(object): """ Just an accumulator on LOAD. """ def __init__(self, spin): xmap(spin, LOAD, self.update) spin.accumulator = self self.data = '' def update(self, spin, data): self....
from distutils.core import setup setup(name='PySpatialOpt', version='0.0.1', description='Python Spatial Optimization Library', author='Aaron Pulver', author_email='apulverizer@gmail.com', url='https://github.com/apulverizer/pyspatialopt', packages=['pyspatialopt', 'pyspatialopt.models', ...
from setuptools import setup, find_packages setup( name='riscyas', version='0.6.0', author = 'Sean Wilson', author_email = 'spwilson27@gmail.com', description = 'An elementary assembler for the RISC-V ISA.', license = 'MIT', url = 'https://github.com/spwilson2/RIS...
from copy import deepcopy from collections import defaultdict from simpleflake import simpleflake from lab_assistant import conf, utils __all__ = [ 'get_storage', 'store', 'retrieve', 'retrieve_all', 'clear', ] def get_storage(path=None, name='Experiment', **opts): if not path: path = co...
import datetime import os from django.test import TestCase from django.conf import settings from django.core.urlresolvers import reverse from schedule.conf.settings import FIRST_DAY_OF_WEEK from schedule.models import Event, Rule, Occurrence, Calendar from schedule.periods import Period, Month, Day, Year from schedule....
from pybuilder.core import init, use_plugin use_plugin("python.core") use_plugin("python.install_dependencies") use_plugin("python.distutils") use_plugin("python.unittest") use_plugin("python.coverage") default_task = "publish" @init def initialize(project): project.build_depends_on('pyyaml') project.build_depends_...
import RPi.GPIO as GPIO from time import sleep PIN = 5 GPIO.setmode(GPIO.BCM) GPIO.setup(PIN, GPIO.IN) while True: if (GPIO.input(PIN)): print("pin True.") else: print("pin False.") sleep(1)
import operator from sqlalchemy import MetaData, null, exists, text, union, literal, \ literal_column, func, between, Unicode, desc, and_, bindparam, \ select, distinct, or_, collate from sqlalchemy import inspect from sqlalchemy import exc as sa_exc, util from sqlalchemy.sql import compiler, table, column from...
from math import factorial def SumOfFactorialsOfDigits(n): result = 0 for d in str(n): result += factorial(int(d)) return result for i in range(3,1000000): if SumOfFactorialsOfDigits(i) == i: print(i)
import shelve import random import textwrap from time import sleep, time from collections import namedtuple from bearlibterminal import terminal as term import spaceship.strings as strings from spaceship.scene import Scene from spaceship.screen_functions import * import spaceship.tools as tools import spaceship.action ...
from django.conf.urls import patterns, url from . import views urlpatterns = patterns('', url(r'^$', views.view_login_page, name='login'), url(r'^login/', views.handle_login, name='login_act'), url(r'^logout/', views.handle_logout, name='logout_act'), )
import os from os.path import join, dirname from glob import glob from xml.etree import ElementTree import numpy as np from lab.misc.auto_helpers import locate, get_element_size_um, get_prairieview_version def get_plane_spacing(xml_path): """Determine the spacing in microns between planes in a T/Z-series.""" pa...
from __future__ import print_function from builtins import range import jsonpatch import json import re import sys from collections import defaultdict from noodles.utils.datahandler import datahandler vers={} lstre = re.compile('^/(cross_links|branches|tags|informed|dependencies)') urlre = re.compile('http(|s)\:\/\/([^...
__all__ = ['ark_chat', 'ark_logs']
import logging from pyvisdk.exceptions import InvalidArgumentError log = logging.getLogger(__name__) def VirtualSerialPortDeviceBackingOption(vim, *args, **kwargs): '''The data object type contains the options for backing a serial port with a host serial port device.''' obj = vim.client.factory.create('ns0:...
from __future__ import division import numbers import numpy as np import six import chainer from chainer.backends import cuda from chainer import function from chainer.utils import type_check from chainercv.functions.ps_roi_average_pooling_2d import _outsize def _pair(x): if isinstance(x, chainer.utils.collections_...
import boto3 ND = 'nodelete' TR = 'true' def lambda_handler(event, context): ec2 = boto3.client('ec2') resp = ec2.describe_snapshots() all_list = [] del_list = [] #print (resp) for snapshots in resp['Snapshots']: for snapshotid in snapshots['SnapshotId']: all_list.append(snapshots[...
""" This module provides :py:class:`PoolOfPoolMixin` only. Basically you need to mix it into :py:class:`concurrent.futures.Executor` implementation and it will be possible to use it with :py:class:`PoolOfPools`. """ from collections import deque from itertools import islice from sys import exc_info from six import rera...
""" Handle basic Dict to object convertion """ __all__ = ["Struct"] class Struct: """ The recursive class for building and representing objects with. """ def __init__(self, obj): self._createObject(obj) def _createObject(self, obj): for k, v in obj.iteritems(): if isinstance(v,...
import wx class MyFrame(wx.Frame): def __init__(self,parent,title): wx.Frame.__init__(self,parent,-1,title) bt=wx.Button(self,-1,"hola") self.Bind(wx.EVT_BUTTON, self.decir_hola, bt) def decir_hola(self,*arg): print ("hola mundo") class MyApp (wx.App): def OnInit(self): fra...
import collections import re MountedResourceMatch = collections.namedtuple('MountedResourceMatch', 'mounted_resource urlvars') class MountedResource: urlvar_regex = r'<(?P<identifier>[^\d\W]\w*)>' def __init__(self, app, name, factory, path, methods=(), method=None, add_slash=False): if not path.startsw...
from django.test import TestCase from cla_eventlog.constants import LOG_TYPES, LOG_LEVELS from cla_eventlog.events import BaseEvent from cla_eventlog.registry import EventRegistry class RegistryStartupChecksTestCase(TestCase): def test_event_without_key_fails(self): registry = EventRegistry() class ...
import time from twisted.internet import defer from zope.interface import implements from tensor.interfaces import ITensorSource from tensor.objects import Source from tensor.utils import fork class DarwinRTSP(Source): """Makes avprobe requests of a Darwin RTSP sample stream (sample_100kbit.mp4) **Configura...
from django.contrib import admin from .models import Comment class CommentAdmin(admin.ModelAdmin): list_display = ['id' ,'custom_model', 'user'] list_display_links = ['id'] list_filter = ['timestamp', 'updated'] admin.site.register(Comment, CommentAdmin)
__author__ = "Lário dos Santos Diniz" import re from django.db import models from django.core import validators from django.contrib.auth.models import AbstractBaseUser, UserManager, PermissionsMixin class Usuarios(AbstractBaseUser, PermissionsMixin): username = models.CharField( 'Apelido / Usuário', max_len...
import sys import numpy as np import matplotlib as mpl mpl.use('Agg') import matplotlib.pyplot as plt plt.ioff() import seaborn import pandas as pd import pybedtools from joblib import Parallel, delayed from common import parse_config, get_chrom_size """ This scipt counts the number of peaks per bin of Hi-C (250kb in t...
""" .. codeauthor:: Tsuyoshi Hombashi <tsuyoshi.hombashi@gmail.com> """ import itertools import pytest from pathvalidate import ascii_symbols, replace_symbol, unprintable_ascii_chars, validate_symbol from pathvalidate._symbol import validate_unprintable from pathvalidate.error import ErrorReason, ValidationError from ....
""" $URL: svn+ssh://svn/repos/trunk/durus/history.py $ $Id: history.py 28338 2006-05-04 21:45:03Z dbinger $ """ from schevo.store.file_storage import FileStorage2 from schevo.store.connection import Connection from schevo.store.persistent import Persistent class _HistoryIndex (dict): """ A substitute offset ind...
import json from public import find_out from random import randint import sys sys.path.insert(0, '/Library/Python/2.7/site-packages/') from sklearn.cluster import KMeans from numpy import std from numpy import average N = 10000 with open('learning/board_feature/standard_stats.json') as f: ss = json.load(f) stan...
def read_word_freq(line): parts = line.split('\t') return parts[0].lower(), int(parts[1]) def load_dict(): en_dict = {} with open('../data/ngrams/en_dict2.txt') as f: for raw_line in f: token, freq = read_word_freq(raw_line) en_dict[token] = freq return en_dict NWORDS...
import collections import prime primeFactorMemoized = { 1 : collections.defaultdict(int) } def primeFactors(n): """Use trial division of primes to find factors""" if n in primeFactorMemoized: return primeFactorMemoized[n].copy() for p in prime.primes(): if (n % p == 0): result = primeFactors(n // p)...
import sys, subprocess class DeepSpeechRecognizer(): def __init__(self, model=None, alphabet=None, lm=None, trie=None): self.model = model self.alphabet = alphabet self.lm = lm self.trie = trie self.py3 = sys.version_info[0] > 2 def recognize(self, audio_file): ""...
from aiohttp import web from examples.aiohttp.hello import HelloStub from venom.rpc import Venom from venom.rpc.comms.aiohttp import create_app, Client venom = Venom() venom.add(HelloStub, Client, 'http://localhost:8080', public=True) app = create_app(venom) if __name__ == '__main__': web.run_app(app, port=8081)
import string from Tkinter import * dict={} def find_cols(filename): """Get no. of assignment cols in peak file""" fd=open(filename) lines=fd.readlines() fd.close() cols=None import string for line in lines: line=string.strip(line) if len(line)>0 and 'Assignment' in line: ...
from flask import request from indico.modules.admin.views import WPAdmin from indico.modules.users import User from indico.util.i18n import _ from indico.web.breadcrumbs import render_breadcrumbs from indico.web.views import WPDecorated, WPJinjaMixin class WPUser(WPJinjaMixin, WPDecorated): """Base WP for user prof...
class Solution(object): def largestRectangleArea(self, heights): assert isinstance(heights, list) # Index of the current height being processed. i = 0 # Stack of height indexes in order of occurence and non-decreasing # height. history = [] maxArea = 0 ...
""" @Author: Well @Date: 2015 - 09 - 14 """ from __future__ import unicode_literals from __future__ import print_function import re import json import traceback import requests def get_token(username, password): """ # 获取预发布环境的user_token,access_token # 返回类型为list # 分别为:user_token,access_token """ ...
from __future__ import print_function import os import sys import argparse from itertools import product,cycle import string import numpy as np import pandas as pd from pyTecanFluent import Utils from pyTecanFluent import Fluent from pyTecanFluent import Labware def get_desc(): desc = 'Create robot commands for qPC...
""" The MIT License Copyright (c) 2011 Olle Johansson Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publi...
from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('djconnectwise', '0136_boardstatus_time_entry_not_allowed'), ] operations = [ migrations.AlterField( model_name='boardstatus', name='time_entry_not_allowed', ...
""" dj-stripe Sync Method Tests. """ import contextlib from copy import deepcopy from unittest.mock import patch from django.contrib.auth import get_user_model from django.test.testcases import TestCase from stripe.error import InvalidRequestError from djstripe.models import Customer from djstripe.sync import sync_subs...
import configparser, os, csv, re, numpy, pickle, logging, time from collections import OrderedDict from scipy import spatial class indexer: def __init__(self, terms, documents, matrix): self.terms = terms self.documents = documents self.matrix = matrix class queryNumber_queryText: def __...
import logging from pyvisdk.exceptions import InvalidArgumentError log = logging.getLogger(__name__) def TemplateConfigFileInfo(vim, *args, **kwargs): '''This data object type describes a template virtual machine configuration file.''' obj = vim.client.factory.create('ns0:TemplateConfigFileInfo') # do some ...
from lxml import html from selenium import webdriver import os import time import sys; reload(sys); sys.setdefaultencoding("utf8") class NewsFeed: def __init__(self,username,password): self.username = username self.password = password self.browser = webdriver.Firefox() self.POI = [] def login(self): self.br...
import os, sys # low level handling, such as command line stuff import string # string methods available import re # regular expressions import getopt # comand line argument handling from low import * # custom functions, written by myself from goterm import GOTerm from collections import default...
from setuptools import setup __version__ = 'unknown' for line in open('src/rtmixer.py'): if line.startswith('__version__'): exec(line) break setup( name='rtmixer', version=__version__, package_dir={'': 'src'}, py_modules=['rtmixer'], cffi_modules=['rtmixer_build.py:ffibuilder'], ...
from sequencer import app app.run()
"""This module contains a collection of unit tests for the ```trhutil``` module.""" import httplib import json import os import sys import unittest import uuid import mock import tornado.web import tornado.testing from yar.util import trhutil def _uuid(): return str(uuid.uuid4()).replace("-", "") class IsJSONConten...
""" This module contains classes to wrap Python VTK to make nice molecular plots. """ __author__ = "Shyue Ping Ong" __copyright__ = "Copyright 2011, The Materials Project" __version__ = "0.1" __maintainer__ = "Shyue Ping Ong" __email__ = "shyuep@gmail.com" __date__ = "Nov 27, 2011" import os import itertools import mat...
import pywt, numpy as np from haar import haar_transform, inverse_haar data = np.ones((4,4), dtype=np.float64) coeffs = pywt.dwt2(data, 'haar') cA, (cH, cV, cD) = coeffs mode = 'haar' testa = [1,2,3,4,5,6,7,8] coeffs = pywt.wavedec(testa, mode, level=3) print coeffs haar_r = haar_transform(np.asarray(testa, dtype='floa...
A=[[1,2,3], [4,5,6]] def transpose(m): height = len(m) width = len(m[0]) return[[m[row][col] for row in range(height)] for col in range(width)] print transpose(A)
from __future__ import unicode_literals from flask import url_for from jinja2 import Markup from sqlalchemy import sql from studio.core.engines import db from sqlalchemy.ext.hybrid import hybrid_property __all__ = [ 'ArticleModel', 'ArticleContentModel', ] class ArticleModel(db.Model): __tablename__ = 'arti...
import pymongo import pytumblr mongo = pymongo.MongoClient() tumblr = pytumblr.TumblrRestClient( 'wXMIlYznCc5ugT2L4GaWMTEDPX1Z37OuUIkwae962BZM5YOhcq', 'ZoAKEXPlWSARyYNdWuK4XdyhQfbP4q2z62E0XjokKHaWgANPav', 'R4ZfhjLM1HaIQZlc4Tv9zwUVBHroY5PvRZy4veQopthmigtfln', '3Hyd5v26lWmFlAZdQdVLEWwVQ94lSBsdiIbeEI72mbRZ...
from __future__ import unicode_literals from django.db import migrations def delete_duplicate_uors(apps, schema_editor): """Delete duplicate UserOrganisationRoles.""" UOR = apps.get_model('lizard_auth_client', 'UserOrganisationRole') for row in UOR.objects.all(): if UOR.objects.filter( u...
import ConfigParser DEFAULTS = { 'host': '0.0.0.0', 'port': 23053, 'password': None, 'timeout': 600, 'bufferLength': 2048, 'passwordHash': 'SHA1', } class ReloadableConfig(ConfigParser.RawConfigParser): def __init__(self, *args, **kwargs): ConfigParser.RawConfigParser.__init__(self, ...
""" What is the greatest product of four adjacent numbers (horizontally, vertically, or diagonally) in this 20x20 array? 08 02 22 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08 49 49 99 40 17 81 18 57 60 87 17 40 98 43 69 48 04 56 62 00 81 49 31 73 55 79 14 29 93 71 40 67 53 88 30 03 49 13 36 65 52 70 95 23 04 60 1...
import matplotlib.pyplot as plt import pylab as pl import networkx as nx import random as rnd import pickle import math import numpy as np def read_pickled_metrics(u,v): global ranked_degrees,ranked_nodes,moving ranked_degrees=[[0 for x in range(101)] for y in range(101)] ranked_nodes=[[0 for x in range(101)] for y ...
from django.contrib import admin # noqa
from Foundation import * from AppKit import * import objc class TextController (NSObject): title = objc.IBOutlet()
from .generic import Manager, SyncMixin class CollaboratorStatesManager(Manager, SyncMixin): state_name = 'CollaboratorStates' object_type = None # there is no object type associated resource_type = 'collaborators' def get_by_ids(self, project_id, user_id): """ Finds and returns the col...
import csv import matplotlib.pyplot as plt import functions_v5 as fxn ILIin = open('/home/elee/Dropbox/Elizabeth_Bansal_Lab/SDI_Data/explore/SQL_export/OR_allweeks_outpatient.csv','r') ILIfile = csv.reader(ILIin, delimiter=',') visitin = open('/home/elee/Dropbox/Elizabeth_Bansal_Lab/SDI_Data/explore/SQL_export/anydiag_...
__all__ = ['MissionTrace', 'CommandTrace', 'TraceRecorder'] from typing import Tuple, Iterator, Dict, Any, Optional, Type import attr import json import threading from bugzoo.core.fileline import FileLineSet from .command import Command from .state import State from .connection import Message class TraceRecorder(object...
import requests class Site: def __init__(self, username, password, urls=None): self.username = username self.password = password self.session = requests.Session() self.get = self.session.get self.post = self.session.post self.urls = urls # Optional handy constant for...
from __future__ import absolute_import, unicode_literals from django.test import TestCase from django.utils import translation from django.utils.html import escape import haystack from haystack.query import SearchQuerySet import time from testproject.models import Document, ParlerDocument from unittests.mocks import Da...
import subprocess import re def merge_dicts(*dict_args): result = {} for dictionary in dict_args: result.update(dictionary) return result def run(config): args = "" for key, value in config.items(): if value is None: args += " -" + key else: args += " ...
from runner.koan import * def my_global_function(a, b): return a + b class AboutMethods(Koan): def test_calling_a_global_function(self): self.assertEqual(5, my_global_function(2, 3)) # NOTE: Wrong number of arguments is not a SYNTAX error, but a # runtime error. def test_calling_functions_wi...
print 1 exit("exit message - quit the program") print "you shouldn't see this"
import pytest from environ import Env def test_solr_parsing(solr_url): url = Env.search_url_config(solr_url) assert len(url) == 2 assert url['ENGINE'] == 'haystack.backends.solr_backend.SolrEngine' assert url['URL'] == 'http://127.0.0.1:8983/solr' def test_solr_multicore_parsing(solr_url): timeout =...
"""Test that the public API classes are available from the ``vcfpy`` package """ import io import textwrap import pytest from vcfpy import exceptions from vcfpy import header from vcfpy import parser def test_header_checker_missing_fileformat(): # construct Header lines = [header.HeaderLine("key", "value")] ...
""" Commands for the Minke CLI utility """ from .sample import SampleCommand from .describe import DescribeCommand from .preprocess import PreprocessCommand
""" Configuration functions for the logging package for Python. The core package is based on PEP 282 and comments thereto in comp.lang.python, and influenced by Apache's log4j system. Copyright (C) 2001-2008 Vinay Sajip. All Rights Reserved. To use, simply 'import logging' and log away! """ import sys, logging, logging...
""" disthelpers ----------- The ``guidata.disthelpers`` module provides helper functions for Python package distribution on Microsoft Windows platforms with ``py2exe`` or on all platforms thanks to ``cx_Freeze``. """ import sys import os import os.path as osp import shutil import traceback import atexit import imp from...
import numpy as np class EntityNormalizationHandler: batch = None def __init__(self, batch): self.batch = batch def get_normalization_by_vertex_count(self, weight_positives): vertex_lists = [np.ones_like(example.get_entity_vertex_indexes(), dtype=np.float32) for example in self.batch.example...
from flask_mail import Mail from PhoenixNow.login import login_manager from PhoenixNow.model import db from flask import Flask import os app = Flask(__name__) mail = Mail() def create_app(config_object, register_blueprint=True): """ Sets up a Flask app variable based on a config object -- see config.py. We ...
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import unittest import numpy as np from vectormath import Vector2, Vector2Array, Vector3, Vector3Array class TestVMathVector3(unittest.TestCase): def test_init_excepti...
import matplotlib.pyplot as plt import numpy as np import torch.nn as nn import torch def loss_plot(d_loss_hist, g_loss_hist): x = range(len(d_loss_hist)) plt.plot(x, d_loss_hist, label='D_loss') plt.plot(x, g_loss_hist, label='G_loss') plt.xlabel('Epoch') plt.ylabel('Loss') plt.legend(loc=4) ...