text stringlengths 3.07k 12.6k |
|---|
#!/usr/bin/env python
from __future__ import print_function
import math
import numpy
from os.path import expandvars
import matplotlib
matplotlib.use("PDF")
fig_size = [11.7,8.3] # din A4
params = {'backend': 'pdf',
'axes.labelsize': 12,
'text.fontsize': 12,
'legend.fontsize': 8,
'xt... |
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import math
def proportional_control(target, current):
a = Kp * (target - current)
return a
class TargetCourse:
def __init__(self, cx, cy):
self.cx = cx
self.cy = cy
self.... |
#Merge Sort uses the Divide and Conquer approach. It involves breaking up the array from the middle until
#Arrays of only 1 elements remain and thein merging them back up in a sorted order.
#Time complexity is O(nlog N) and space complexity is O(n)
count = 0
def merge_sort(array):
if len(array) == 1:
retu... |
"""
Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get and put.
get(key) - Get the value (will always be positive) of the key if the key exists in the cache, otherwise return -1.
put(key, value) - Set or insert the value if the key is not already ... |
import requests as rq
import json
from crontab import CronTab
from datetime import datetime, timedelta
import math
from multiprocessing import Pool
import random
import schedule
import time
import RPi.GPIO as IO
from neopixel import *
# LED branches config:
LED_COUNT = 5 #number of LEDs
LED_PIN = 18 #I/O pin defi... |
#!/usr/bin/env python3
# SPDX-License-Identifier: MIT
import json
import sys
from dataclasses import dataclass
from enum import Enum
# https://github.com/espressif/esp-idf/blob/c69f0ec3292de2b9df5554405744296333d0feb2/components/nvs_flash/src/nvs_page.hpp#L36-L39
from typing import Any, TextIO, List, Optional
PSB_INI... |
import os
import re
from scipy.ndimage import imread
from scipy.misc import imresize
import numpy as np
try:
import dicom
except ImportError:
print('warning: pydicom is not installed, so you can load the png files,'
'but not the .dcms in the large dataset ')
# Utilities for preprocessing
def remov... |
import ipywidgets as widgets
import pandas as pd
import techminer.core.dashboard as dash
from techminer.core import (DASH, TF_matrix, TFIDF_matrix,
add_counters_to_axis, limit_to_exclude,
sort_by_axis)
from techminer.plots import bar_plot, barh_plot
############... |
import json
import os
import click
from kiss.clockify_api import ClockifyApi
from kiss.time_entries_checker import TimeEntriesChecker, TimeEntriesCheckOption
from kiss.time_entries_diff import TimeEntriesDiffComputer
from kiss.time_entries_file import TimeEntriesFile, Month, Task, DateInterval
from kiss.time_entries_... |
from scipy.ndimage import imread
import numpy as np
import math
import cv2
def pyramid_sizes(init_size, a_output_size, b_output_size):
"""
Determine appropriate resolutions for all levels of an image pyramid.
@param init_size Max width/height of the lowest resolution of the pyramid.
@param a_output_si... |
# © 2019 University of Illinois Board of Trustees. All rights reserved
"""
New hotspot detection method that uses the C++ AlleleSearcher class
"""
import argparse
from AlleleSearcherLite import AlleleSearcherLite, LocationOutOfBounds
from ReferenceCache import ReferenceCache
from PileupContainerLite import PileupConta... |
# Released under The MIT License (MIT)
# http://opensource.org/licenses/MIT
# Copyright (c) 2015 SCoT Development Team
"""
Summary
-------
Tools for basic data manipulation.
"""
from __future__ import division
import numpy as np
from .utils import check_random_state
def atleast_3d(x):
x = np.asarray(x)
if... |
# The MIT License (MIT)
# Copyright (c) 2019 by the xcube development team and contributors
#
# 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... |
"""
If you can prove your the owner of a tag (By ID and just messaging me) I will immediately remove any associated tag that you want from me.
My purpose for this project was to expand my own knowledge and to share tags with the world.
Embed meta property preview has a max of 347 characters
string Accepts any text wit... |
from weather import *
from News import *
from spotify_playback_control import spotifycontrol
from BingTTS import *
from translate import *
from read_gmail import *
import random
'''開啟麥克風並透過Dialogflow內建的語音辨識功能來辨識'''
def detect_intent_stream():
global audio,stream
session = random.randint(0,10)
import dialogf... |
# Natural Language Toolkit: Gale-Church Aligner Distance Functions
#
# Copyright (C) 2001-2011 NLTK Project
# Author: <NAME> <<EMAIL>>
# URL: <http://nltk.org/>
# For license information, see LICENSE.TXT
import math
BIG_DISTANCE = 2500
# Based on Gale & Church 1993, "A Program for Aligning Sentences in ... |
'''
Created on Aug 1, 2012
@author: <NAME>
Email: <EMAIL>
'''
import FILES
import tools.ROOTFileReader as FileReader
from ROOT import gROOT
fileTemplate = 'data/correctionFactors/correctionFactors_%s_%s_JSON.txt'
samples = [
'TTJet',
'POWHEG',
'PYTHIA6',
'MCatNLO',
'TTJets-ma... |
# Copyright (c) 2004-2006 gocept gmbh & co. kg
# See also LICENSE.txt
# $Id$
"""Process definitions"""
import zope.component
import zope.interface
from OFS.Folder import Folder
from AccessControl import ClassSecurityInfo
from Globals import InitializeClass
from Products.PageTemplates.PageTemplateFile import PageTempl... |
import os
import glob
import re
import pandas as pd
import numpy as np
from datetime import date
from .build_primary_pset_tables import build_primary_pset_tables, build_cell_df, build_compound_df, build_tissue_df
from .build_experiment_tables import build_experiment_tables, build_experiment_df
from .build_gene_compound... |
import functools
from io import BytesIO
from typing import Tuple
from .announcements import _get_unique_id
import asyncio
import discord
from discord.ext.commands import Context
from discord import Member
from PIL import Image, ImageDraw, ImageFont, ImageOps
loop = asyncio.get_event_loop()
def async_executor():
... |
import os
import torch
import time
import math
def get_batch(source, i, bptt):
# get_batch subdivides the source dataset into chunks of length args.bptt.
# If source is equal to the example output of the batchify function, with
# a bptt-limit of 2, we'd get the following two Variables for i = 0:
# ┌ a... |
import copy
import pytest
from barril import units
from barril.basic.fraction import FractionValue
def testFractionScalar():
# create our scalar
f = units.FractionScalar("length", value=FractionValue(250, (3, 4)), unit="m")
# check formatting
assert f.GetFormatted() == "250 3/4 [m]"
# check co... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Jul 30 23:33:49 2020
@author: joaovitor
"""
import numpy as _np
from typing import List
class Coordinate(object):
"""Coordinate abstraction."""
def __init__(self, x: float = 0., y: float = 0., z: float = 0.):
"""
Coordinate r... |
#!/usr/bin/env python
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
import MITgcmutils as mit
plt.ion()
matplotlib.rcParams['ps.useafm'] = True
matplotlib.rcParams['pdf.use14corefonts'] = True
matplotlib.rcParams['text.usetex'] = True
dir0 = 'tmp_energy7/'
filets = 'diag_ocnSnap*'
filepe ... |
import json
import logging
import random
import matplotlib.pyplot as plt
import numpy as np
import ruamel.yaml
import joblib
from matplotlib.lines import Line2D
from termcolor import colored
from .base import BaseCallbacks
from .serialize import fig2data, serialize
# TODO: logging for all printed info on the termi... |
import torch
import gym
import os
import random
import torch.nn as nn
import torch.nn.functional as f
import torch.optim as optim
from torch.distributions import Categorical
import numpy as np
DEFAULT_CONFIG = {
'gamma': 0.99,
'lr': 0.01,
'decay_rate': 0.98,
'actior_lr': 0.001,
'critic_lr': 0.001,... |
import os
import time
import elasticsearch
import config
from model.comment import Comment
from slim.utils import to_hex
from model._post import POST_TYPES, POST_STATE, POST_VISIBLE
from model.topic import Topic
from model.user import User
from model.wiki import WikiArticle
INDEX_NAME = config.ES_INDEX_NAME
if conf... |
class TestRegistration:
def test_okay_is_registered(self, client, acc1):
res = client.db.is_registered(acc1.addr)
assert res
def test_fail_is_registered(self, client, unregistered_addr):
res = client.db.is_registered(unregistered_addr)
assert not res
class TestApplications:
... |
import argparse
import os
import shutil
import warnings
import numpy as np
import torch
import torch.nn.functional as F
from torch.utils.tensorboard import SummaryWriter
from tqdm import tqdm, trange
from forward_model import GaussianCompressiveSensing, NoOp
from model.deep_decoder import DeepDecoder
from utils impor... |
"""
Unit-aware replacements for numpy functions.
"""
from __future__ import absolute_import
from functools import wraps
import pkg_resources
import numpy as np
from .fundamentalunits import (Quantity, wrap_function_dimensionless,
wrap_function_remove_dimensions,
... |
import torch
from torch import nn
import torchvision.datasets as dsets
import torchvision.transforms as transforms
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
import fasttext
import torch.nn.functional as F
from torch.utils import data
import modules.classifiers as classifiers
import modules.... |
from jax.config import config
config.update("jax_enable_x64", True)
import jax.numpy as np
from jax import jit, grad, vmap
from jax import random
from jax import lax
from jax.lax import stop_gradient
from jax.ops import index, index_update
from jax.flatten_util import ravel_pytree
from functools import partial
from ... |
import copy
import importlib
import multiprocessing
import os
import subprocess
import tempfile
import morepath
import reg
import sqlalchemy
import transaction
import yaml
from beaker.middleware import CacheMiddleware as BeakerCacheMiddleware
from beaker.middleware import SessionMiddleware as BeakerMiddleware
from cel... |
#
#
# Copyright 2019 Asylo authors
#
# 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 wri... |
#!/usr/bin/env python3
import argparse
from os import system
import cgp.cgp_utilies
from controller import get_top, post_top
from mario_emu.emulator import Emulator
# Hyper parameters
from mario_emu.picture_processor import PictureProcessor
POPULATION_SIZE = 100
GENOME_SIZE = 1024
NB_BREED = 5 # Number of children... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.core.files.storage import default_storage
from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage
from django.db.models.fields.files import FieldFile
from django.views.generic import FormView
from django.views.generic.base imp... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
"""=================================================================
@Project : Algorithm_YuweiYin/LeetCode-All-Solution/Python3
@File : LC-2047-Number-of-Valid-Words-in-a-Sentence.py
@Author : [YuweiYin](https://github.com/YuweiYin)
@Date : 2022-01-27
===============... |
from random import randint
import math
def liner_equation(x,y):
return -2*x - 3*y + 8
def nonliner_equation(x,y):
return 2*y - 3*x*x + 5*x - 3
def generate_dataset(count, type="liner"):
data = []
for i in range(count):
rx = float(randint(0, 6000))
ry = float(randint(0, 6000))
... |
import tqdm
import numpy as np
from numpy import sin, cos
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
class DoublePendulum:
def __init__(self, m1=1.0, m2=1.0, l1=1.0, l2=1.0, g=9.81):
self.m1 = m1
self.m2 = m2
self.l1 = l1
self.l2 = l2
... |
#!/usr/bin/env python3.7
# billboardgui.py
"""GUI tool for scraping data from www.billboard.com"""
# stand lib
from pathlib import Path
import subprocess as sp
from time import sleep
import tkinter as tk
from tkinter import ttk
# custom
from constants import *
# from scrapeutil import *
from filesanddirs import make_... |
import sys
from expression_walker import walk
from pass_utils import BINOPS, UNOPS
try:
import gelpia_logging as logging
import color_printing as color
except ModuleNotFoundError:
sys.path.append("../")
import gelpia_logging as logging
import color_printing as color
logger = logging.make_module_l... |
load("@bazel_skylib//lib:collections.bzl", "collections")
load("@bazel_skylib//lib:paths.bzl", "paths")
load(
"@fbcode_macros//build_defs/lib:python_typing.bzl",
"gen_typing_config",
"get_typing_config_target",
)
load("@fbcode_macros//build_defs/lib:src_and_dep_helpers.bzl", "src_and_dep_helpers")
load("@fb... |
"""Various ways to save data."""
import csv
import logging
from dataclasses import asdict, fields
from typing import Any, Collection, Mapping, Sequence, Tuple
import mysql.connector
from mysql.connector import errorcode
from mysql.connector.connection import MySQLConnection, MySQLCursor
from data_crawler.data_objects... |
from __future__ import unicode_literals
from prompt_toolkit.document import Document
from prompt_toolkit.enums import DEFAULT_BUFFER
from prompt_toolkit.filters import HasSelection, IsMultiline, Filter, HasFocus, Condition, ViInsertMode, EmacsInsertMode
from prompt_toolkit.key_binding.vi_state import InputMode
from pr... |
# -*- coding: utf-8 -*-
# Time: 2021-08-30 14:03
# Copyright (c) 2021
# author: Euraxluo
import os
import copy
import typing
import warnings
from inspect import *
from environs import Env
from easydict import EasyDict
from pydantic import BaseSettings
class Types(object):
int: Env.int = typing.TypeVar('int')
... |
import pandas as pd
import numpy as np
from sklearn.metrics import mean_squared_error
import warnings
import matplotlib.pyplot as plt
warnings.simplefilter("ignore")
#Open the CSV file with the userid and movieid along with their ratings
ratings = pd.read_csv("ratings.csv")
#calculate the number of users... |
# coding=utf-8
# Copyright 2020 HuggingFace Datasets Authors.
#
# 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... |
# This contains factories for creating test input, using factory boy
# https://factoryboy.readthedocs.io/en/latest/index.html
# Naming convention here is to use "*DataFactory" for dictionaries used as API input/out, and
# <ModelName>Factory for the domain objects themselves
from random import randrange
import factor... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Nov 8 16:08:22 2018
@author: uqytu1
"""
import pandas as pd
import numpy as np
import itertools
from matplotlib import pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
from sklearn.... |
import dgl
import torch
import torch.nn as nn
import torch.nn.functional as F
import itertools
import numpy as np
import scipy.sparse as sp
import dgl.data
dataset = dgl.data.CoraGraphDataset()
g = dataset[0]
print(g)
print(g.ndata['feat'])
print(g.ndata['feat'].size())
print(g.ndata['label'])
# Split edge set for t... |
# -*- coding: utf8 -*-
import gc
import os
import json
import logging
import pandas as pd
from io import BytesIO
from qcloud_cos import CosConfig
from qcloud_cos import CosS3Client
class Data_Frames:
a = None
def main_handler():
logger = logging.getLogger()
logger.setLevel(logging.WARNING)
global c... |
#!/usr/bin/env python3
from optparse import OptionParser
import re
import os
import math
import sys
from subprocess import Popen, STDOUT
VERSION = "1.1.0"
WEB_DIRECTORY = "ftp://ftp.ecn.purdue.edu/tgrogers/accel-sim/traces/"
this_directory = os.path.dirname(os.path.realpath(__file__)) + "/"
sys.path.insert(0,os.path.... |
import sys, os, io
from sys import stdin
from math import log, gcd, ceil
from collections import defaultdict, deque, Counter
from heapq import heappush, heappop, heapify
from bisect import bisect_left, bisect_right
import math
alphabets = list('abcdefghijklmnopqrstuvwxyz')
#for deep recursion_________________________... |
from __future__ import print_function
import copy
import os.path as osp
import click
import cv2
import matplotlib.cm as cm
import numpy as np
import torch
import torch.nn.functional as F
from torchvision import models, transforms
from pdb import set_trace as st
import torchvision.datasets as datasets
from tqdm import... |
import codecs
import json
import logging
from os import path, remove
from subprocess import check_call
from tempfile import NamedTemporaryFile
from .node_base import NodeOrLeaf
from .node_classes import Leaf, Node
def import_tree(obj, how="dict", **kwargs):
"""
Import tree from data source.
"""
if ho... |
import json
import logging
import requests
from django import forms
from django.utils.html import mark_safe
from django.core.cache import caches as django_caches
log = logging.getLogger(__name__)
class Typeahead(forms.TextInput):
"""
Form widget converted to typeahead on client side.
"""
is_multiple... |
#! /home/smithw/.tensorflow2/bin/python
# use python in (TF2) venv: opencv installed there
# motion_mask.py
# WESmith 01/30/22
# use pygame to make motion-detection ignore mask using a video frame
import pygame as pg
import cv2
import numpy as np
import os, sys
from datetime import datetime
pg.init()
RED = (25... |
"""A factory class that adapts DIPY's dMRI models."""
import warnings
import numpy as np
from dipy.core.gradients import gradient_table
class ModelFactory:
"""A factory for instantiating diffusion models."""
@staticmethod
def init(gtab, model="TensorModel", **kwargs):
"""
Instatiate a dif... |
import os
from sqlalchemy import (Boolean, CheckConstraint, Column, DateTime, Enum, ForeignKey, Integer, String, Table, Text,
UniqueConstraint)
from sqlalchemy.orm import backref, deferred, relationship
from .database import Base
from .nb_helpers import safe_read_notebook
DATABASE_URL = os.en... |
import re
from os.path import isfile, join
from os import listdir, walk
from datasets import Dataset, load_dataset, load_metric, concatenate_datasets
import torchaudio
import librosa
import numpy as np
from transformers import Wav2Vec2Processor
from transformers import Wav2Vec2ForCTC
import torch
import random
import ... |
import requests
import json
""" 这是原始思路 """
class Dict(dict):
__setattr__ = dict.__setitem__
__getattr__ = dict.__getitem__
def dict_to_object(dictObj):
if not isinstance(dictObj, dict):
return dictObj
inst=Dict()
for k,v in dictObj.items():
inst[k] = dict_to_object(v)
return ... |
from pathlib import Path
def parse_vad_label(line, frame_size: float = 0.032, frame_shift: float = 0.008):
"""Parse VAD information in each line, and convert it to frame-wise VAD label.
Args:
line (str): e.g. "0.2,3.11 3.48,10.51 10.52,11.02"
frame_size (float): frame size (in seconds) that i... |
from loader import *
from collections import Counter
import math
from commons import CATEGORICAL, ORDINAL, SEQUENTIAL, RATIO_INTERVAL, HIERARCHICAL, COUNTS, OTHER, YEAR
import logging
import numpy as np
from commons.logger import set_config
logger = set_config(logging.getLogger(__name__))
from dateutil import parser
... |
import re
from flask import Blueprint, redirect, url_for, render_template, flash, request
from flask_login import current_user, logout_user, login_user, login_required
from app.extensions import openid, db
from app.models.user import User
from .forms import (LoginForm,
RegisterForm,
... |
##################################################
## syna.py
## Menu assistant for SSD1306 Displays
## on ESP32 and ESP8266
##################################################
## Author: <NAME>
## Copyright: Copyright 2021, Lipurd
## License: MIT License
## Version: 0.2.0
###############################################... |
from typing import Union
import time
import numpy as np
from xnmt import batcher, input, loss, vocab, events, util
class AccumTimeTracker(object):
def __init__(self):
self.start_time = None
self.accum_time = 0.0
def __enter__(self):
self.start_time = time.time()
def __exit__(self, *args):
sel... |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
import re
import subprocess
import sys,os
COMMAND_SUCCESS = 0
COMMAND_ERROR = 1024
def get_output(cmd):
"""Runs command described by lst and returns (output, returncode)."""
try:
child = subprocess.Popen(cmd, stdout = subprocess.PIPE, stderr = subprocess... |
import json
from typing import Iterator
MIN_DATE = "2000-01-01T00:00:00"
MAX_DATE = "2014-08-29T23:59:59"
STATEMENTS = {
'CS01': 'SELECT COUNT(*) FROM call_center',
'CS02': 'SELECT COUNT(*) FROM catalog_page',
'CS03': 'SELECT COUNT(*) FROM catalog_returns',
'CS04': 'SELECT COUNT(*) FROM catalog_sales'... |
from flask_webhook_server.base import BasePacket
import os
from typing import Optional, Union
import requests
import dotenv
import hashlib
from flask import Flask, request
from logging import Logger
from requests.models import Response
from . import BaseWebhook, AbstractConnector
class RtmConnector(AbstractConnecto... |
from uuid import uuid4
import requests
import json
from random import sample
from os.path import exists
from gzip import GzipFile
import time
import threading
import logging
logger = logging.getLogger(__name__)
# number of node that each node send the message to in the P2P network
ADJENCENT_NODES=3
from block impor... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Note: To use the "upload" functionality of this file, you must:
# $ pipenv install twine --dev
import io
import os
import sys
import subprocess
from shutil import rmtree
from setuptools import find_packages, setup, Command, Extension
from distutils.command.build_ext ... |
import requests
import argparse
import logging
import pathlib
import time
import json
import os
AUTHORIZATION_BEARER = "" #= "Bearer cHecTjbI4CTu7TrqlAKOVicGNnx65dKwhs4SvdqPXXzN7AXClnW4uDX4m0oJ"
CURRENT_PATH = pathlib.Path(__file__).parent.absolute()
START_TIMESTAMP = 0 #1567296000
END_TIMESTAMP = 0 #1598918400
SECON... |
import sys, random, math
from PyQt5.QtWidgets import *
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QPainter, QColor
from multiprocessing import Process
xMin = -3
xMax = 3
yMin = -3
yMax = 3
#widthScale = 3
#heightScale = 3
zoomLevel = 4
class Mandelbrot(QWidget):
def __init__(self):
super().__ini... |
# ----------------------------------------------------------------------------
# pyglet
# Copyright (c) 2006-2008 <NAME>
# Copyright (c) 2008-2020 pyglet contributors
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following c... |
# from demo.webcam import main
import torch
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
import argparse
import cv2
from maskrcnn_benchmark.config import cfg
from predictor import COCODemo
import time
import os
import json
import numpy as np
def dataloader(img):
par... |
#!/usr/bin/env python3
from argparse import ArgumentParser
from os import path
import sys
from pathlib import Path
from zipfile import ZipFile
def files(*dir, suffix=''):
"""Returns the list of files in ``dir``, optionally filtering files with suffix ``ext``."""
return filter(lambda e: e.is_file(), Path(path... |
#!/usr/bin/env python3
import numpy as np
import os
import struct
import binascii
def writeRawIV(data, filename, spacings):
"""Writes an array to a rawiv file specified by filename."""
assert isinstance(data, np.ndarray), "Data is not a NumPy array!"
assert len(data.shape) == 3, "Data does not have 3 di... |
#!/usr/bin/python3
##
## A script to set up and launch the Zosterops phylogeny experiments.
##
## following the script from <NAME>, 16/02/2021
## <NAME>, 14/05/2021
# NOTE: make sure to copy/symlink this to the model root folder before running
import os, sys, shutil, time, subprocess
## PARAMETERS AND VARIABLES
# S... |
# This file is a part of PDDLRL project.
# Copyright (c) 2020 <NAME> (<EMAIL>)
# Copyright (c) 2021 <NAME> (<EMAIL>, <EMAIL>), IBM Corporation
import os
from typing import Any, Optional, Protocol, Mapping
import gin
import numpy as np
import dm_env
import acme
from acme.agents import agent
from acme.jax import sav... |
# Autores: <NAME> y <NAME>.
# Este código está bajo la licencia de MIT.
import socket, time
from _thread import *
# Numero maximo de jugadores concurrentes
JGD_MAX = 20
# Numero de puerto
PUERTO = 8080
# Llave para dejar entrar al cliente
KEY = "<KEY>"
zoc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
zoc.... |
import numpy as np
import roipool3d_cuda
import torch
from lib.datasets.kitti import kitti_utils
def roipool3d_gpu(pts, pts_feature, boxes3d, pool_extra_width, sampled_pt_num=512):
"""
:param pts: (B, N, 3)
:param pts_feature: (B, N, C)
:param boxes3d: (B, M, 7)
:param pool_extra_width: float
... |
import pathlib
import os
import tensorflow as tf
import numpy as np
import model
import losses
import dataset_helpers
DATA_PATH = os.path.realpath(os.path.join(__file__, '../../data'))
SHAPE_BASIS_PATH = os.path.join(DATA_PATH, "shape_basis.npy")
SHAPE_MEAN_PATH = os.path.join(DATA_PATH, "shape_mean.npy")
EXPR_BASIS_... |
# -*- coding: utf-8 -*-
from datetime import datetime, timedelta
import leather
import pytz
from cairosvg import svg2png
from django.core.mail import EmailMultiAlternatives
from django.template.loader import get_template
from email.mime.image import MIMEImage
from premailer import transform
from .config import daily_... |
# On Raspberry Pi
from DoSomething import DoSomething
import tensorflow as tf
import base64
import datetime
import time
import json
import os
import numpy as np
root = '010121'
class SignalGenerator:
def __init__(self, labels, sampling_rate, frame_length, frame_step,
num_mel_bins=None, lower_frequency... |
#!/usr/bin/env python
COMMAND_RIGHT = b'B'
COMMAND_LEFT = b'T'
COMMAND_TOP = b'L'
COMMAND_BOTTOM = b'R'
COMMAND_ON = b'D'
COMMAND_OFF = b'U'
COMMAND_P = b'P'
class EgvParser:
def __init__(self):
self.command = None
self.distance = 0
self.number_value = 0
@staticmethod
def skip(r... |
import os
from discord import NotFound
from discord.ext.commands import Cog
from datetime import datetime
import re
import json
class Log(Cog):
def __init__(self, bot):
self.bot = bot
self.bot.update_logs = self.update_logs
self.re_lastentry_num = re.compile(r".*([0-9])\).*$")
... |
'''這是一個類似電子經典遊戲 Pong的遊戲
主要內容就是用下方的橫版不斷將球往上頂回去
若是讓球掉下去就結束了
使用方向鍵左右遊玩 一次移動只能按左或者按右
'''
'''
總共建立了 3個 Class Ball , Paddle , Pong
in class Ball's init function create 7 variables to accept parameters
(x,y座標 vx,vy 速度 width,height 長寬 color 顏色)
use function "render" and "@Property" decorator to draw the ball
and third f... |
import argparse
import time
import numpy as np
import torch
from torch import nn, optim
import torch.utils.data
from torch.utils.tensorboard import SummaryWriter
from torchvision import models
from .dataset import Dataset
from .data_utils import load_train_df, TRAIN_ROOT, CLASSES, train_valid_split
def main():
... |
import aiohttp
import asyncio
from typing import (
Any,
Dict,
List,
Union,
TypeVar
)
from urllib.parse import quote as uriquote
__all__ = (
"Route",
"Library",
"Compiler",
"Language",
"LanguageStream",
"LibraryVersion"
)
LT = TypeVar('LT', bound='Language')
class Route:
BASE: str = "https:/... |
import time
import cv2
import numpy as np
import pandas as pd
import torch
import torchvision
import torchvision.transforms as T
from torch.utils.data import DataLoader, Dataset
from torch.utils.tensorboard import SummaryWriter
from torchvision.models.detection.faster_rcnn import FastRCNNPredictor
# Writer will outpu... |
#!/usr/bin/env python
# Copyright 2014-2018 The PySCF Developers. 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
#
# U... |
import datetime
import re
from typing import List
from django import template
from django.conf import settings
from django.urls import reverse
from django.utils.functional import SimpleLazyObject
from magplan.models import Vote, Comment
from magplan.utils import safe_cast
from magplan.views import posts, ideas
regis... |
import struct
import math
from obj_loader import obj_loader
def char(c):
return struct.pack("=c", c.encode('ascii'))
def word(c):
return struct.pack("=h", c)
def dword(c):
return struct.pack("=l", c)
def color(r, g, b):
return bytes([b, g, r])
class Bitmap(object):
def __init__(self, width, hei... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import numpy as np
import qutip as qt
from keras.models import Sequential
from keras import regularizers
from keras.layers.core import Dense, Activation, Flatten
from keras.layers.convolutional import (Convolution2D, MaxPooling2D)
from keras.optimizers import SGD
from kera... |
"""Coba global configuration functionality."""
import sys
import json
import collections
import traceback
from pathlib import Path
from typing_extensions import Literal
from typing import Dict, Any, Iterable
from coba.exceptions import CobaException
from coba.registry import CobaRegistry
from coba.utilities import c... |
from fbs_runtime.application_context.PyQt5 import ApplicationContext
from PyQt5.QtWidgets import QMainWindow
from PyQt5.QtWidgets import QApplication, QMainWindow, QCheckBox, QLabel, QComboBox, QPushButton, QHBoxLayout, QVBoxLayout, QGridLayout, QDialog, QDateEdit, QTextEdit
from PyQt5 import QtCore, QtGui
from PyQt5.Q... |
from __future__ import print_function
import time
from gocd_cli.command import BaseCommand
from gocd_cli.utils import get_settings
from .check import Check
from .retrigger_failed import RetriggerFailed
__all__ = [
'Check',
'CheckAll',
'List',
'Pause',
'RetriggerFailed',
'Trigger',
'Unloc... |
import sys
from pathlib import Path
from datetime import datetime, timedelta
import json
from jirahub import command_line
from jirahub.jirahub import IssueSync
from jirahub.entities import Source
from . import mocks
CONFIG_DIR = Path(__file__).parent / "configs"
CONFIG_PATH = CONFIG_DIR / "full_config.py"
BASE_CONF... |
# SPDX-License-Identifier: Apache-2.0
# Copyright 2020 igo95862
# 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 ... |
# In addition to length of edges, the graph has vertex costs associated with it. Let us define the
# cost of the path as the sum of the costs of its edges and sum of the costs of the vertices (along
# with the ends). Find the cheapest paths between the starting vertex and all the other vertices.
# Find a solution for d... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.