text stringlengths 3.07k 12.6k |
|---|
# -*- coding: utf-8 -*- #
# Copyright 2018 Google LLC. 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 requir... |
"""
State-Action-Reward-State-Action (sars'a') learning algorithm implementation
"""
from __future__ import division, print_function, absolute_import
import theano.tensor as T
import theano
import numpy as np
from lasagne.objectives import squared_error
from .helpers import get_end_indicator, get_action_Qvalues
from... |
# -*- encoding: utf-8 -*-
# Testing new amara.tree API
# Testing quick reference examples
import unittest
import cStringIO
import amara
from amara.lib import testsupport
from amara import tree, xml_print
from amara import bindery
XML = '<a x="1"><b>i</b><c>j<d/>k</c><b>l</b></a>'
#self.assertEqual(doc[u'a'], doc.xml... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division
import numpy as np
from keras.utils.generic_utils import Progbar
from six.moves import xrange
class Agent(object):
"""Base Agent class
Parameters
----------
model : :obj:`Model`
A learning model. E... |
from kivy.compat import text_type
from kivy.core.window import Window
from kivy.metrics import dp
from kivy.properties import ListProperty, ObjectProperty, StringProperty
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.button import Button
from kivy.uix.popup import Popup
from kivy.uix.settings import SettingIte... |
from tkinter import *
from tkinter import ttk
from tkinter.ttk import Combobox
from tkinter.filedialog import askopenfilename
from tkinter.filedialog import askopenfilenames
from tkinter.filedialog import askdirectory
from tkinter.filedialog import asksaveasfilename
import tkinter.scrolledtext as scrolledtext
from base... |
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------... |
def ordena(lista, maior):
"""
Ordena 'lista' do maior para o menor, caso 'maior' seja True; caso
contrário, ordena do menor para o maior. Essa função modifica a lista
passada por parâmetro.
Parâmetros: lista de números ou strings e um booleano.
Retorna: nada.
"""
if maior:
for ... |
from pytest import raises, mark
import numpy as np
from beyond.io.ccsds import dumps, loads, CcsdsError
@mark.parametrize("kep", ("kep", "nokep"))
def test_dump_opm(orbit, datafile, ccsds_format, helper, kep):
kep = kep == "kep"
ref = datafile("opm", kep)
txt = dumps(orbit, fmt=ccsds_format, kep=kep)
... |
from ntptime import settime
import network
import machine
from TM1637 import TM1637
import gc
import time
from si7021 import Si7021
from umqtt.simple import MQTTClient
from sys import exit
from os import listdir
import ujson
gc.collect()
with open('config.json') as f:
cfg = ujson.load(f)
cfg_wifi = cfg['wifi']
cf... |
import pytest
from godot import Vector3, Plane
def test_init():
v = Plane(1, 2, 3, 4)
assert type(v) == Plane
assert v.normal == Vector3(1, 2, 3)
assert v.d == 4
@pytest.mark.parametrize(
"args",
[
("NaN", 2.2, 3.3, 4.4),
(1.1, "NaN", 3.3, 4.4),
(1.1, 2.2, "NaN", 4.4... |
# Make py2 like py3
from __future__ import (absolute_import, division, print_function, unicode_literals)
from builtins import ( # pylint: disable=redefined-builtin, unused-import
bytes, dict, int, list, object, range, str,
ascii, chr, hex, input, next, oct, open,
pow, round, super,
filter, map, zip
)
... |
import numpy as np
from abc import ABC, abstractmethod
from .model import Model
from ..util.metrics import mse, mse_prime
class Layer(ABC):
def __init__(self):
self.input = None
self.output = None
@abstractmethod
def forward(self, input):
raise NotImplementedError
@abstractme... |
import logging
import os
import shutil
import subprocess
import tarfile
from contextlib import ExitStack as does_not_raise
from pathlib import Path
from pprint import pprint as pp
from unittest.mock import Mock
import pytest
from conftest import count_files_dir
from SuperTar import SuperTar, what_comp
from SuperTar.e... |
import os
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
import numpy as np
import pandas as pd
import zigzag
from matplotlib.finance import candlestick2_ohlc
fpath = os.path.dirname(os.path.abspath(__file__))
fpath += '/data/ingest_data/'
load_file_name = 'binance_btc_usdt_4h.csv'
write_up_down_f... |
import numpy as np
from scipy.misc import imresize
import gym
from gym.core import ObservationWrapper, Wrapper
from gym.spaces.box import Box
from gym.wrappers import SkipWrapper, TimeLimit
from copy import copy
import collections
try:
import ppaquette_gym_doom
from ppaquette_gym_doom.wrappers.action_space imp... |
import json
from flask_login import login_required
from . import blueprint_region
from ..models import RegionCount
from ..models import Region
from ..models import Doctor
from ..models import DoctorTitle
from ..models import DoctorDisease
from ..models import HospitalOffice
from ..models import Hospital
from ..models i... |
import sys
from uuid import uuid1
from copy import copy
from notion.client import NotionClient
from notion.utils import extract_id
import os
from random import choice
colors = [
"default",
"gray",
"brown",
"orange",
"yellow",
"green",
"blue",
"purple",
"pink",
"red",
]
def q... |
"""Methods to clean and transform the raw data from the USPS EDDM tool."""
import multiprocessing
import os
import geojson
import geopandas as gpd
from models.etl import initiate
import pandas as pd
import shapely
from shapely import speedups
speedups.enable()
pd.options.mode.chained_assignment = None
def con... |
import logging
import os
import pickle
import random
from pathlib import Path
import itertools
import numpy as np
import pandas as pd
from sklearn.preprocessing import LabelEncoder
from src.data.make_dataset import DATE_COLUMNS, CAT_COLUMNS
import utm
project_dir = Path(__file__).resolve().parents[2]
def rule(row):
... |
import unittest
import abc
import os
import torch
import numpy as np
from configs import BaseConfig, env
from utils.common import deepcopy, merge_dict, _all_subclasses, cmp_class, all_subclasses, is_abstract, \
all_subclasses_not_abstract, hasattrs
from utils.path import get_filename, get_path, comp_path
from util... |
import os
try:
import json
except ImportError:
from scheme import json
from mesh.constants import *
from mesh.transport.http import STATUS_CODES
from mesh.util import get_package_data, write_file
from scheme import Field
class JavascriptConstructor(object):
RESERVED_WORDS = ['delete', 'default', 'export'... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Helper module that handles the use of VGG19 in the training of the model
"""
import torch
import torch.nn as nn
import torchvision.models as models
from losses import VariationalLoss, ContentTrack, StyleLoss, StyleTrack
from losses import gram_matrix
class Norma... |
############### Blackjack Project #####################
## The deck is unlimited in size.
## There are no jokers.
## The Jack/Queen/King all count as 10.
## The the Ace can count as 11 or 1.
## Use the following list as the deck of cards:
## cards = [11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]
## The cards in the li... |
import os
import pandas as pd
import xlrd
import openpyxl
import re
# import docx
# from tools.validate import check_email
CSV_FILES_PATH = r'D:\teacher_wen\原始文件'
EXCEL_FILES_SAVING_PATH = r'D:\teacher_wen\原始文件\excels'
EXCEL_FILES_PATH = r'D:\teacher_wen\待发送\isaic\中文'
EXCEL_SAVE_FILE = r'D:\teacher_wen\待发送\isaic\isai... |
from .myqt import QT
import pyqtgraph as pg
import numpy as np
from .base import WidgetBase
from .baselist import ClusterBaseList
from .peelercontroller import spike_visible_modes
from .tools import ParamDialog
from .. import labelcodes
class SpikeModel(QT.QAbstractItemModel):
def __init__(self, parent =None, ... |
# DepthInSpace is a PyTorch-based program which estimates 3D depth maps
# from active structured-light sensor's multiple video frames.
#
# MIT License
#
# Copyright (c) 2019 autonomousvision
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation ... |
import cv2
import numpy as np
class PinholeCamera:
"""
Class representing Video Camera used by robot, it stores params of this camera needed in Visual Odometry
"""
def __init__(self, width, height, int_matrix):
self.cam_width = width
self.cam_height = height
self.fx = int_matri... |
# -*- coding: utf-8 -*-
# Author: <EMAIL>
import os,sys
import math
import time
import string
def __progress(count, total, suffix=''):
bar_len = 30
filled_len = int(round(bar_len * count / float(total)))
percents = round(100.0 * count / float(total), 1)
bar = '=' * filled_len + '-'... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date : 2020-02-18 11:06:13
# @Author : <NAME> & <NAME> (<EMAIL>)
# @Link : http://iridescent.ink
# @Version : $1.0$
from __future__ import division, print_function, absolute_import
import torch as th
import numpy as np
from torchsar.utils.const import *
from torch... |
import requests
import xml.etree.ElementTree as ET
class Dymo:
def __init__(self, host="https://127.0.0.1", port="41951", printer="DYMO LabelWriter 450 Twin Turbo"):
self.uri = f"{host}:{port}/DYMO/DLS/Printing"
self.header = {'Content-Type': 'application/x-www-form-urlencoded'}
self.pr... |
import pygame
import random
import sys
from time import sleep
padWidth = 400
padHeight = 640
rockimage = ['rock01.png','rock02.png','rock03.png','rock04.png','rock05.png', \
'rock06.png','rock07.png','rock08.png','rock09.png','rock10.png', \
'rock11.png','rock12.png','rock13.png','ro... |
import re
from doit.task import dict_to_task
from doit.control import no_none
from . import dag
from .util import generator_flatten
def Matcher(str_or_callable):
if type(str_or_callable) is str:
return lambda file_: bool(re.search(str_or_callable, file_) is not None)
if hasattr(str_or_callable, '__ca... |
#!/usr/bin/env python
"""
VMAF - Video Multimethod Assessment Fusion
VMAF is a perceptual video quality assessment algorithm developed by Netflix.
VMAF Development Kit (VDK) is a software package that contains the VMAF algorithm implementation,
as well as a set of tools that allows a user to train and test a custom V... |
'''
Encoding Visual Attributes in Capsules for Explainable Medical Diagnoses (X-Caps)
Original Paper by <NAME>, <NAME>, and <NAME> (https://arxiv.org/abs/1909.05926)
Code written by: <NAME>
If you use significant portions of this code or the ideas from our paper, please cite it :)
If you have any questions, please emai... |
"""
The script purpose for Multi Human Parsing Dataset(MHP) v2.0
1. generate semantic segmentation without instance
2. convert to tfrecord
necessary folder structure - MHP v2.0
+ LV-MHP-v2
+ images
+ list
- train.txt
- val.txt
+ parsing_annos
- *.jpg
+ tfrecord
This script... |
##########################################################
# to turn off warnings #
import warnings #
warnings.filterwarnings('ignore') #
#
import os ... |
#!/usr/bin/env python
# coding=utf-8
"""
Ant Group
Copyright (c) 2004-2020 All Rights Reserved.
------------------------------------------------------
File Name : order.py
Author : <NAME>
Email: <EMAIL>
Create Time : 2020-06-09 15:49
Description : description what the main function of this file
... |
import random
from tempfile import NamedTemporaryFile
import requests
from django.contrib.auth.models import Group
from django.core.files import File
from django.db import models
from django.utils.html import format_html
from apps.bot.classes.consts.Consts import Platform as PlatformEnum
class Platform(models.Model... |
from matplotlib import pyplot
from math import cos, sin, atan
import numpy as np
class Neuron():
def __init__(self, x, y, is_bias=False):
self.x = x
self.y = y
self.is_bias = is_bias
def draw(self, neuron_radius):
if not self.is_bias:
neuron = pyplot.Circle((self.x,... |
import numpy as np
import time
from pykin.kinematics.transform import Transform
JOINT_TYPE_MAP = {'revolute' : 'revolute',
'fixed' : 'fixed',
'prismatic' : 'prismatic'}
LINK_TYPE_MAP = {'cylinder' : 'cylinder',
'sphere' : 'sphere',
'box' ... |
import numpy as np
import pandas as pd
import matplotlib
import matplotlib.pyplot as plt
def get_mean_std_results(df):
odom_multipliers = np.unique(df['Odometry Multiplier'])
results = []
for multiplier in odom_multipliers:
data = df[df['Odometry Multiplier'] == multiplier]
Error_corrected = data['Path Error']... |
import pathlib
import subprocess
import typing
import libzfs
import zonys
import zonys.core
import zonys.core.zfs
import zonys.core.zfs.dataset
import zonys.core.zfs.snapshot
import zonys.core.zfs.property
class AlreadyExistsError(RuntimeError):
def __init__(self, name):
super().__init__("File system {}... |
#!/usr/bin/python3 -u
''' Orchestrate multiple processes '''
import argparse
from collections import OrderedDict
import os
import shlex
import signal
import subprocess
import sys
import time
def args_parse():
''' Parse arguments '''
parser = argparse.ArgumentParser(description='Orchestrate multiple processes... |
import tensorflow as tf
import os
import random
import sys
import pathlib
from PIL import Image
# 测试集数量
_NUM_TEST = 2000
# 随机种子
_RANDOM_SEED = 0
# 定义数据块数量
_NUM_SHARDS = 5
# 数据集路径
DATASET_DIR = "/root/quan/fruits-360/Training/"
# 标签文件存放名字
#LABEL_FILENAME = "labels.txt"
data_root_orig = "/root/quan/fruits-360/Training/"... |
# coding: utf-8
"""
Name: fetch_favorite_tweets.py
Fetch selected user's favorite tweets.
Usage: python3 fetch_favorite_tweets.py -i <user_id>
Author: <NAME>
Date: 2021/08/26
"""
import argparse
import os
from os.path import abspath, dirname, join
import sys
import random
import time
import requests
def parse_args... |
# !/usr/bin/python
# -*- coding: utf-8 -*-
import tensorflow as tf
import tf_utils
def placeholder_inputs(batch_size, img_w, img_h):
input_img_pl = tf.placeholder(tf.float32, shape=(batch_size, img_w, img_h))
label_seg_pl = tf.placeholder(tf.int32, shape=(batch_size, img_w, img_h))
label_cls_pl = tf.plac... |
import sublime
import sublime_plugin
import subprocess
import os
class HotspotsRunCommand(sublime_plugin.TextCommand):
def tranform_count(self, count_str):
"""
Transforms count number from the form of llvm-cov to a float
llvm-cov format is num[|k|M|G|T|P|E|Z|Y]
"""
try:
if count_str[-1] >= '0' and count_... |
#from PyDSP import *
from .process import *
from . import *
import numpy as np
import scipy.signal
class SpectralFluxProcess(IterativeProcess):
def begin(self):
#self.frame_zero = np.zeros( self.matrix.data[0,:].shape )
#self.out = np.empty( self.matrix.data.shape )
self.out = np.empt... |
"""
"""
import numpy as np
import torch
from torch import optim
import torch.nn.functional as F
from scipy.spatial import distance
import scipy.sparse as sp
import networkx as nx
import auto_encoders.gae.utils as gae_util
import auto_encoders.gae.optimizer as gae_optimizer
import auto_encoders.model as model
impor... |
import argparse
import csv
import cPickle as pickle
import collections
from HTMLParser import HTMLParser
import operator
import re
import json
import sklearn.preprocessing
# Taken from
# https://github.com/tensorflow/tensorflow/blob/16254e75e2fe4bb0f879b45fbad0c4b62c028011/tensorflow/models/rnn/translate/data_utils.p... |
# Copyright (c) 2013, 2018 National Technology and Engineering Solutions of Sandia, LLC . Under the terms of Contract
# DE-NA0003525 with National Technology and Engineering Solutions of Sandia, LLC, the U.S. Government
# retains certain rights in this software.
"""Slycat makes extensive use of `darray` objects - dens... |
from discord import Embed, FFmpegPCMAudio
from discord.ext import commands
from discord.utils import get
from youtube_dl import YoutubeDL
from asyncio import run_coroutine_threadsafe
import re
import requests
from bs4 import BeautifulSoup
class Music(commands.Cog, name='Music'):
YDL_OPTIONS = {'forma... |
from __future__ import absolute_import, unicode_literals
from http.client import HTTPSConnection
import mock
import clay.config
from clay import http
try:
from urllib.request import Request as urllib_Request
from urllib.request import HTTPSHandler, urlopen
from urllib.error import HTTPError, URLError
excep... |
import os
import sys
sys.path.append(os.path.abspath('..'))
sys.path.append(os.path.abspath('../..'))
sys.path.append(os.path.abspath('../../..'))
sys.path.append(os.path.abspath('../../../..'))
sys.path.append(os.path.abspath('../../../../..'))
import matplotlib.pyplot as plt
import numpy as np
from src.acc... |
from esm import model
import torch
import esm
import re
from tqdm import tqdm
import numpy as np
import pandas as pd
# region 将字符串拆分成固定长度
def cut_text(text,lenth):
"""[将字符串拆分成固定长度]
Args:
text ([string]): [input string]
lenth ([int]): [sub_sequence length]
Returns:
[string list]: ... |
"""Subject routes."""
from datetime import datetime, timedelta, timezone
import bottle
from pymongo.database import Database
from shared.utils.type import MetricId, ReportId, SubjectId
from ..database.datamodels import default_subject_attributes, latest_datamodel
from ..database.measurements import measurements_by_m... |
import os
import datetime
import numpy as np
import pandas as pd
import xarray as xr
import boto3
from botocore.handlers import disable_signing
def get_forecast_from_silam_zarr(date_str, modality, day, version="v5_7_1"):
"""
Obtain forecast of specified parameter from SILAM for the whole world in zarr format
... |
"""Int class.
Represents an unbounded int using a widget.
"""
# Copyright (c) Jupyter Development Team.
# Distributed under the terms of the Modified BSD License.
from .widget import DOMWidget, register
from .trait_types import Color
from traitlets import (Unicode, CInt, Bool, CaselessStrEnum,
... |
"""
Evaluate NPL posterior samples predictive performance/time
"""
import numpy as np
import pickle
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
from tqdm import tqdm
import scipy as sp
import importlib
import npl.sk_gaussian_mixture as skgm
from npl.evaluate import gmm_ll as gll
from sk... |
import os
import time
import argparse
import random
import numpy as np
from tqdm import trange
from statistics import mean
parser = argparse.ArgumentParser(description='NAS Without Training')
parser.add_argument('--data_loc', default='../datasets/cifar', type=str, help='dataset folder')
parser.add_argument('--api_loc'... |
import numpy as np
import random
from collections import namedtuple, deque
from dueling_model import Dueling_QNetwork
from model import QNetwork
import torch
import torch.nn.functional as F
import torch.optim as optim
BUFFER_SIZE = int(1e5) # replay buffer size
BATCH_SIZE = 64 # minibatch size
GAMMA = 0.99 # disc... |
# coding=utf-8
import re
import logging
import base64
import os
import datetime
from openerp.http import request
import openerp
from .. import client
_logger = logging.getLogger(__name__)
def get_img_data(pic_url):
import requests
headers = {
'Accept': 'textml,application/xhtml+xml,application/xml;q=0.9,im... |
# Copyright 2017 Huawei Technologies Co.,LTD.
# 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
#
# Unl... |
"""
File name: gdax/client.py
Author: <NAME> <<EMAIL>>
Implementation of GDAX Client to get realtime data.
"""
import json
from datetime import datetime, timedelta
from websocket import create_connection
from cryptostreamer.provider import ProviderClient
class NoProductsError(Exception): pass
class NoChannelsEr... |
from django.shortcuts import render, get_object_or_404, redirect
from django.http import Http404, JsonResponse, HttpResponse
from django.views.decorators.http import require_GET, require_POST, require_http_methods
from django.views.decorators.csrf import csrf_exempt
from django.contrib.auth import authenticate, login a... |
from discord.ext import commands, tasks
import sys
import traceback
import json
import datetime
import time
import random
import asyncio
import discord
from discord import slash_command
import os
from dotenv import load_dotenv
load_dotenv()
bot = discord.Bot()
def convert(time):
pos = ["s", "... |
import json
import numpy as np
import tensorflow as tf
from .xlnet import build_xlnet
__all__ = [
'build_model_from_config',
'load_model_weights_from_checkpoint',
'load_trained_model_from_checkpoint',
]
def checkpoint_loader(checkpoint_file):
def _loader(name):
return tf.train.load_variable(... |
#!/bin/python3
import rospy
import std_msgs.msg as std_msg
import nav_msgs.msg as nav_msg
import math
import numpy as np
def euler_from_quaternion(x, y, z, w):
"""
Convert a quaternion into euler angles (roll, pitch, yaw)
roll is rotation around x in radians (counterclockwise)
pitch is rotation around... |
"""
This module contains the definitions necessary to parse sets of instructions in
string form and return a simple attribute object holding everything
"""
INSTRUCTION_HAS_WHITESPACE = "Cannot parse an instruction with whitespace"
INCOMPLETE_SET = "There must be one set of '{},{}' to finish " \
"the... |
# Copyright The Linux Foundation
# SPDX-License-Identifier: Apache-2.0
import os
from collections import OrderedDict
import openpyxl
from datatypes import SLMLicense
##### Main xlsx reporting functions
##### External usage shouldn't require calling anything except these
def makeXlsx(categories):
wb = openpyxl.W... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from .. import _utilities
from... |
"""
使用簡單的前饋神經網路feed-forward neural network來訓練並預測mnist資料集,用我自行產生的csv檔來當做資料來源.
see tensorflow-1.6.0/tensorflow/examples/tutorials/mnist/fully_connected_feed.py
"""
import tensorflow as tf
from mnist import mnist_dataset as md
from mnist import mnist_core as mnist
#from tensorflow.examples.tutorials.mnist import mnist
fro... |
# Copyright 2021 DAI Foundation
#
# 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 applicable law or agreed to in writing,... |
"""
Wrapper to get the ChemProp predictions on the test set for each model in
the folder `model_folder_cp`.
"""
import os
import json
import argparse
import numpy as np
from nff.utils import (bash_command, parse_args, read_csv,
fprint, CHEMPROP_METRICS, apply_metric)
def is_model_path(cp_mode... |
''' THIS IS MY FIRST PYTHON GUI PROJECT. IF YOU WANT TO ADD SOME FEATURES AND CONTRIBUTE TO IT, FEEL FREE TO DO SO!
BASICALLY WHAT THIS PROGRAM DOES - IT SEND THE CUSTOMIZED 'NAME' MASS EMAILS USING AN EXCEL FILE WITH JUST ONE CLICK MAKING A LIL BIT OF OUR LIFE EASIER.'''
#IMPORTING MODULES
from tkinter import *
from... |
from fastai.basic_train import load_learner
import pandas as pd
from pydub import AudioSegment
from librosa import get_duration
from pathlib import Path
from numpy import floor
from audio.data import AudioConfig, SpectrogramConfig, AudioList
import os
import shutil
import tempfile
def load_model(mPath, mName="stg2-rn... |
# author: <NAME> (nxkennedy)
import csv
import os
import time
import sqlite3
rootdir = os.getcwd()
components = []
reports = []
dbname = 'db-' + time.strftime("%Y%m%d-%H%M%S") + '.db'
def normalize(infile):
filename = os.path.basename(infile)
info = filename.split(' ')
s_id = info[2]
s_type =... |
from django.contrib.auth.models import User
from api_v1.models import Bucketlist, BucketlistItem
from rest_framework import viewsets
from api_v1.serializers import UserSerializer, BucketlistSerializer, \
BucketlistItemSerializer
from rest_framework.response import Response
from rest_framework import status
from res... |
#!usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Application that actually uses Flyweight Pattern.
"""
__author__ = '<NAME>'
from color import Color
from flyweight.cirlcle import SharedCircle, UnsharedCircle
from flyweight.rect import SharedRectangle, UnsharedRectangle
class FlyweightShapeFactory:
"""
Fly... |
import bisect
import torch.utils.data as data
from data.coco import COCODataset
import math
import itertools
import torch
import torch.distributed as dist
import pdb
class group_sampler:
"""
Wraps another sampler to yield a mini-batch of indices.
It enforces that elements from the same group should appear... |
# -*- coding: utf-8 -*-
import os, sys
import numpy as np
from skimage import io
import random, uuid
import matplotlib.pyplot as plt
from pydaily import filesystem
def plot_lr(l_img, r_img, l_title=None, r_title=None, suptitle=None):
fig, axes = plt.subplots(nrows=1, ncols=2, figsize=(10, 4))
axes[0].imshow... |
import logging
import sys
from contextlib import contextmanager
import traceback as tb
from json import dumps as json_to_str
from enum import Enum
# region Constants
_FMT_STRING = "%(asctime)s %(levelname)s %(name)s {arrow} %(message)s"
_UNC_ARROW = "➔"
_ASCII_ARROW = "->"
_TIP_LEVEL = 21 # Important log info
_REPOR... |
# summarize model
from collections import OrderedDict
import pandas as pd
import torch
from torch import nn
class TorchSummarizeDf(object):
def __init__(self, model, weights=False, input_shape=True, nb_trainable=False, debug=False):
"""
Summarizes torch model by showing trainable parameters and we... |
import asyncio
from asyncio.tasks import sleep
import shelve
import datetime
import discord
from discord.ext import commands
import redis
redis_server = redis.Redis()
token = str(redis_server.get('DISCORD_TOKEN').decode('utf-8'))
my_server = str(redis_server.get('MY_SERVER').decode('utf-8'))
league_logins = str(redis_... |
import logging
import sqlite3
import time
from datetime import date, datetime
from .indices import IndicesClient
logger = logging.getLogger("elasticsearch")
def _escape(value):
"""
Escape a single value of a URL string or a query parameter. If it is a list
or tuple, turn it into a comma-separated string... |
##############################################################################
# Author: <NAME>
# Last Changed: 5/7/21
#
# REQUIREMENTS
# - Detailed dependencies in requirements.txt
# - Directly referenced:
# - prefect, bs4, requests
#
# - Infrastructure:
# - Prefect: Script is registered as a Prefect flow with api... |
import pathlib
import json
import pycountry
import google_play_scraper as gplay
from itunes_app_scraper.scraper import AppStoreScraper
import csv
from datetime import date
import time
from concurrent.futures import ThreadPoolExecutor
from collections import deque
import pycountry
class app_instance:
def __init__... |
"""
Classes used in the second assignment in CSSE1001.
StockCollection: All stock market data stored in application.
Stock: Data for a single stock.
TradingData: Data for a single day of trading in one stock.
Loader: Abstract class defining the process of loading stock market data.
Analyser: Ab... |
from bokeh.models import CustomJS
# handle the currently selected article
def selected_code_videos():
code = """
var ids = [];
var titles = [];
var published_times = [];
// var texts = [];
var publication_end_times = [];
var media_availables =... |
import re
from enum import Enum
from typing import DefaultDict, Dict, List, Tuple
fieldRegex = re.compile(r"(.*): (\d+)-(\d+) or (\d+)-(\d+)")
ticketStartRegex = re.compile(r"(\d+),")
class Field:
def __init__(self, name: str, low1: int, high1: int, low2: int, high2: int) -> None:
self.name = name
... |
# classic arcade game Pong
try:
import simplegui
except ImportError:
import SimpleGUICS2Pygame.simpleguics2pygame as simplegui
import random
import os
# from flask import Flask
# initialize globals - pos and vel encode vertical info for paddles
WIDTH = 600
HEIGHT = 400
BALL_RADIUS = 20
PAD_WIDTH = 8
PAD_HEIGH... |
"""Invoke commands for project/session/ticket management
"""
import os
import shutil
import configparser
from invoke import task
from settings import PROJECTS_BASE, SESSIONS, DEVEL, get_project_dir # , private_repos
def get_project_name(ticket):
"find_project_by_ticket(number)"
hgrc = os.path.join(DEVEL, '_{... |
import numpy as np
from scipy.ndimage import filters
from bidict import bidict
def image_gradient(image, sigma):
image = np.asfarray(image)
gx = filters.gaussian_filter(image, sigma, order=[0, 1])
gy = filters.gaussian_filter(image, sigma, order=[1, 0])
return gx, gy
class CurvePoint(object):
__... |
import re
import glob
from json import dumps
from os.path import curdir, abspath, join, splitext, isfile
from os import walk
rfc_2119_keywords_regexes = [
r"MUST",
r"REQUIRED",
r"SHALL",
r"MUST NOT",
r"SHALL NOT",
r"SHOULD",
r"RECOMMENDED",
r"SHOULD NOT",
r"NOT RECOMMENDED",
r"M... |
#encoding: utf-8
from pipeline import Pipeline
from mongo import MongoManager
from datetime import datetime, timedelta
from pprint import pprint
from tweet import Tweet
from classifiermanager import ClassifierManager
from brandclassifier import ProductMatch
from genderclassifier import GenderClassifier
class TweetSa... |
# parser.py
import io
import numpy as np
import pandas as pd
from enum import Enum, auto
import xml.etree.ElementTree as ET
import xml.dom.minidom as MD
from pathlib import Path
from typing import Union, Optional, Any, List
__all__ = ["Parser", "InFile", "OutFile"]
PathOrStr = Union[Path, str]
DEBUG = False
cl... |
# -*- coding: utf-8 -*-
"""
Created on Mon Jun 24 10:20:16 2019
@author: qde
"""
import unittest
import numpy as np
from math import sqrt,atan2, isclose
from fdia_simulation.models import Radar, PeriodRadar
class RadarTestCase(unittest.TestCase):
def setUp(self):
self.radar = Radar(x = ... |
# ##### BEGIN GPL LICENSE BLOCK #####
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distrib... |
# Copyright 2016 The Bazel 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 applicable la... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.