content stringlengths 0 894k | type stringclasses 2
values |
|---|---|
#!/usr/bin/env python3
import os
import sys
import json
import zipfile
import datetime
import shutil
from wearebeautiful import model_params as param
MAX_SCREENSHOT_SIZE = 256000 # 256Kb is enough!
bundles_json_file = "bundles.json"
def bundle_setup(bundle_dir_arg):
''' Make the bundle dir, in case it doesn't e... | python |
from flask import render_template, flash, redirect, url_for, session, Markup
from flask_login import login_user, logout_user, login_required
from app import app, db, lm
from app.models.forms import *
from app.models.tables import *
@lm.user_loader
def load_user(id):
return Usuario.query.filter_by(id=id).first()
... | python |
import logging
import paho.mqtt.client as mqtt
import time
# from utils_intern.messageLogger import MessageLogger
logging.basicConfig(format='%(asctime)s %(levelname)s %(name)s: %(message)s', level=logging.DEBUG)
logger = logging.getLogger(__file__)
class MQTTClient:
def __init__(self, host, mqttPort, client_id... | python |
from gym_trafficnetwork.envs.parallel_network import Cell
import numpy as np
# For the simplest road type
def homogeneous_road(num_cells, vfkph, cell_length, num_lanes):
r = []
for _ in range(num_cells):
r.append(Cell(vfkph, cell_length, num_lanes))
return r
# For roads who have cells with the number of lanes a... | python |
import re
import typing as tp
from time import time
from loguru import logger
def time_execution(func: tp.Any) -> tp.Any:
"""This decorator shows the execution time of the function object passed"""
def wrap_func(*args: tp.Any, **kwargs: tp.Any) -> tp.Any:
t1 = time()
result = func(*args, **k... | python |
import os
import time
import argparse
import numpy as np
import cv2
from datetime import datetime
import nnabla as nn
import nnabla.functions as F
import nnabla.parametric_functions as PF
import nnabla.solvers as S
import nnabla.logger as logger
import nnabla.utils.save as save
from nnabla.monitor import Monitor, Moni... | python |
# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: get_app_health_config_v2.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from go... | python |
#!/usr/bin/env python
import os
import sys
import visa
import time
#-------------------------------------------------------------#
## main function
# @param there is no parameter for main function
def main():
rm = visa.ResourceManager()
print rm.list_resources()
instr1 = rm.open_resource('USB0::0x05E6::0x2280::410... | python |
import os, time
from this import d
import numpy as np
import pandas as pd
import tensorflow as tf
from sklearn.preprocessing import MinMaxScaler
from datetime import datetime, timedelta
from detector import detect_anomaly
from decomposition import load_STL_results, decompose_model
from models import *
from data_loade... | python |
import datetime
import time
from open_publishing.core.enums import EventTarget, EventAction, EventType
class Events(object):
def __init__(self,
ctx):
self._ctx = ctx
def get(self,
references=None,
target=None,
action=None,
type=None,
... | python |
def add(x, y):
return x + y
def double(x):
return x + x | python |
import math
import datetime
block_size = 0.5
def block_name(lat, lon):
discretized_lat = (math.floor(lat/block_size)+0.5)*block_size
discretized_lon = (math.floor(lon/block_size)+0.5)*block_size
return (discretized_lat, discretized_lon)
def inside_polygon(x, y, points):
"""
Return True if a coord... | python |
"""
Results represent Prefect Task inputs and outputs. In particular, anytime a Task runs, its output
is encapsulated in a `Result` object. This object retains information about what the data is, and how to "handle" it
if it needs to be saved / retrieved at a later time (for example, if this Task requests for its out... | python |
import numpy
import pytest
from pauxy.systems.ueg import UEG
from pauxy.estimators.ueg import fock_ueg, local_energy_ueg
from pauxy.estimators.greens_function import gab
from pauxy.utils.testing import get_random_wavefunction
from pauxy.utils.misc import timeit
@pytest.mark.unit
def test_fock_build():
sys = UEG({'... | python |
import subprocess
host = ["www.google.com", "192.0.0.25"]
rounds = 32
ping = subprocess.Popen(
["ping", "-c", str(rounds), host[1]],
stdout = subprocess.PIPE,
stderr = subprocess.PIPE
)
out, error = ping.communicate()
print "Out : %s"%out
import re
matcher = re.compile("rtt min/avg/max/m... | python |
#!/usr/bin/env python3
# This script is used to avoid issues with `xcopy.exe` under Windows Server 2016 (https://github.com/moby/moby/issues/38425)
import glob, os, shutil, sys
# If the destination is an existing directory then expand wildcards in the source
destination = sys.argv[2]
if os.path.isdir(destination) == T... | python |
from django.urls import reverse
from rest_framework import status
from rest_framework.test import APITestCase
class TicketTests(APITestCase):
def setUp(self):
"""
Configurations to be made available before each
individual test case inheriting from this class.
"""
url = reve... | python |
from interface import create_new_user
import unittest
from passlock import User,Credentials
class TestClass(unittest.TestCase):
'''
A Test class that defines test case for the user behaviour
'''
def setUp(self) :
'''
set up mehtod that runs each testcase
'''
self.new_us... | python |
import unittest
import numpy as np
import theano
import theano.tensor as T
from daps.model import weigthed_binary_crossentropy
class test_loss_functions(unittest.TestCase):
def test_weigthed_binary_crossentropy(self):
w0_val, w1_val = 0.5, 1.0
x_val, y_val = np.random.rand(5, 3), np.random.randi... | python |
''' Filters that operate on ImageStim inputs. '''
import numpy as np
from PIL import Image
from PIL import ImageFilter as PillowFilter
from pliers.stimuli.image import ImageStim
from .base import Filter
class ImageFilter(Filter):
''' Base class for all ImageFilters. '''
_input_type = ImageStim
class Ima... | python |
#
# @lc app=leetcode.cn id=206 lang=python3
#
# [206] 反转链表
#
# https://leetcode-cn.com/problems/reverse-linked-list/description/
#
# algorithms
# Easy (58.01%)
# Total Accepted: 38.9K
# Total Submissions: 66.5K
# Testcase Example: '[1,2,3,4,5]'
#
# 反转一个单链表。
#
# 示例:
#
# 输入: 1->2->3->4->5->NULL
# 输出: 5->4->3->2->1->N... | python |
# encoding: utf-8
"""Test utility functions."""
from unittest import TestCase
import os
from viltolyckor.utils import parse_result_page
from requests.exceptions import HTTPError
DATA_DIR = "tests/data"
class TestUtils(TestCase):
def setUp(self):
pass
def test_parse_result_page(self):
file_p... | python |
# -*- coding: utf-8 -*-
"""
*** Same as its parent apart that text baselines are reflected as a LineString (instead of its centroid)
DU task for ABP Table:
doing jointly row BIO and near horizontal cuts SIO
block2line edges do not cross another block.
The cut are based on baseli... | python |
import pytest
from pybatfish.client.session import Session
from pybatfish.datamodel import PathConstraints, HeaderConstraints
from test_suite.sot_utils import (SoT, BLOCKED_PREFIXES, SNAPSHOT_NODES_SPEC, OPEN_CLIENT_PORTS)
@pytest.mark.network_independent
def test_no_forwarding_loops(bf: Session) -> None:
"""Ch... | python |
"""Externalized strings for better structure and easier localization"""
setup_greeting = """Dwarf - First run configuration
Insert your bot's token, or enter 'cancel' to cancel the setup:"""
not_a_token = "Invalid input. Restart Dwarf and repeat the configuration process."
choose_prefix = """Choose a prefix. A pref... | python |
#coding=utf-8
from django.conf.urls import patterns, url, include
from cmdb.views import contract
urlpatterns = patterns('',
url(r'^$', contract.list_contract, name='contract_index'),
url(r'add/$', contract.add_contract, name='add_contract'),
url(r'del/(?P<contract_id>\d+)/$', contract.del_contract, na... | python |
## Problem: Finding Numbers in a Haystack
# use regex library
import re
# open file for reading
# save the file into the same directory
textfile_handle = open("regex_sum_42.txt")
# list of all numbers found so far
num_all_list = list()
# read through and parse a file with text and numbers
# loop over every line of ... | python |
from numpy import asarray
from datetime import datetime, timedelta
from PyQt5.QtCore import Qt
from PyQt5.QtChart import QChart, QLineSeries, QBarCategoryAxis, QValueAxis
from PyQt5.QtGui import QPainter
from core import AppCore
from widget.GeometryRestoreWidget import GeometryRestoreWidget
from gen.ui_AnalysisWidget ... | python |
# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: task.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import... | python |
import os
DB_HOST = os.environ["REDIS_HOST"]
DB_PORT = int(os.environ["REDIS_PORT"])
DB_NAME = int(os.environ["REDIS_ID"])
DB_QUEUE = os.environ["INPUT_QUEUE"]
BATCH_SIZE = 16
SERVER_SLEEP = 0.25
| python |
#!/usr/bin/env python
import roslib
import rospy
import math
import time
import numpy as np
import os
from std_msgs.msg import Int32MultiArray
from std_msgs.msg import Int32
from rospy_tutorials.msg import Floats
from gpiozero import PWMOutputDevice
#initialize all variables
#current positon
Xc=0
Yc=0
#fi... | python |
from datetime import datetime
from django import forms
from .models import Location
class StrikeFilterForm(forms.Form):
daterange = forms.CharField(label='Date', max_length=23)
country__name = forms.ChoiceField(label='Country', choices=())
province = forms.CharField(label='Province', max_length=100, requi... | python |
"""Model generation"""
from abc import ABC
from collections import namedtuple
from copy import copy
import functools
import itertools
import numpy as np
from scipy.special import expit # pylint: disable = no-name-in-module
import sympy
from sympy.utilities.lambdify import lambdify
from synmod import constants
from ... | python |
# -*- coding: UTF-8 -*-
# Copyright 2011-2018 Rumma & Ko Ltd
# License: BSD (see file COPYING for details)
"""Desktop UI for this plugin.
Documentation is in :doc:`/specs/users` and :doc:`/dev/users`
"""
from __future__ import unicode_literals
from textwrap import wrap
from django.conf import settings
from django.d... | python |
"""
Checks the bam header:
* to make sure all rgs have the same sample
* enforce PL to be ILLUMINA
Writes out a new header with the aliquot submitter id as the SM
and/or PL as ILLUMINA as needed.
@author: Kyle Hernandez
"""
import os
import time
import sys
import pysam
import argparse
import logging
PLATFORM = "ILL... | python |
from AndroidFTPBackup.utils import FileHelper, ConfigHelper
configHelper: ConfigHelper = None
fileHelper: FileHelper = None
| python |
# python3
import sys, threading
from collections import deque
def compute_height_brute_force(n, parents):
# Replace this code with a faster implementation
max_height = 0
for vertex in range(n):
height = 0
current = vertex
while current != -1:
height += 1
curr... | python |
import time
import pickle # To work with cookies
import json
from selenium.webdriver.support.wait import WebDriverWait
class Login():
def __init__(self, driver, profile, password):
self.profile = profile
self.driver = driver
self.password = password
def run(self):
self.driver... | python |
a = (2 ** 2)
b = (2 ** 2)
c = 2
print("a ** b ** c =", a ** b ** c)
| python |
# Code adapted from Fei Xia
import glob
import os
import cv2
import meshcut
import numpy as np
from tqdm import tqdm
from PIL import Image
def load_obj_np(filename_obj, normalization=False, texture_size=4, load_texture=False,
texture_wrapping='REPEAT', use_bilinear=True):
"""Load Wavefront .ob... | python |
import os.path
import ranger.api
import ranger.core.fm
import ranger.ext.signals
from subprocess import Popen, PIPE
hook_init_prev = ranger.api.hook_init
def hook_init(fm):
def zoxide_add(signal):
path = signal.new.path
process = Popen(["zoxide", "add", path])
process.wait()
fm.signal... | python |
from __future__ import division
# These functions have their own module in order to be compiled with the right
# __future__ flag (and be tested alongside the 2.x legacy division operator).
def truediv_usecase(x, y):
return x / y
def itruediv_usecase(x, y):
x /= y
return x
| python |
# Copyright 2017 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | python |
"""
Manage sound and music
"""
from engine.const import CONST
snd_manager = None
class SndManager():
def __init__(self):
self.sounds = {}
self.permanent_sound = []
self.playlist = []
self.music_index = 0
self.music = None
self.sounds_playing = []
def set_play... | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import base
import cw
class Summary(base.CWBinaryBase):
"""見出しデータ(Summary.wsm)。
type:見出しデータには"-1"の値を付与する。
"""
def __init__(self, parent, f, yadodata=False, nameonly=False, materialdir="Material", image_export=True,
wpt120=Fa... | python |
from django.urls import path
from moim.views import *
urlpatterns = [
path('', MoimView.as_view()),
path('<int:moim_id>/', MoimDetailView.as_view()),
path('<int:moim_id>/apply/', MoimApplyView.as_view())
]
| python |
#
# PySNMP MIB module PPP-SEC-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/PPP-SEC-MIB
# Produced by pysmi-0.3.4 at Wed May 1 14:41:52 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 0... | python |
import random
import math
Menor = int(input("Insira o menor limite : "))
Maior = int(input("Insira o maior limite : "))
## Retorna um número entre os x e y (Os 2 inclusos)
Rand = random.randint(Menor,Maior)
# Número mínimo de adivinhação = log 2 (limite superior - limite inferior + 1)
print("\n\t\tVocê tem apena... | python |
class News:
def __init__(self,title,description,urlToImage,content,url):
self.title=title
self.description=description
self.urlToImage=urlToImage
self.content=content
self.url=url
class Sources:
def __init__(self, id, name, description, url, category):
self.id =... | python |
"""Some utilities for caching pages."""
import zlib
from beaker.util import func_namespace
from mako.runtime import capture
def cache_content(request, key, do_work):
"""Argh!
Okay, so. Use this when you want to cache the BODY of a page but not
the CHROME (i.e., wrapper or base or whatever).
``requ... | python |
import os
import pickle
import numpy as np
import soundfile as sf
from scipy import signal
from scipy.signal import get_window
import librosa
from librosa.filters import mel
from numpy.random import RandomState
from pathlib import Path
import ipdb
from tqdm import tqdm
def butter_highpass(cutoff, fs, order=5):
nyq... | python |
import tkinter as tk
from tkinter import messagebox as mbox
from tkinter import filedialog
from Phase0 import phase0
from Phase0_1 import phase0_1
from Phase1 import phase1
from Phase2 import phase2
from Phase3 import phase3
from form_viewer import form_viewer
#Tk class generating
root = tk.Tk()
# screen size
ro... | python |
import numpy as np
import os
import tensorflow as tf
from sandbox.rocky.tf.optimizers.conjugate_gradient_optimizer import FiniteDifferenceHvp, ConjugateGradientOptimizer
from hgail.algos.gail import GAIL
import auto_validator
import hyperparams
import utils
# setup
args = hyperparams.parse_args()
exp_dir = utils.s... | python |
# Copyright (c) 2019, CMCC Technologies Co., Ltd.
# Copyright (c) 2019, ZTE Corporation.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless... | python |
# Computes the transition temperature Tc from the temperature dependence of the leading
# Bethe-Salpeter eigenvalue.
#
# Usage: python compute_tc.py T=*
#
# Author: Urs R. Haehner (haehneru@itp.phys.ethz.ch)
import numpy as np
from scipy import optimize
from matplotlib import pyplot as plt
import h5py
import os
import... | python |
import numpy as np
import openslide
import sys
import os
from PIL import Image
from color_norm.color_normalize import reinhard_normalizer
def white_ratio(pat):
white_count = 0.0
total_count = 0.001
for x in range(0, pat.shape[0]-200, 100):
for y in range(0, pat.shape[1]-200, 100):
p = p... | python |
import win32ui
import pyautogui
from win10toast import ToastNotifier
path = pyautogui.prompt('Please enter the path below:')
path = path+"/?"
pyautogui.keyDown("win")
pyautogui.press("r")
pyautogui.keyUp("win")
pyautogui.typewrite("cmd")
pyautogui.press("enter")
pyautogui.press("enter")
pyautogui.typ... | python |
# Copyright 2021 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | python |
from lib.base import PowerDNSClient
class SuggestZone(PowerDNSClient):
def _run(self, *args, **kwargs):
return self.api.suggest_zone(*args, **kwargs)
| python |
"""
The :mod:`websockets.server` module defines a simple WebSocket server API.
"""
import asyncio
import collections.abc
import email.message
import logging
from .compatibility import asyncio_ensure_future
from .exceptions import InvalidHandshake, InvalidOrigin
from .handshake import build_response, check_request
fr... | python |
import os
from pylearn2.utils import serial
from theano import tensor as T
from theano import function
from pylearn2ext.chbmit import CHBMIT
from tests.plot_eeg import plot_eeg_predict_seizure_period
def predict_plot(model_path, dataset):
"""
Script to perform seizure detection and plot the results.
Pa... | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import logging
import os
import random
import time
class IdWorker(object):
def __init__(self, worker_id, host_id):
self.worker_id = worker_id
self.host_id = host_id
self.logger = logging.getLogger("idworker")
# stats
self.ids... | python |
""" CPG locomotion controller. """
import itertools
import os
from argparse import ArgumentParser
from pathlib import Path
import farms_pylog as pylog
import matplotlib.pyplot as plt
import networkx as nx
import numpy as np
import yaml
from farms_container import Container
from farms_network.networkx_model import Net... | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import sys
import socket
import threading
import datetime
#from threading import Lock
from Utils import DebugLock as Lock
from Utils import Utils
try:
from Event import Event
from NaptSocket import NaptSocket, NaptSocketStatus
from NaptConnectionEve... | python |
import cv2
cap = cv2.VideoCapture(0)
fgbg =cv2.createBackgroundSubtractorMOG2()
while (1):
ret, frame = cap.read()
fgmask = fgbg.apply(frame)
edges = cv2.Canny(fgmask,100,200)
cv2.imshow('Original', frame)
cv2.imshow('MOG2', fgmask)
cv2.imshow('Output', edges)
k = cv2.waitKey(30) & 0xff
if k == 27:
break
... | python |
import argparse
import logging
import string
import jsonlines
from Levenshtein import distance
from tqdm.auto import tqdm
from src.models.bart_seq2seq_kilt import BartSeq2Seq
from src.models.bert_binary_kilt import BertBinary
from src.utils import batch_it, chunk_it
def normalize(sent):
return (
sent.lo... | python |
from ._base import *
from ..tinygrail.bigc import BigC
from ..tinygrail.model import TBid
@click.command()
@click.argument("player_name", type=TG_PLAYER)
@click.argument("character_ids", type=int, nargs=-1)
def force_view(player_name, character_ids):
for cid in character_ids:
big_c = BigC(player_name, cid... | python |
from algosdk.v2client.indexer import IndexerClient
from algosdk.v2client.algod import AlgodClient
from tinyman.v1.client import TinymanMainnetClient
from tinyman.v1.pools import get_pool_info_from_account_info
import datetime
import statistics
class AlgoTools:
def __init__(self, address = None):
### Setup ... | python |
#!/usr/bin/env python
import unittest
class test_sample_hook(unittest.TestCase):
def test_nothing(self):
#do nothing
return
| python |
# coding: utf-8
import responses
import os
import json
import io
import watson_developer_cloud
from watson_developer_cloud.discovery_v1 import TrainingDataSet, TrainingQuery, TrainingExample
try:
from urllib.parse import urlparse, urljoin
except ImportError:
from urlparse import urlparse, urljoin
base_discove... | python |
import glob
import datetime
import string
import pandas as pd
current_year = datetime.datetime.today().year
def age_binner(age):
if age < 5:
return "04 and under"
elif 5 <= age <= 9:
return "05 to 09 years"
elif 10 <= age <= 14:
return "10 to 14 years"
elif 15 <= age <= 19:
... | python |
class MethodsManager:
"""My Methods Manager
"""
def __init__(self):
self.heap = {}
def insert(self, elems):
"""Insert for main
Args:
elems (list): Tokens form user input
"""
if elems[1][0].isupper():
name = elems[1]
# I have ... | python |
from dataclasses import asdict
from dataclasses import dataclass
from dataclasses import field
from typing import List
from unittest import mock
from unittest.case import TestCase
from lxml.etree import Element
from lxml.etree import QName
from tests.fixtures.books import BookForm
from tests.fixtures.books import Boo... | python |
# Morando Nicolò
import pandas as pd
file_path = 'filepath.csv'
data = pd.read_csv(file_path)
data.describe()
| python |
# 0611.py
"""
ref: https://gist.github.com/jsheedy/3913ab49d344fac4d02bcc887ba4277d
ref: http://felix.abecassis.me/2011/09/opencv-morphological-skeleton/
"""
import cv2
import numpy as np
#1
src = cv2.imread('./data/T.jpg', cv2.IMREAD_GRAYSCALE)
##src = cv2.imread('alphabet.bmp', cv2.IMREAD_GRAYSCALE)
#... | python |
import dicom
import argparse
import pylab
import os
import tqdm
parser = argparse.ArgumentParser(description="由dicom格式文件生成png图片")
parser.add_argument("origin", help="文件源路径(文件或文件夹)")
parser.add_argument("--output", "-o", help="输出路径", default="./")
argv = parser.parse_args()
def get_path_filelist(path):
files = ... | python |
import platform
from selenium.webdriver import Chrome, DesiredCapabilities
from selenium.webdriver.chrome.options import Options
from tests.util.web.platform.browser.generic import ManagedBrowser
class ChromeManagedBrowser(
ManagedBrowser
):
"""
ChromeManagedBrowser provides a Chrome edition of ManagedT... | python |
from __future__ import absolute_import
# import models into model package
from .v1_persistent_volume import V1PersistentVolume
from .v1_tcp_socket_action import V1TCPSocketAction
from .v1_resource_quota_status import V1ResourceQuotaStatus
from .v1_container_state_terminated import V1ContainerStateTerminated
from .v1_r... | python |
from .logger import get_logger
| python |
from django.test import TestCase
from django.core.management import call_command
from databuilder.tests import utils
from databuilder import models
# noinspection SpellCheckingInspection
sample_name = 'Bob Bobski'
class TestTask1(TestCase):
def setUp(self):
self.model_name = models.SampleTest.__name__.l... | python |
import argparse
import os
import xml.etree.ElementTree as ET
import sys
import configparser
import os
from os import path
import codecs
import re
parser = argparse.ArgumentParser()
parser.add_argument("-raw_path", default='../raw_data/xml/schaeftlarn')
parser.add_argument("-save_path", default='../raw_data/stories/la'... | python |
#name: CurateChemStructures
#description: curating a molecules set for structural data homogenization
#top-menu: Chem | Curate...
#language: python
#sample: chem/chem_standards.csv
#tags: demo, chem, rdkit
#input: dataframe data [Input data table]
#input: column smiles {type:categorical; semType: Molecule} [Molecules,... | python |
import json
import falcon
class HealthCheck:
def on_get(self, req, resp):
resp.body = json.dumps({'status': 'happy and health!'})
resp.status = falcon.HTTP_200
| python |
import attr
from operator import itemgetter, methodcaller, attrgetter
from django.conf import settings
import spacy
from .service import Service
from .states import states
from .loaders import table_loader
from .language_model import nlp
from ..forms import QuestionForm
@attr.s
class NlpMiddleware:
get_respon... | python |
# -*- coding: utf-8 -*-
"""
This module contains all functions for response of optical elements.
Created on Wed May 22 12:15:23 2019
@author: Swarnav Banik
sbanik1@umd.edu
"""
import numpy as np
import numpy.fft as fourier
import scipy as scp
from PIL import Image
# %% Common Functions ####################... | python |
# -*- coding: utf-8 -*-
from __future__ import print_function
from __future__ import division
"""
Created on Fri May 4 13:43:46 2018
@author: xingshuli
"""
import os
from keras.optimizers import SGD
from keras.preprocessing.image import ImageDataGenerator
from keras import backend as K
#from NIN_16 import NIN16
#fro... | python |
from flask_login import current_user
from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, SubmitField, BooleanField, FileField
from wtforms.validators import DataRequired, Length, Email, EqualTo, ValidationError
from flask_wtf.file import FileField, FileAllowed, FileRequired
from app.models ... | python |
import ee
import geemap
# Create a map centered at (lat, lon).
Map = geemap.Map(center=[40, -100], zoom=4)
fromFT = ee.FeatureCollection("users/wqs/Pipestem/Pipestem_HUC10")
# This function computes the feature's geometry area and adds it as a property.
def addArea(feature):
return feature.set({'areaHa': feature.... | python |
import keras
# initializer = keras.initializers.glorot_uniform(seed=0)
initializer = keras.initializers.glorot_normal()
"""
Creates Residual Network with 50 layers
"""
def create_model(input_shape=(64, 64, 3), classes=1):
# Define the input as a tensor with shape input_shape
X_input = keras.lay... | python |
from typing import Union, List, Any
from ..core.client import ClientBase
from ..core.connect import AsyncTCPConnection
Key = Union[int, float, str]
class MasterClient(ClientBase):
def get_shard(self, key):
return self._execute("get_shard", key)
def get_map(self):
return self._execute("get_ma... | python |
from fastapi import APIRouter, HTTPException
import pandas as pd
import plotly.express as px
import numpy as np
import plotly.graph_objects as go
router = APIRouter()
@router.get('/vizprices')
async def visual():
# load in airbnb dataset
DATA_PATH = 'https://raw.githubusercontent.com/Air-BnB-2-BW/data-science... | python |
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function
from unittest import TestCase
from tests.utils import assert_equal_dict
from polyaxon_schemas.ml.hooks import StepLoggingTensorHookConfig
from polyaxon_schemas.ml.processing.pipelines import TFRecordSequencePipelineConfig
from p... | python |
from cereal import car
from common.realtime import DT_CTRL
from common.numpy_fast import clip
from common.params import Params
from selfdrive.car import apply_std_steer_torque_limits
from selfdrive.car.hyundai.hyundaican import create_lkas11, create_clu11, create_lfahda_mfc, \
... | python |
#!/usr/bin/env python3
# Copyright (c) 2019 The Khronos Group Inc.
# SPDX-License-Identifier: Apache-2.0
from itertools import product
from shared import PLATFORMS, TRUE_FALSE, VS_VERSION, make_win_artifact_name
if __name__ == "__main__":
for platform, uwp in product(PLATFORMS, TRUE_FALSE):
print(make_w... | python |
import tkinter as tk
class DashboardGUI:
def __init__(self, master, interpreter):
self.master = master
self.interpreter = interpreter
h = 316
w = 480
self.top_bar_canvas = tk.Canvas(master,bg="black",height=h,width=w/20)
self.top_bar_canvas.grid(row=0,column=0,rowspan=2)
self.time_text = self.top_bar_... | python |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import time, random
import numpy as np
import tensorflow as tf
from tensorflow.python.layers import core as layers_core
import argparse
from tensorflow.python.client import device_lib
import os
from u... | python |
import numpy as np
from ..Tools.Downloading._ReadDataIndex import _ReadDataIndex
from .. import Globals
def ReadIndex(subcomp,L,prod):
'''
Reads the index file for a given data product.
Inputs
======
subcomp : string
Name of sub component of instrument
L : int
Level of data to download
prod : str
Data p... | python |
# -*- coding: UTF-8 -*-
# A part of NonVisual Desktop Access (NVDA)
# Copyright (C) 2007-2020 NV Access Limited, Peter Vágner
# This file is covered by the GNU General Public License.
# See the file COPYING for more details.
import time
import nvwave
import threading
import queue
from ctypes import cdll
fro... | python |
import mock
import pytest
from django import forms
from django.db import models
from filer.models import Image
from barbeque.filer import FilerFileField, AdminFileFormField
from barbeque.tests.factories.filer import ImageFactory
class FileModel(models.Model):
file1 = FilerFileField(null=True)
file2 =... | python |
import shutil
from pathlib import Path
import dask.dataframe as dd
import numpy as np
import pandas as pd
from bokeh.io import export_png
from bokeh.io import output_file
from bokeh.models import Column
from bokeh.models import Div
from bokeh.plotting import figure
from bokeh.plotting import save
from sid.colors impor... | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.