text stringlengths 3.07k 12.6k |
|---|
from typing import Union, Dict, Pattern, Callable, Any, List
import re
import logging
log = logging.getLogger('foo')
class ValidationError(Exception):
def __init__(self, reason):
super().__init__()
self.reason = reason
class RequiredKey:
def __init__(self, key: str):
self.key = key
... |
"""
Module that holds the entry point for the console.
"""
import sys
import json
import signal
import logging
import cProfile
import pstats
from spotdl.console.save import save
from spotdl.console.sync import sync
from spotdl.download import Downloader
from spotdl.console.preload import preload
from spotdl.console.d... |
import math
import torch
import torch.nn as nn
from locked_dropout import LockedDropout
class Chomp1d(nn.Module):
def __init__(self, chomp_size):
super(Chomp1d, self).__init__()
self.chomp_size = chomp_size
def forward(self, x):
return x[:, :, :-self.chomp_size].contiguous()
class TC... |
# -*- coding: utf-8 -*-
"""Test suite for axonius_api_client."""
import os
import pathlib
import pytest
from axonius_api_client import PACKAGE_ROOT
from axonius_api_client.setup_env import (
KEY_CERTWARN,
KEY_DEFAULT_PATH,
KEY_ENV_FILE,
KEY_ENV_PATH,
KEY_KEY,
KEY_OVERRIDE,
KEY_SECRET,
... |
import threading
from abc import ABCMeta, abstractmethod
from asyncio import iscoroutine
from concurrent.futures import Future
from contextlib import AbstractContextManager
from types import TracebackType
from typing import (
Any, AsyncContextManager, Callable, ContextManager, Coroutine, Optional, Tuple, Type, Type... |
# Copyright 2021 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import annotations
import re
import sys
from dataclasses import dataclass
from itertools import chain
from typing import Iterator
#
# Note: This file is used as an pex en... |
# The MIT License (MIT)
#
# Copyright (c) 2020 <NAME> for Adafruit Industries LLC
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the right... |
from django.test import TestCase
from django.conf import settings
from django.contrib.auth.models import User
from django.contrib.sessions.middleware import SessionMiddleware
from rest_framework.test import APIRequestFactory, force_authenticate
from rest_framework import status
from .models import GradeInfo
from .view... |
import unittest
import pytest
import os
from PIL import Image
from benfords_law_utils.utils import calculate_benford_stats, ascii_art_bar_graph, calculate_benford_stats_for_image, \
get_pixel_values
def test_calculate_benford_stats_for_empty_input():
counts, ratios, total_count = calculate_benford_stats([])
... |
# Tutorial example. Doesn't depend on any third party GUI framework.
# Tested with CEF Python v57.0+
from cefpython3 import cefpython as cef
import base64
import platform
import sys
import os
import threading
def main():
check_versions()
sys.excepthook = cef.ExceptHook # To shutdown all CEF processes... |
# -*- coding: utf-8 -*-
"""
celery.contrib.batches
======================
Experimental task class that buffers messages and processes them as a list.
.. warning::
For this to work you have to set
:setting:`CELERYD_PREFETCH_MULTIPLIER` to zero, or some value where
the final multiplied value is higher than... |
import json
import requests
import isDaylight
from time import sleep as sleep
from tools import xbmclog
from tools import xbmcinfo
class Light(object):
def __init__(self, bridge_ip, username, light_id, spec):
self.bridge_ip = bridge_ip
self.username = username
self.light_id = light_id
... |
# The code here is a translation of the MATLAB code provided at
# https://www.mathworks.com/matlabcentral/fileexchange/41459-6-functions-for-generating-artificial-datasets
import numpy as np
def spirals(N = 1000, degrees = 570, start = 90, noise = 0.2):
"""
Generate "two spirals" dataset with N instances.
... |
# -*- coding: utf-8 -*-
"""command line of scar"""
import argparse
# from distutils.command.config import config
import os
import pandas as pd
from ._scar import model
from .__version__ import __version__
def main():
"""main function for command line interface"""
args = Config()
count_matrix_path = args... |
from dataclasses import dataclass
import torch
from ganslate.nn.gans.unpaired import cyclegan
from ganslate.nn.losses.adversarial_loss import AdversarialLoss
from projects.maastro_hx4_pet_translation.modules.hx4_cyclegan_balanced_losses \
import HX4CycleGANBalancedLosses
@dataclass
class HX4CycleGANBalancedCon... |
"""
一个简单的 unix 代理工具,用于中间人劫持获取数据包,解析 iOS 与 usbmuxd 传输过程时,转换成明文数据
使用方法:
1.sudo chmod 777 /var/run/
2.sudo mv /var/run/usbmuxd /var/run/usbmuxx
3.python /tools/unix_socket.py
4.恢复 sudo mv /var/run/usbmuxx /var/run/usbmuxd
"""
import logging
import os
import sys
sys.path.append(os.getcwd())
import plistlib
import re
i... |
"""Registry of semantic properties for robots. A robot typically consists of a
set of parts, a base (either fixed or moving), end effectors, and other
assorted properties. This module provides utilities to help build generalized
code.
"""
class EndEffectorInfo:
"""Stores info about default end effectors and the ... |
#MIT License
#Copyright (c) 2021 <NAME>
#Permission is hereby granted, free of charge, to any person obtaining a copy
#of this software and associated documentation files (the "Software"), to deal
#in the Software without restriction, including without limitation the rights
#to use, copy, modify, merge, publis... |
# -*- coding: utf-8 -*-
import pytest
from tornado.testing import gen_test
from web_app.tests.utils import execute_scheme, VdiHttpTestCase
from web_app.tests.fixtures import (
fixt_db, # noqa: F401
fixt_redis_client,
fixt_auth_context, # noqa: F401
fixt_user, # noqa: F401
fixt_user_admin, # noq... |
# -*- coding: UTF-8 -*-
import argparse
import json
import sys
import os
import zlib
from git import Repo
from flask import Flask, url_for
from flask_sqlalchemy import SQLAlchemy
import graphene
import graphql
from flask_graphql import GraphQLView
app = Flask(__name__)
app.config.from_object('config')
db = SQLAlche... |
from sys import exit
import pygame as game
game.init()
BLACK = (0, 0, 0)
CAPTION = "Solaris"
DARK_LIME_GREEN1 = (0, 137, 0) # dark lime green, first shade
DARK_LIME_GREEN2 = (0, 177, 0) # dark lime green, second shade
MODE_HEIGHT = 450
MODE_WIDTH = 850
PLAYER_HEIGHT = 80
PLAYER_WIDTH = 80
PURE_LIME_GREEN = (0, 235... |
"""
Alexa Skill for looking up Pokemon information on the PokeAPI.
http://amzn.to/1LzFrj6
http://amzn.to/1LGWsLG
"""
import os
import boto3
import requests
from base64 import b64decode
ENCRYPTED_SLACK_HOOK = os.environ['SLACK_HOOK']
# Decrypt code should run once and variables stored outside of the function
# handl... |
"""Grep dialog for Find in Files functionality.
Inherits from SearchDialogBase for GUI and uses searchengine
to prepare search pattern.
"""
import fnmatch
import os
import sys
from tkinter import StringVar, BooleanVar
from tkinter.ttk import Checkbutton # Frame imported in ...Base
from idlelib.searchbase impo... |
"""
Driver module for `vara-container`.
This module handles command-line parsing and maps the commands to tool suite
internal functionality.
"""
import logging
import typing as tp
from pathlib import Path
import click
import jinja2
from benchbuild.utils.settings import ConfigPath
from varats.containers.containers im... |
import face_alignment
import skimage.io
import numpy
from argparse import ArgumentParser
from skimage import img_as_ubyte
from skimage.transform import resize
from tqdm import tqdm
import os
import imageio
import numpy as np
import warnings
warnings.filterwarnings("ignore")
def extract_bbox(frame, fa):
if max(fra... |
import numpy as np
def mark_sites_with_chars(aln, target_list, size=1,
ignore_case=True, inverse=False,
copy=False, _sep='|'):
"""Adds markers to the alignment indicating which sites
matche/contain the target character or string.
Adds one marker for eac... |
"""Module containing class `DateTimeFormatter`."""
import itertools
import re
_FRACTION_CODE_RE = re.compile('%([1-6])f')
"""Regular expression for modified fraction codes."""
_FRACTION_PLACEHOLDER = '<~!@#$^&*>'
"""
Placeholder for modified fraction codes in `datetime.strftime` format string.
We replace modified... |
"""
helper functions for parsing response text from the JPL Horizons CGI.
these functions are intended to be called by LHorizon methods and should
generally not be called directly.
"""
import re
from io import StringIO
from typing import Optional
import numpy as np
import pandas as pd
from dateutil import parser as d... |
import json
import os
import re
from os.path import join as j
from os.path import exists
from requests import request
def get_current_cluster_name():
return request(url='http://gateway:51678/v1/metadata', method='get').json()['Cluster']
def is_reserved(key):
return re.match(r'^_.*$', key)
def is_optionnal... |
# coding: utf8
from pathlib import Path
from clldutils.misc import slug
from pylexibank.dataset import Dataset as BaseDataset
from pylexibank import FormSpec
DATAFILE = "Aslian_wordlists_Master_full+Maniq.tsv"
# some of the lexemes will be split into multiple lexemes.
# these have been checked to make sure the cognat... |
import os
import torch
import torch.nn as nn
from torch.utils.data import DataLoader
import data
from model.augmentation import SimpleTransform
from .base_evaluator import BaseEvaluator
class KNNEvaluator(BaseEvaluator):
@staticmethod
def add_commandline_args(parser):
parser.add_argu... |
"""
Copyright (c) 2018-2022 Intel 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 required by applicable law or agreed to in wri... |
from flask import Blueprint, jsonify, render_template, render_template_string, redirect, url_for, request, abort
from flask_login import current_user
import pendulum
from datetime import timezone
from dateutil import tz
from src import configuration
from flask_jwt_extended import create_access_token
# Blueprint Config... |
# Copyright 2021 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import annotations
import logging
from dataclasses import dataclass
from pants.backend.python.subsystems.twine import TwineSubsystem
from pants.backend.python.target_type... |
"""
playermesh
"""
from __future__ import absolute_import, division, print_function, unicode_literals
import logging
import os
import numpy
from OpenGL import GL
from mcedit2.rendering.chunkmeshes.entity.models import cookedModels
from mcedit2.rendering.chunkmeshes.entitymesh import entityModelNode
from mcedit2.r... |
#!/usr/bin/env python
# -*- coding=utf-8 -*-
import cv2
import argparse
import os
import numpy as np
import sys
from pathlib import Path
from PIL import Image
import string
import tensorflow as tf
from object_detection.utils import ops as utils_ops
sys.path.append(os.path.join(Path().resolve(), '..', 'crnn.pytorch')... |
#! /usr/bin/python
# -*- coding: UTF-8 -*-
# Copyright 2012 <NAME>, TestLink-API-Python-client developers
#
# 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/... |
# ------------------------------------------------------------------------------
#
# MIT License
#
# Copyright (c) 2018 <NAME>
#
# 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 restri... |
"""
This class is responsible cloning udp and tcp services
"""
import sys
from args_container import ArgsContainer
from login_manager import *
from util_functions import UtilFunctions
class LocalTcpToGlobal:
"""
This class moves tcp service object from local domain to global domain, by creati... |
# -*- coding: utf-8 -*-
#
# Copyright (2016-2017) Hewlett Packard Enterprise Development LP
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import pytest
import re
import yaml
from moc... |
from functools import partial
from typing import List, cast
from toolz import sliding_window # type: ignore
from tutils import (
UBoolInt,
lmap,
load_and_process_input,
nextwhere,
run_tests,
splitstriplines,
)
DAY = "09"
INPUT, TEST = f"input-{DAY}.txt", f"test-input-{DAY}.txt"
TA1 = None
TA2 ... |
import os
import threading
import time
import datetime
import subprocess
start_date = str(datetime.datetime.now().month) + "_" + str(datetime.datetime.now().day) + "_" + str(datetime.datetime.now().year)
cwd = os.getcwd() + "\\"
encoded = cwd + "Videos\\"
oneclick_file = cwd + start_date + "_oneclick.bat"
modellist = ... |
# Copyright 2008-2015 Nokia Networks
# Copyright 2016- Robot Framework 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
... |
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import torch.nn as nn
import torch
import sys
from fairseq import utils
from fairseq.distributed import utils as distributed_utils
from fairse... |
# -------------------------------------------------------------------------------------------------------------------
# this is a alpha version. need more work
# written by <NAME>
#
# things that i should add and fix:
# words list are bad (need better words file)
# add auto learn function for new words
# -------... |
from threading import Thread
# import pygame
# import speake3
import speech_recognition as sr
import numpy as np
import matplotlib.pyplot as plt
import cv2
from easygui import *
import os
from PIL import Image, ImageTk
from itertools import count
import tkinter as tk
import string
import platform
def play_music():
... |
from itertools import product as product
from math import ceil
import matplotlib.pyplot as plt
import numpy as np
import torch
from utils.config import cfg_mnet
#-----------------------------#
# 中心解码,宽高解码
#-----------------------------#
def decode(loc, priors, variances):
boxes = torch.cat((prio... |
# Copyright (c) Facebook, Inc. and its affiliates.
# Initial version was taken from https://github.com/ChenRocks/UNITER/
# and adapted for MMF.
from collections import namedtuple
from typing import Optional, Tuple
import torch
from mmf.utils.general import retry_n
from omegaconf import DictConfig, OmegaConf
from tor... |
from rest_framework.renderers import BaseRenderer, TemplateHTMLRenderer
from rest_framework import status
from tempfile import mkstemp
from pandas import DataFrame
try:
# Python 2 (uses str)
from StringIO import StringIO
except ImportError:
# Python 3 (Python 2 equivalent uses unicode)
from io import S... |
from mlagents.torch_utils import torch
import abc
from typing import Tuple
from enum import Enum
class Swish(torch.nn.Module):
def forward(self, data: torch.Tensor) -> torch.Tensor:
return torch.mul(data, torch.sigmoid(data))
class Initialization(Enum):
Zero = 0
XavierGlorotNormal = 1
Xavier... |
# -*- coding: utf-8 -*-
"""Classes for validating data passed to the annotations API."""
import copy
from pyramid import i18n
from h.schemas.base import JSONSchema, ValidationError
from h.util import document_claims
_ = i18n.TranslationStringFactory(__package__)
class AnnotationSchema(JSONSchema):
"""Validate... |
'''
Panopticon by <NAME>
Copyright (c) 2018, Valentijn "ev1l0rd" V.
All rights reserved.
Copyright 2016, <NAME>
This file is licensed under the BSD 3-clause License
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Red... |
import src.estimation.configuration as configs
import src.utils.plots as plots
from src.datasets.bighand.dataset import BighandDataset
from src.datasets.msra.dataset import MSRADataset
from src.estimation.architecture.jgrp2o import JGR_J2O
from src.estimation.metrics import MeanJointErrorMetric
from src.estimation.prep... |
# File : bpgen.py
# Author: AugFJTan
# Last Modified 7 Feb 2018 12:37 PM
import sys
import argparse
import platform
import time
available_languages = ("c", "cpp", "java", "python", "html")
comment_styles = ("c", "cpp", "python", "html")
author = "AugFJTan"
class Boilerplate:
def __init__(self, filename, ext, langu... |
#!/usr/bin/python
# -*- encoding: utf-8 -*-
from datasets import get_datasets
from utils.AttrDict import AttrDict
from config import load_cfg
from torch.utils.data import DataLoader
from models import get_model
from optimizer import Optimizer
import torch.nn as nn
import torch
import os
import sys
import logging
imp... |
#!/usr/bin/env python3
import csv
from git import Repo, exc
import matplotlib.pyplot as plt
from argparse import ArgumentParser
git_dir = "COVID-19"
path = "csse_covid_19_data/csse_covid_19_time_series/"
filename1 = "time_series_covid19_"
filename2 = "_global.csv"
modes = {"total":"number of cases","delta":"number of... |
"""
Standardized class and functions to test instruments for pysat libraries. Not
directly called by pytest, but imported as part of test_instruments.py. Can
be imported directly for external instrument libraries of pysat instruments.
"""
import datetime as dt
from importlib import import_module
import warnings
impo... |
import binascii
from io import BytesIO
from .serializers import *
from pycoin.block import Block
from .exceptions import NodeDisconnectException, InvalidMessageChecksum
import os
import codecs
class ProtocolBuffer (object):
def __init__ (self):
self.buffer = BytesIO()
self.header_size = MessageHeaderSerializer.ca... |
import yfinance as yf
from datetime import date
import tulipy as ti
import numpy as np
import pandas as pd
#MAIN- FUNCTION
def compute_study_data(symbol):
daily_3M, weekly_5Y, monthly_10Y = get_time_series_data(symbol)
performance = get_performance(weekly_5Y)
seasonality = get_seasonality(monthly_10Y)
... |
import numpy as np
from PIL import ImageGrab
import cv2
import time
from directkeys import ReleaseKey, PressKey, DirectionKey
import pyautogui
def roi(img, vertices):
#blank mask:
mask = np.zeros_like(img)
#filling pixels inside the polygon defined by "vertices" with the fill color
cv2... |
from measure.measure_average_precision import average_precision
from measure.measure_hamming_loss import hamming_loss
from measure.measure_ranking_loss import ranking_loss
from measure.measure_example_auc import example_auc
from measure.measure_example_f1 import example_f1
from measure.measure_one_error import one_erro... |
import torch
from pathlib import Path
from torch.utils.data import DataLoader
from svd.utils.io import load_model
from svd.core.audio import SVDDataset
from svd.train import prep_net_config
from svd.utils.progress import progress
from svd.core.model import SingingVoiceDetector
from svd.adversaries.raw_attack import o... |
from .. import db
from ..models.containers import (
Template,
TemplateContent
)
from ..models.container_schemes import (
TemplateSchema
)
from flask import Blueprint
from flask import (
abort,
jsonify,
make_response,
request
)
from flask_jwt_extended import (
jwt_required,
jwt_optio... |
import pytest
from vault_cli import environment, exceptions
def test_exec_command(mocker):
execvpe = mocker.patch("os.execvpe")
environment.exec_command(["a", "b"], {"C": "d"})
execvpe.assert_called_with("a", ("a", "b"), mocker.ANY)
args, __ = execvpe.call_args
assert args[2]["C"] == "d"
def ... |
#!/usr/bin/env python3
import os
import logging
import sys
import json
import subprocess
import traceback
import re
from github import Github
from pr_info import PRInfo
from s3_helper import S3Helper
from get_robot_token import get_best_robot_token
from docker_pull_helper import get_image_with_version
from commit_s... |
import sys
sys.path.insert(0, "../")
from blossom import find_perfect_matching
from blossom import find_maximum_matching, find_perfect_maximum_matching
from blossom import UGraph, generate_random_graph, generate_random_graph_w
test_uwgraph = []
test_uwgraph.append( [(0,1),(1,2),(0,2),(4,1),(1,3),(4,3),(3,6),(5,3),(5,... |
from rllab.algos.base import RLAlgorithm
import theano.tensor as TT
import numpy as np
from rllab.misc import ext
from rllab.misc.special import discount_cumsum
from rllab.sampler import parallel_sampler, stateful_pool
from rllab.sampler.utils import rollout
from rllab.core.serializable import Serializable
import rll... |
from flask import Flask, jsonify, make_response, request, session, escape
from flask_restful import Api, Resource
from flask_cors import CORS
from werkzeug.exceptions import abort
from datetime import timedelta
from Database import DBController
from Auth import AuthManager
from User import UserManager
from Logue import... |
# This module contains a series of functions for creating a fake dataset.
import numpy as np
from functools import partial
from astropy.wcs import WCS
from copy import deepcopy
def make_star_function(ad_base, nstars=10, border=0, radius=None,
fwhm=None, flux=1., seed=None):
"""
Create a ... |
""" Tests for the CumulusCI task module """
import unittest
import logging
import collections
import mock
from cumulusci.core.tasks import BaseTask
from cumulusci.core.config import BaseGlobalConfig
from cumulusci.core.config import BaseProjectConfig
from cumulusci.core.config import TaskConfig
from cumulusci.core.co... |
#!/usr/bin/env python3
# MIT License
#
# Copyright (c) 2021, <NAME>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use,... |
# -*- coding: utf-8 -*-
from jupyter_client.manager import start_new_kernel
from jupyter_client import KernelManager
from nbformat.v4 import output_from_msg
import os
from .. import config
from .base import PwebProcessorBase
from . import subsnippets
from IPython.core import inputsplitter
from ipykernel.inprocess imp... |
"""Example of an RNN in Myia.
Myia is still a work in progress, and this example may change in the future.
"""
import time
from dataclasses import dataclass
import numpy
from numpy.random import RandomState
from myia import ArithmeticData, myia, value_and_grad
# The following import installs custom tracebacks for ... |
# from print_tree import print_tree
'''
AVL Tree can be implemented similar to a Binary Search Tree.
Only change is that each node in AVL Tree maintain its Height and on Insert/Removal
of a Key, we need to balance the nodes.
Therefore, below implementation shows only insert and remove methods.
Re... |
#
# Copyright © 2020 Mergify SAS
# Copyright © 2018 <NAME> <<EMAIL>>
#
# 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... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
Copyright (c) 2013 <NAME> <<EMAIL>>
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... |
import json
import os
import subprocess
import sys
from ansi2html import Ansi2HTMLConverter
from flask import Flask, flash, redirect, render_template, request, url_for
from flask_wtf import FlaskForm
from wtforms import (BooleanField, IntegerField, SelectField, StringField,
SubmitField)
from wtfor... |
import socket
import threading
import logging
import platform
import traceflow
import struct
class socket_handler:
def __init__(self, daddr):
try:
self.raw_sock = socket.socket(
socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_RAW
)
except PermissionError as ... |
import abc
import logging
import time
from datetime import datetime
from datetime import timedelta
log = logging.getLogger(__name__)
class GaveUpError(Exception):
"""Raised by a :class:`Retryer` that has exceeded its maximum number of retries."""
pass
class DelayStrategy(object):
"""Used by a :class:`R... |
import csv
import gzip
import unicodedata
from pathlib import Path
def is_valid_owé_format(text, n=4, is_file=False, **kwargs): # Is this really needed? Maybe. Maybe not.
"""
Args:
text: The text to validate. Could be a text or file path. If file path, is_file should be True
n: Separator cou... |
import RPi.GPIO as GPIO
import sys
import json
import time
import subprocess
import datetime
import requests
import jwt
import paho.mqtt.client as mqtt
from pprint import pprint
sys.path.append("/home/pi/MFRC522-python")
from mfrc522 import SimpleMFRC522
from requests.exceptions import ConnectionError
GPIO.setwarnings... |
"""
Introduction
--------------
This python file contains the source code used to carry the data preparation
process
Code
------
"""
# -*- coding: utf-8 -*-
import logging
import pandas as pd
from pathlib import Path
from datetime import datetime
import sqlite3
BASE_RAW_DATA_DIR = 'data/raw'
"""
str: Base raw data ... |
"""
Creating training file from VOC dataset
>> wget -O ~/Data/VOCtrainval_2007.tar http://pjreddie.com/media/files/VOCtrainval_06-Nov-2007.tar
>> wget -O ~/Data/VOCtest_2007.tar http://pjreddie.com/media/files/VOCtest_06-Nov-2007.tar
>> wget -O ~/Data/VOCtrainval_2012.tar http://pjreddie.com/media/files/VOCtrai... |
# Written by <NAME> in 18/July/2020
# PyJoy math part,Contains classes used by various functions
class vec2:
def __init__(self, x, y):
self.x = x / 1000
self.y = y / 1000
class vec3:
def __init__(self, x, y, z):
self.x = x / 1000
self.y = y / 1000
self... |
# -*- coding: utf-8 -*-
"""
@create: 2017-10-13 11:10:34.
@author: name
@desc: template_maker
"""
import re
import os
import json
import codecs
from tornado import template
from tornado.options import options, define
FPAHT_DEFINE = '${fpath}'
FPATH = os.path.abspath(os.path.dirname(__file__))
# try:
# from fun... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import numpy as np
from obspy.signal.util import next_pow_2
from gmprocess.waveform_processing.fft import compute_and_smooth_spectrum
from gmprocess.waveform_processing.spectrum import \
brune_f0, moment_from_magnitude
# Options for tapering noise/signal windows
TAP... |
#!/usr/bin/env python3
import os
import json
import numpy as np
import argparse
import pandas as pd
from pprint import pprint
from collections import OrderedDict
from pygama import DataGroup
from pygama.io.daq_to_raw import daq_to_raw
from pygama.io.raw_to_dsp import raw_to_dsp
def main():
doc="""
"""
rt... |
from math import floor
import os
# TODO: Chop long single-words
# from PIL import ImageFont
from PIL import Image, ImageFont
ROOT_DIR = os.path.dirname(os.path.abspath(__file__))
def get_path(path):
return os.path.join(ROOT_DIR, path)
def wrap(font, text, line_width):
words = text.split()
... |
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.core.exceptions import PermissionDenied
from django.forms import ModelForm
from django.http import Http404, HttpRequest, HttpResponse
from django.shortcuts import get_object_or_404, redirect, render
from django.url... |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# Fichier: etoiles.py
# Auteur: <NAME>
"""
Exploitation du Catalogue of the Brightest Stars (Ochsenbein+ 1988).
Les fichiers :
catalog.dat
names.dat
doivent être téléchargés sur le site du catalogue et placés dans le dossier
du module.
Lien... |
# import
import pygame, os
# //== ** Attributes ** ==// #
WIDTH = 1024
HEIGHT = 768
SCREEN_SIZE = (WIDTH, HEIGHT)
SCREEN_CENTER = (WIDTH // 2, HEIGHT // 2)
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
BLUE = (0, 0, 255)
YELLOW = (255, 255, 0)
LighBlue = (173, 216, 230)
NotBlue = (1... |
from datetime import datetime
import os
import pandas as pd
import requests
from typing import Tuple
AUTH_KEY = '' # Add in your api_key here
def api_call(api_key: str, city: str, state: str, country: str = 'us') -> dict:
'''
Makes request to openweather map with all parameters
and returns... |
import random
import time
from scenic.core.distributions import Samplable, RejectionException, needsSampling
from scenic.core.lazy_eval import needsLazyEvaluation
from scenic.core.external_params import ExternalSampler
from scenic.core.workspaces import Workspace
from scenic.core.vectors import Vector
from scenic.cor... |
# -*- coding: utf-8 -*-
import json
import os
from collections import namedtuple
from PIL import ImageFont
Color = namedtuple("Color", ["red", "green", "blue", "alpha"])
def hex_to_tuple(color):
"""Converts a HTML-style RGB(A) hex-string to a
:py:class:`~skald.configuration.Color`.
:param color: A hex-s... |
import torch
import torch.nn as nn
import torch.nn.functional as F
from ops.dcn.deform_conv import ModulatedDeformConv
# ==========
# Spatio-temporal deformable fusion module
# ==========
class STDF(nn.Module):
def __init__(self, in_nc, out_nc, nf, nb, base_ks=3, deform_ks=3):
"""
Args:
... |
"""Tools related to identifying connections between different scales."""
from typing import List, Tuple, Any, Optional, Dict, Union, Set
from itertools import product
from strops.operators.models import Operator
from strops.schemes.models import ExpansionScheme, OperatorRelation
from networkx import MultiDiGraph, all... |
from datetime import datetime, timedelta
from logging import getLogger
from typing import Callable, List, Optional, Tuple
from jose import JWTError
from jose.jwt import decode, encode
from jsonschema.exceptions import ValidationError
from starlette.requests import Request
from watchmen_auth import AuthenticationDetai... |
import datetime
from django.conf import settings
from django.core.mail.message import EmailMultiAlternatives
from django.db import models
from django.template import Template
from django.template.context import Context
from djmoney.models.fields import MoneyField
class BicycleType(models.Model):
name = models.C... |
from __future__ import absolute_import
import logging
import enum
from typing import Any, List, Optional, Sequence, Tuple, TypeVar, Union, cast, Mapping
from django.utils.encoding import force_str
try:
from django.utils.functional import classproperty # type: ignore
except ImportError:
# Pre-Django 3.1
f... |
import torch
import torch.nn as nn
import math
from torch.optim import Adam
from d3rlpy.models.torch.imitators import create_probablistic_regressor
from d3rlpy.models.torch.q_functions import compute_max_with_n_actions
from .utility import torch_api, train_api
from .utility import compute_augmentation_mean
from .sac_i... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.