code
stringlengths
1
199k
import math from pathlib import Path from tkinter import W, N, E, StringVar, PhotoImage from tkinter.ttk import Button, Label, LabelFrame from overrides import overrides from pyminutiaeviewer.gui_common import NotebookTabBase from pyminutiaeviewer.minutia import Minutia, MinutiaType class MinutiaeEditorFrame(NotebookTa...
"""This screws up visualize.py""" """ import numpy as np from matplotlib import pyplot as plt from matplotlib.lines import Line2D from torch.autograd import Variable as Var from torch import Tensor class RealtimePlot(): def __init__(self, style='ggplot'): plt.style.use(style) plt.ion() self....
# coding: utf-8 import unittest import time from msrestazure.azure_exceptions import CloudError import azure.mgmt.relay.models from azure.mgmt.relay.models import RelayNamespace, Sku, SkuTier, Relaytype, AuthorizationRule, AccessRights, AccessKeys, WcfRelay, ErrorResponseException, ErrorResponse from azure.common.cred...
from tkinter import * import mysql.connector as mysql from MySQLdb import dbConnect from HomeOOP import * import datetime from PIL import Image, ImageTk class MainMenu(Frame): def __init__(self, parent): #The very first screen of the web app Frame.__init__(self, parent) w, h = parent.winfo_screenwi...
from youtrack import YouTrackException def utf8encode(source): if isinstance(source, str): source = source.encode('utf-8') return source def _create_custom_field_prototype(connection, cf_type, cf_name, auto_attached=False, additional_params=None): if additional_params is None: additional_par...
from __future__ import division
import inspect try: from collections.abc import Mapping except ImportError: from collections import Mapping import six from .reducers import tuple_reducer, path_reducer, dot_reducer, underscore_reducer from .splitters import tuple_splitter, path_splitter, dot_splitter, underscore_splitter REDUCER_DICT = { "...
from IPython.display import HTML from bs4 import BeautifulSoup import urllib f = open('chars.txt', 'w') r = urllib.urlopen('http://www.eventhubs.com/tiers/ssb4/').read() soup = BeautifulSoup(r, "lxml") characters = soup.find_all("td", class_="tierstdnorm") count = 1 tierCharList=[] for element in characters: if cou...
"""Miscellaneous utility functions.""" import os import sys import errno import locale import re import tempfile import shutil import fnmatch import functools from collections import Counter, namedtuple from multiprocessing.pool import ThreadPool import traceback import subprocess import platform import shlex from beet...
import pandas as pd import numpy as np import re from gensim import corpora, models, similarities from gensim.parsing.preprocessing import STOPWORDS def split(text): ''' Split the input text into words/tokens; ignoring stopwords and empty strings ''' delimiters = ".", ",", ";", ":", "-", "(", ")", " ", "\t" r...
import win32process import win32api import win32con import ctypes import os, sys, string TH32CS_SNAPPROCESS = 0x00000002 class PROCESSENTRY32(ctypes.Structure): _fields_ = [("dwSize", ctypes.c_ulong), ("cntUsage", ctypes.c_ulong), ("th32ProcessID", ctypes.c_ulong), ...
from evosnap import constants class POSDevice: def __init__(self,**kwargs): self.__order = [ 'posDeviceType', 'posDeviceConnection', 'posDeviceColour', 'posDeviceQuantity', ] self.__lower_camelcase = constants.ALL_FIELDS self.pos_device_type = kwargs.get('pos_device_type'...
import numpy as np from snob import mixture_slf as slf n_samples, n_features, n_clusters, rank = 1000, 50, 6, 1 sigma = 0.5 true_homo_specific_variances = sigma**2 * np.ones((1, n_features)) rng = np.random.RandomState(321) U, _, _ = np.linalg.svd(rng.randn(n_features, n_features)) true_factor_loads = U[:, :rank].T tru...
import os import shutil from codecs import open as codecs_open import numpy as np from setuptools import setup, find_packages from distutils.core import Distribution, Extension from distutils.command.build_ext import build_ext from distutils import errors from Cython.Build import cythonize from Cython.Compiler.Errors i...
"""This module implements all contexts for state handling during uploads and downloads, the main interface to which being the TftpContext base class. The concept is simple. Each context object represents a single upload or download, and the state object in the context object represents the current state of that transfe...
import base64 import fnmatch import glob import json import os import re import shutil import stat import subprocess import urllib.parse import warnings from datetime import datetime, timedelta from distutils.util import strtobool from distutils.version import LooseVersion from typing import Tuple, Any, Union, List, Di...
import sys import time import re import smbus class Adafruit_I2C(object): @staticmethod def getPiRevision(): "Gets the version number of the Raspberry Pi board" # Revision list available at: http://elinux.org/RPi_HardwareHistory#Board_Revision_History try: with open('/proc/cpuinfo', 'r') as infile...
from .. import util from ..util import sqla_compat from . import schemaobj from sqlalchemy.types import NULLTYPE from .base import Operations, BatchOperations import re class MigrateOperation(object): """base class for migration command and organization objects. This system is part of the operation extensibilit...
""" Django settings for puput_demo project. For more information on this file, see https://docs.djangoproject.com/en/dev/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/dev/ref/settings/ """ from __future__ import absolute_import, unicode_literals from puput import...
import _plotly_utils.basevalidators class FamilysrcValidator(_plotly_utils.basevalidators.SrcValidator): def __init__( self, plotly_name="familysrc", parent_name="barpolar.hoverlabel.font", **kwargs ): super(FamilysrcValidator, self).__init__( plotly_name=plotly_name, par...
import arp import oui import ipcalc import sys class Discovery(object): """ Find out the host types in the Ip range (CIDR) NOTE: This finds mac addresses only within the subnet. It doesn't fetch mac addresses for routed network ip's. """ def __init__(self): self.__arp = arp.ARP() sel...
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 index on 'Place', fields ['place_id'] db.create_index('storybase_geo_place', ['place_id']) # Adding index on 'Location...
import csv import numpy as np import HackApp.models as database from django.core.management.base import BaseCommand, CommandError class Command(BaseCommand): def handle(self, *args, **options): percentageAfterNine = 0.05 percentage3to50 = 0.7 longBound = [13.375556, 16.610556] latBo...
import os import mock import pytest import bridgy.inventory from bridgy.inventory import InventorySet, Instance from bridgy.inventory.aws import AwsInventory from bridgy.config import Config def get_aws_inventory(name): test_dir = os.path.dirname(os.path.abspath(__file__)) cache_dir = os.path.join(test_dir, 'aw...
from bluepy.btle import * import time import serial from pyqtgraph.Qt import QtGui, QtCore import pyqtgraph as pg start_time = time.time() data = [] data2 = [] data3 = [] data4 = [] angles = [] pg.setConfigOption('background', 'w') pg.setConfigOption('foreground', 'k') pen = pg.mkPen('k', width=8) app = QtGui.QApplicat...
""" GatewayScanner is an abstraction for searching for KNX/IP devices on the local network. * It walks through all network interfaces * and sends UDP multicast search requests * it returns the first found device """ from __future__ import annotations import asyncio from functools import partial import logging from typi...
from django.db import models from django.utils.translation import ugettext_lazy as _ from feincms.module.page.models import Page from feincms.content.richtext.models import RichTextContent from feincms.content.medialibrary.models import MediaFileContent Page.register_extensions('feincms.module.extensions.datepublisher'...
import sublime, sublime_plugin def clean_layout(layout): row_set = set() col_set = set() for cell in layout["cells"]: row_set.add(cell[1]) row_set.add(cell[3]) col_set.add(cell[0]) col_set.add(cell[2]) row_set = sorted(row_set) col_set = sorted(col_set) rows = lay...
class Card: count = 0 url = "" name = "" sideboard = -1
from __future__ import (unicode_literals, absolute_import, division, print_function) import re import unicodedata import datetime import subprocess from py3compat import string_types, text_type from django.utils import timezone from django.conf import settings from uninond.models.SMSMessages imp...
from django.conf import settings from django.contrib import messages from django.forms import Form from django.http import Http404, HttpResponse, HttpResponseBadRequest from django.shortcuts import get_object_or_404, redirect, render from django.views.decorators.csrf import csrf_exempt from django.utils import timezone...
from collections import defaultdict from typing import cast, Dict, List, NewType from backend.common.consts.api_version import ApiMajorVersion from backend.common.models.event_details import EventDetails from backend.common.models.keys import TeamKey from backend.common.queries.dict_converters.converter_base import Con...
import setuptools with open("README.rst") as f: long_description = f.read() setuptools.setup( name='django-diplomacy', version="0.8.0", author='Jeff Bradberry', author_email='jeff.bradberry@gmail.com', description='A play-by-web app for Diplomacy', long_description=long_description, long...
"""Signal pattern matching.""" import re from typing import Union class PatternError(Exception): """Pattern error.""" class Pattern: """Signal pattern representation.""" PATTERN_REGEX = re.compile(r"[01xX]+") PATTERN_REGEX_BYTES = re.compile(b"[01xX]+") def __init__(self, pattern: Union[str, bytes])...
import re import time import subprocess out=subprocess.check_output(["cat","/sys/class/net/eth0/address"]) print out print "hi"
"""Calculating pi with Monte Carlo Method and NumPy. """ from __future__ import print_function import numpy #1 @profile def pi_numpy(total): #2 """Compute pi. """ x = numpy.random.rand(total) ...
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 = [ ('wunderlist', '0011_auto_20151230_1843'), ] operations = [ migrations.AlterField( ...
import os from channels.asgi import get_channel_layer os.environ.setdefault("DJANGO_SETTINGS_MODULE", "ena.settings") channel_layer = get_channel_layer()
from rest_framework.serializers import ( HyperlinkedIdentityField, ModelSerializer, SerializerMethodField, ) from comments.api.serializers import CommentSerializer from accounts.api.serializers import UserDetailSerializer from comments.models import Comment from posts.models import Post class PostCreateUpdateSerial...
import json import requests class SlackNotification(object): icon_url = "https://github-bogdal.s3.amazonaws.com/freepacktbook/icon.png" def __init__(self, slack_url, channel): self.slack_url = slack_url self.channel = channel if not self.channel.startswith("#"): self.channel ...
""" KINCluster is clustering like KIN. release note: - version 0.1.6 fix settings update pipeline delete unused arguments fix convention by pylint now logging - version 0.1.5.5 fix using custom settings support both moudle and dict - version 0.1.5.4 Update tokenizer, remove stopwords eff...
import sublime, sublime_plugin class SaveAllExistingFilesCommand(sublime_plugin.ApplicationCommand): def run(self): for w in sublime.windows(): self._save_files_in_window(w) def _save_files_in_window(self, w): for v in w.views(): self._save_existing_file_in_view(v) def _save_existing_file_in_view(self, v):...
import os import sys if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "asteria.settings") from django.core.management import execute_from_command_line execute_from_command_line(sys.argv)
from collections import deque import time import requests BRAZIL = 'br' EUROPE_NORDIC_EAST = 'eune' EUROPE_WEST = 'euw' KOREA = 'kr' LATIN_AMERICA_NORTH = 'lan' LATIN_AMERICA_SOUTH = 'las' NORTH_AMERICA = 'na' OCEANIA = 'oce' RUSSIA = 'ru' TURKEY = 'tr' platforms = { BRAZIL: 'BR1', EUROPE_NORDIC_EAST: 'EUN1', ...
import logging logger = logging.getLogger("pocean") logger.addHandler(logging.NullHandler()) __version__ = "1.0.0"
from .message import * from functools import wraps import datetime import pymongo import re from app import session class Singleton(type): instance = None def __call__(cls, *args, **kwargs): if not cls.instance: cls.instance = super(Singleton, cls).__call__(*args, **kwargs) return cl...
from setuptools import setup with open('requirements.txt') as f: required = f.read().splitlines() setup( name="aloft.py", version="0.0.4", author="Nate Mara", author_email="natemara@gmail.com", description="A simple API for getting winds aloft data from NOAA", license="MIT", test_suite="tests", keywords="aviat...
from django.apps import AppConfig class AutodoappConfig(AppConfig): name = 'AutoDoApp'
""" ================================================== Sparse linear algebra (:mod:`scipy.sparse.linalg`) ================================================== .. currentmodule:: scipy.sparse.linalg Abstract linear operators ------------------------- .. autosummary:: :toctree: generated/ LinearOperator -- abstract r...
from reversion.admin import VersionAdmin from django.contrib.gis import admin from .models import Feedback,Topic @admin.register(Feedback) class FeedbackAdmin(VersionAdmin, admin.ModelAdmin): model = Feedback list_display = ['name', 'email', 'topic', 'message'] save_as = True ordering = ['topic'] @admin...
import py from rpython.rlib.jit import JitDriver, hint, set_param from rpython.rlib.jit import unroll_safe, dont_look_inside, promote from rpython.rlib.objectmodel import we_are_translated from rpython.rlib.debug import fatalerror from rpython.jit.metainterp.test.support import LLJitMixin from rpython.jit.codewriter.po...
"""Top-level module for releng-sop."""
from datetime import datetime, timedelta from django.db import models from election.models import ElectionManager from exception.models import handle_exception, handle_record_found_more_than_one_exception,\ handle_record_not_found_exception, handle_record_not_saved_exception, print_to_log from issue.models import I...
import getpass try: assert raw_input except NameError: raw_input = input def prompt(name, default=None): """ Grab user input from command line. :param name: prompt text :param default: default value if no input provided. """ prompt = name + (default and ' [%s]' % default or '') promp...
import unittest from stomp import backward3 class TestBackward3(unittest.TestCase): def test_pack_mixed_string_and_bytes(self): lines = ['SEND', '\n', 'header1:test', '\u6771'] self.assertEqual(backward3.encode(backward3.pack(lines)), b'SEND\nheader1:test\xe6\x9d\xb1') ...
import collections class Change(object): def __init__(self): super(Change, self).__init__() def makeChange(self, change): coinVaulues = collections.OrderedDict() coinVaulues['h'] = 50 coinVaulues['q'] = 25 coinVaulues['d'] = 10 coinVaulues['n'] = 5 coinVaulues['p'] = 1 coins = {} ...
from __future__ import unicode_literals from base64 import b64encode, b64decode import datetime import copy import json from django.conf import settings from django.http import HttpResponse, HttpResponseBadRequest, HttpResponseNotFound, HttpResponseNotAllowed from gripcontrol import Channel, HttpResponseFormat, HttpStr...
from verta._swagger.base_type import BaseType class UacGetOrganizationByIdResponse(BaseType): def __init__(self, organization=None): required = { "organization": False, } self.organization = organization for k, v in required.items(): if self[k] is None and v: raise ValueError('attr...
from fibonacci import Fibonacci def ans(): return Fibonacci.index(Fibonacci.after(int('9' * 999))) if __name__ == '__main__': print(ans())
import yaml def main(): #f = open("data.yaml", "r") f = open("data2.yaml", "r") yd = yaml.load(f) #print "YAML Data: %s" % str(yd) for key in yd: print "%s" % key print "Type: %s" % str(type(yd[key])) print str(yd[key]) print "" def yaml_test(): #f = open("data.ya...
import zmq import random import time def run(): context = zmq.Context() sender = context.socket(zmq.PUSH) sender.bind('tcp://*:5557') sink = context.socket(zmq.PUSH) sink.connect('tcp://localhost:5558') print 'Press Enter when the workers are ready: ' _ = raw_input() print('sending tasks...
from __future__ import absolute_import, print_function, division import copy import os import re import urwid from mitmproxy import filt from mitmproxy import script from mitmproxy import utils from mitmproxy.console import common from mitmproxy.console import signals from netlib.http import cookies from netlib.http im...
import BeautifulSoup import requests import time cm_time_format = '%a %Y-%m-%d %H:%M:%S' def get_status(baseurl): # Retrieve and process the page from the modem url = baseurl + 'status_cgi' pagedata = requests.get(url).content timestamp = time.time() # Get the time immediately after retrieval bs = B...
import logging from src.settings import JINJA_ENVIRONMENT from src.base import BaseHandler from src.main.models import Torrent, UserTorrent from google.appengine.ext import ndb from google.appengine.api import users import arrow from time import sleep class IndexPage(BaseHandler): def get(self): # new movie...
from django.shortcuts import render from rest_framework import viewsets from waterfall_wall.serializers import ImageSerializer from waterfall_wall.models import Image def index(request): context = {} return render(request, 'waterfall_wall/index.html', context) class ImageViewSet(viewsets.ModelViewSet): """ ...
from django.core.management.base import BaseCommand from django.contrib.auth.models import User from photos.models import PhotoSceneCategory from photos.add import add_photo class Command(BaseCommand): args = '<flickr_dir>' help = 'Adds photos from flickr' def handle(self, *args, **options): admin_u...
from __future__ import print_function import sys from pandas.core.base import PandasObject from pandas.core.common import adjoin, notnull from pandas.core.index import Index, MultiIndex, _ensure_index from pandas import compat from pandas.compat import(StringIO, lzip, range, map, zip, reduce, u, ...
""" Custom made pose attribute for simulation """ import math from vector_3 import Vector3 from polar_vector import PolarVector class Pose: def __init__(self): self.position = Vector3() self.velocity = PolarVector()
import glob import imp import sys import os import radical.utils as ru import pprint import subprocess as sp script_dir = os.path.dirname(os.path.realpath(__file__)) cmd = "git branch | grep '*' | cut -f 2 -d \ " \ + " | sed -e 's/readthedocs.tutorial/tutorial/g' " \ + " | sed -e 's/readthedocs/release/g'" myta...
import os import webapp2 from mako.template import Template from mako.lookup import TemplateLookup class MainHandler(webapp2.RequestHandler): def get(self): template_values = { 'some_foo': 'foo', 'some_bar': 'bar' } # the template file in our GAE app directory path = os.path.join(os.path.d...
import time, sys import numpy as np import matplotlib.pyplot as plt sys.path.append('../../') from py2Periodic.physics import twoLayerQG from numpy import pi params = { 'f0' : 1.0e-4, 'Lx' : 1.0e6, 'beta' : 1.5e-11, 'defRadius' : 1.5e4, 'H1' : 500.0, 'H2' :...
from __future__ import unicode_literals from rbpkg.package_manager.dep_graph import DependencyGraph from rbpkg.testing.testcases import TestCase class DependencyGraphTests(TestCase): """Unit tests for rbpkg.package_manager.dep_graph.DependencyGraph.""" def test_iter_sorted_simple(self): """Testing Depen...
import docker from cargo.container import Container from cargo.image import Image RESERVED_METHODS = ['containers', '_client', 'images', 'info', 'start', 'stop'] class Dock(object): """Wrapper class for `docker-py` Client instances""" def __init__(self, *args, **kw): super(Dock, self).__init__() self._clien...
""" Copyright: (c) 2012-2014 Artem Nezvigin <artem@artnez.com> License: MIT, see LICENSE for details """ from functools import wraps from flask import g, request, session, render_template, url_for, redirect from faceoff.models.user import find_user def templated(template_name=None): """ Automatically renders a ...
from holmesalf import BaseAuthNZWrapper from alf.client import Client as AlfSyncClient from tornadoalf.client import Client as AlfAsyncClient class AlfAuthNZWrapper(BaseAuthNZWrapper): """This class gathers authentication and authorization for some of the services used by Holmes""" def __init__(self, config...
""" read-bookmark.py ~~~~~~~~~~~~~~~~ This module is an example of how to harness the Readability API w/ oAuth. This module expects the following environment variables to be set: - READABILITY_CONSUMER_KEY - READABILITY_CONSUMER_SECRET - READABILITY_ACCESS_TOKEN - READABILITY_ACCESS_SECRET Once you have your consumer k...
from flask import render_template from . import main @main.app_errorhandler(404) def page_not_found(e): return render_template('404.html'), 404 @main.app_errorhandler(500) def internal_server_error(e): return render_template('500.html'), 500
from unittest import TestCase from paramiko import SSHException from pyinfra.api import Config, State from pyinfra.api.connect import connect_all from pyinfra.api.exceptions import NoGroupError, NoHostError, PyinfraError from ..paramiko_util import PatchSSHTestCase from ..util import make_inventory class TestInventoryA...
import click import mock import pytest from click.testing import CliRunner from sigopt.cli import cli class TestRunCli(object): @pytest.mark.parametrize('opt_into_log_collection', [False, True]) @pytest.mark.parametrize('opt_into_cell_tracking', [False, True]) def test_config_command(self, opt_into_log_collection...
import unittest import ezgal.zf_grid import numpy as np import math import tests.zf_grid class test_get_rest_mags(tests.zf_grid.test_zf_grid): def test_get_rest_mags(self): self.assertTrue(np.allclose( self.zf_grid.get_rest_mags(tests.zf_grid.test_zs), [0.275, 0.75, 1.25, 1.75, 2.25,...
from __future__ import absolute_import import os import ming from ming import Session from ming.odm import ThreadLocalODMSession from ming import create_datastore from depot.fields.ming import DepotExtension mainsession = Session() DBSession = ThreadLocalODMSession(mainsession, extensions=(DepotExtension, )) database_s...
from __future__ import absolute_import, division, print_function import ast from jaspyx.ast_util import ast_load, ast_call from jaspyx.visitor import BaseVisitor class BinOp(BaseVisitor): def visit_BinOp(self, node): attr = getattr(self, 'BinOp_%s' % node.op.__class__.__name__, None) attr(node.left,...
import argparse import collections import json import string import sys header_template = """ $header_front $begin_namespace enum class Token { $tokens }; enum class Nonterminal { $nonterminals }; enum class Production { $productions }; struct Lexer_State { const char* begin; const char* end; unsigned int l...
class Solution(object): def convertToTitle(self, n): """ :type n: int :rtype: str """ return "" if n == 0 else self.convertToTitle((n - 1) / 26) + chr((n - 1) % 26 + ord('A'))
import requests import json import time import subprocess import re import os from collections import OrderedDict from test_framework.test_framework import OpenBazaarTestFramework, TestFailure from test_framework.smtp_server import SMTP_DUMPFILE class SMTPTest(OpenBazaarTestFramework): def __init__(self): s...
__author__ = 'djw' class FieldNodeItem(object): """ An item built on a player's field board, held within a node/cell on that board """ def __init__(self): self.cattle = 0 self.boars = 0 self.sheep = 0 self.grain = 0 self.vegetables = 0 def update_animals(self,...
class Solution: def reverseList(self, head: ListNode) -> ListNode: current = head previous = None while current is not None: temp = current.next current.next = previous previous = current current = temp return previous
import warnings class Yaku: yaku_id = None tenhou_id = None name = None han_open = None han_closed = None is_yakuman = None def __init__(self, yaku_id=None): self.tenhou_id = None self.yaku_id = yaku_id self.set_attributes() def __str__(self): return self....
from os import system, chdir, getcwd from sys import argv import subprocess build_cmd = argv[1]; dep_dir = argv[2]; src_dir = argv[3]; test_dir = argv[4]; rev = argv[5]; if (len(argv) < 7): out_dir = test_dir + "-" + rev; else: out_dir = argv[6]; work_dir = "__tmp" + rev; system("cp -rf " + src_dir + " " + work...
import os from datetime import datetime from math import ceil from Bio.PDB import PDBList from Bio.PDB.PDBParser import PDBParser from Bio.PDB.MMCIFParser import MMCIFParser start = datetime.now() basedir = "." pdbl = PDBList() pdblist = pdbl.get_all_entries() outstrs = ["Checking all PDB entries at {}".format(start.is...
import rosbag from sensor_msgs.msg import PointCloud2 def pc_filter(topic, datatype, md5sum, msg_def, header): if datatype == 'sensor_msgs/PointCloud2': return True return False class MockCamera(object): """A MockCamera reads saved point clouds. """ def __init__(self): pass def r...
''' Contains Vmstat() class Typical contents of vmstat file:: nr_free_pages 1757414 nr_inactive_anon 2604 nr_active_anon 528697 nr_inactive_file 841209 nr_active_file 382447 nr_unevictable 7836 nr_mlock 7837 nr_anon_pages 534070 nr_mapped 76013 nr_file_pages 1228693 nr_dirty 21 nr_wr...
""" The output tab for the main toolbar @author: Chris Scott """ from __future__ import print_function from __future__ import absolute_import from __future__ import unicode_literals import os import shutil import subprocess import copy import logging import math import functools import datetime import time import numpy...
import logging import os import pkg_resources import sys import ConfigParser from paste.deploy import loadapp, loadwsgi SERVER = loadwsgi.SERVER from gunicorn.app.base import Application from gunicorn.config import Config class PasterBaseApplication(Application): def app_config(self): cx = loadwsgi.loadcont...
from flask import Flask, jsonify, request, abort, render_template app = Flask(__name__) @app.route("/",methods=['GET']) def index(): if request.method == 'GET': return render_template('index.html') else: abort(400) @app.route("/devices",methods=['GET']) def devices(): if request.method == 'GET': retur...
''' Stores syntax file from last activated view and reuses this for a new view. @author: Oktay Acikalin <ok@ryotic.de> @license: MIT (http://www.opensource.org/licenses/mit-license.php) @since: 2011-03-05 @todo: Remove odd workaround below when/if "on_deactivated", "on_new" and "on_activated" events get fired in...
import numpy as np from Other_samples.testCases import * from Other_samples.Gradient_check.gc_utils import sigmoid, relu, dictionary_to_vector, vector_to_dictionary, \ gradients_to_vector def forward_propagation(x, theta): """ Implement the linear forward propagation (compute J) presented in Figure 1 (J(the...
"""Axis class and associated.""" import re import numexpr import operator import functools import numpy as np from .. import exceptions as wt_exceptions from .. import kit as wt_kit from .. import units as wt_units __all__ = ["Axis"] operator_to_identifier = {} operator_to_identifier["/"] = "__d__" operator_to_identifi...
import sys import os import shlex import sphinx.environment from docutils.utils import get_source_line def _warn_node(self, msg, node): if not msg.startswith('nonlocal image URI found:'): self._warnfunc(msg, '%s:%s' % get_source_line(node)) sphinx.environment.BuildEnvironment.warn_node = _warn_node sys.path...
import asyncio import collections import logging import aiohttp import typing from lbry import utils from lbry.conf import Config from lbry.extras import system_info ANALYTICS_ENDPOINT = 'https://api.segment.io/v1' ANALYTICS_TOKEN = 'Ax5LZzR1o3q3Z3WjATASDwR5rKyHH0qOIRIbLmMXn2H=' SERVER_STARTUP = 'Server Startup' SERVER...