text stringlengths 3.07k 12.6k |
|---|
import logging
import uasyncio
import ubinascii
import utime
class MHZ19Exception(Exception):
pass
class MHZ19ChecksumException(MHZ19Exception):
pass
class MHZ19InvalidResponseException(MHZ19Exception):
pass
def calc_checksum(data):
csum = 0
for b in data:
csum = (csum + b) % 256
... |
import six
class RuleSet(object):
"""
Rule sets provide a convenient data structure to work with lists of
collection rules.
The rule set class enables operations using set operations (union,
difference, intersection) and simple syntax for addition and subtraction
using the +/- operators.
... |
import numpy as np
import numba
from scipy.interpolate import InterpolatedUnivariateSpline
from pax import plugin, dsputils
class NaturalBreaksClustering(plugin.ClusteringPlugin):
"""Split peaks by a variation on the 'natural breaks' algorithm.
Any gaps (distances between hits) in peaks larger than min_gap_s... |
import torch
import random
def create5Dimages(images):
# images : 4D tensor with shape [BT,C,H,W]
T = 16
B = images.size(0) // T
C = images.size(1)
H = images.size(2)
W = images.size(3)
image = torch.tensor([]).cuda()
for b in range(B):
bimage = images[b * T:(b + 1) * T, :, :, ... |
from nmigen import *
from nmigen.lib.fifo import AsyncFIFOBuffered
import os, sys, time, random, string, struct
import asyncio
from threading import Thread
from .. import Applet
from ...gateware import *
from ...host import *
SOURCE = "source"
SINK = "sink"
LOOPBACK = "loopback"
_all_modes = [SOURCE, SINK, LOOPBAC... |
'''
MIT License
Copyright (c) 2020 <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, publish, distri... |
'''Devices
===========
Defines some of the devices that are used in the experiment.
'''
__all__ = (
'FTDIOdorsBase', 'FTDIOdorsSim', 'FTDIOdors', 'DAQInDeviceBase',
'DAQInDeviceSim', 'DAQInDevice', 'DAQOutDeviceBase', 'DAQOutDeviceSim',
'DAQOutDevice')
from weakref import ref
from moa.device.digital im... |
# -*- coding: utf-8 -*-
import json
import os
import random
import time
import numpy as np
import requests
from apscheduler.schedulers.background import BackgroundScheduler
from apscheduler.executors.pool import ThreadPoolExecutor, ProcessPoolExecutor
from flask import Flask, request, jsonify
from collections import de... |
import imagezmq, time
from PIL import Image, ImageTk
import tkinter as tk
from threading import Thread, Event
import cv2
import logging
"""to handle multi thread processes."""
# class Plate:
# def __init__(self,image_rgb):
# self.image = image_rgb
# def perspective(self):
# logging.debug('per... |
"""Add "Use this" buttons into files that contain Git merge conflicts."""
from __future__ import annotations
import itertools
import tkinter
from typing import Callable
from porcupine import get_tab_manager, tabs, utils
from porcupine.plugins.linenumbers import LineNumbers
setup_after = ["linenumbers"]
def find_me... |
import torch
import torch.nn as nn
import torch.nn.functional as F
from .scalenorm import ScaleNorm
from .powernorm import MaskPowerNorm
class DownsampleConv(nn.Module):
def __init__(self, c_in):
super().__init__()
padding = 1 if torch.__version__ >= "1.5.0" else 2
self.downConv = nn.Conv... |
from abc import abstractmethod
from typing import (
TYPE_CHECKING,
Any,
Callable,
Generic,
List,
Optional,
Sequence,
TypeVar,
Union,
)
import numpy as np
from squad.constants import Direction
if TYPE_CHECKING:
from ..base import BaseState
T = TypeVar("T", bound="BaseState")... |
#!/usr/bin/env python
# pylint: disable=redefined-outer-name
"""The actual fixtures, you found them ;)."""
import logging
import re
import shutil
import subprocess
from pathlib import Path
from string import Template
from time import time
from typing import Generator, List, NamedTuple
import pytest
from _pytest.t... |
#!/usr/bin/python3
# Copyright 2021 Google LLC
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agr... |
#!/usr/bin/env python
import numpy as np
import os
import sys
import geometry_msgs.msg
import moveit_commander
import moveit_msgs.msg
import rospy
import torch
from moveit_commander.conversions import pose_to_list
from utils.pnet import PNet
def all_close(goal, actual, tolerance):
"""
used to check if the c... |
# 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, software
# d... |
'''A face detection app that uses the OpenCV python wrapper and
a face_recogniton library to detect faces, draw a red circle over and number over
them, print the coordinates of each face to the console, and save the face
detecting session to the current directory.
The opencv-python, face_recognition, and pyautogui m... |
import collections
import functools
import io
import os
# Python3, if using Python2 install pathlib from pypi.
import pathlib
import cogapp
visit_methods = collections.OrderedDict([
('file', ['Schema', 'schema::CodeGeneratorRequest::RequestedFile::Reader']),
('imports', ['Schema', 'List<Import>::Reader']),
... |
# -*- coding: utf-8 -*-
# Copyright (c) 2017, Direction and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe, erpnext
from frappe.utils import flt, cstr, nowdate, comma_and
from frappe import throw, msgprint, _
def pe_before_submit(self, method):
if... |
"""Light-weight mapping between sqlite3 and python data structures."""
import logging
import sqlite3
from typing import Any, Callable, Dict
LOG = logging.getLogger(__name__)
class DatabaseRow:
"""Base class for sqlite Row schemas."""
TABLE_NAME: str
FIELDS: Dict[str, Callable[[Any], Any]]
def __ini... |
# coding:utf8
import cv2
import sys
import numpy as np
try:
import pyscreenshot as ImageGrab
import pyautogui
import time
except Exception as e:
print(e)
class MovingDetector():
def __init__(self):
pass
def camera_detect(self, device=0, func=None):
self.camera = cv2.VideoCapt... |
import unittest
from facefit.esr.fern import *
from facefit.esr.fern import Fern
from facefit.util import *
def compare_arrays(self, a, b):
return self.failUnless(np.isclose(np.array(a), b, atol=1e-5).all())
# class ESRTest(unittest.TestCase):
# def test_fit_shape_to_box(self):
# shapes = [
# ... |
# Copyright 2016 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... |
import argparse
import pathlib
import csv
import json
import ecole as ec
import numpy as np
import random
import ConfigSpace.hyperparameters as CSH
# Import ConfigSpace and different types of parameters
from smac.configspace import ConfigurationSpace
#from smac.facade.smac_bo_facade import SMAC4BO
from smac.facade.s... |
import tkinter as tk
from tkinter import messagebox
import pymysql.cursors
import random
# December 14, 2016
# coded while listening to <NAME>
class mainProgram:
def __init__(self, master):
self.master = master
self.master.geometry("300x300")
self.master.title("FoodRand")
self.mas... |
import os
import uuid
import shutil
import string
from configparser import ConfigParser
from importlib import import_module
from os.path import join, dirname, abspath, exists, splitext
import scrapx
from scrapx.commands import ScrapxCommand
from scrapy.utils.template import render_templatefile, string_camelcase
from ... |
class EventsAttributes:
featured = "featured"
today = "today"
upcoming = "upcoming"
class EventAttributes:
class EventType:
key = "key"
name = "name"
class Server:
id = "id"
name = "name"
class Depature:
location = "location"
city = "city"
... |
import tkinter as tk
class Table(tk.Frame):
def __init__(self, master, line_with=1, xscroll=False, yscroll=False,
line_color="#dfe2e5", row_colors=("#f6f8fa", "#ffffff"), title_color="#e6e8ea", bg_color=None,
widths=None):
tk.Frame.__init__(self, master, bd=0)
sel... |
# write tests for bfs
import pathlib
import pytest
from search import graph
TRAVERSAL_ORDER = [
"<NAME>",
"31540829",
"31626775",
"31806696",
"32790644",
"33483487",
"<NAME>",
"<NAME>",
"<NAME>",
"<NAME>",
"<NAME>",
"29700475",
"30727954",
"30944313",
"32036... |
# vim: ft=python fileencoding=utf-8 sts=4 sw=4 et:
# Copyright 2015-2021 <NAME> (The Compiler) <<EMAIL>>
#
# This file is part of qutebrowser.
#
# qutebrowser 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, e... |
from sqlalchemy import (
Table,
Column,
Index,
Integer,
String,
Text,
Boolean,
ForeignKey,
UniqueConstraint,
)
from sqlalchemy.dialects.postgresql import JSONB
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import (
scoped_session,
sessionma... |
from dateutil.parser import parse as date_parser
from mock import Mock
import pytest
from easytrakt.models import Episode
from easytrakt.models import Movie
from easytrakt.models import MovieWatchlist
from easytrakt.models import Season
from easytrakt.models import Settings
from easytrakt.models import Show
def test... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# This file is part of CbM (https://github.com/ec-jrc/cbm).
# Author : <NAME>
# Credits : GTCAP Team
# Copyright : 2021 European Commission, Joint Research Centre
# License : 3-Clause BSD
import os
from os.path import join, normpath
from ipywidgets import (Text, V... |
from binascii import hexlify
import uuid
from cryptography import x509
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes
from flask import current_app
from commandment.mdm import commands
from commandment.mdm.app import command_router
from .commands import Prof... |
"""Implementation of various typing / preprocessing passes used in
the encoding.
.. testsetup::
import z3
from sloth import *
from sloth.encoder.astbuilder import ast
from sloth.utils import utils
"""
import collections
import z3
from ..utils import utils
from . import slast
def fold(f_inner, f_leaf,... |
## -*- coding: utf-8 -*-
## (C) 2015 <NAME>,
## This module is part of solthiruthi project under open-tamil umbrella.
## This code maybe used/distributed under MIT LICENSE.
from __future__ import print_function
import abc
import codecs
import copy
from tamil import utf8
# Suffix removal algorithm
class RemoveSuffi... |
# -*- coding: utf-8 -*-
"""
Created on Fri May 1 19:29:28 2020
@author: Mike
"""
##############################################################################
configfilename = "configfile.csv"
##############################################################################
import numpy as np
import pandas as pd
from... |
"""
Filter and re-grid Mean Height field (DEM) from grid-1 onto grid-2.
Notes:
Interpolate coordinates of grid-2 (x2/y2) onto grid-1
"""
import sys
import h5py
import pyproj
import numpy as np
import matplotlib.pyplot as plt
from netCDF4 import Dataset
from scipy.ndimage import map_coordinates
from scipy.ndimage ... |
import tempfile
from typing import Optional, List
import tarski.fstrips as fs
from tarski.benchmarks.blocksworld import generate_fstrips_blocksworld_problem
from tarski.benchmarks.counters import get_counters_elements, generate_fstrips_counters_problem
from tarski.fstrips import AddEffect, DelEffect, FunctionalEffect,... |
#!/usr/bin/python
from datetime import *
from ccalculator import *
"""
planets_cal=array("Sun","Moon","Moon_Node","Apogee","Mercury",
"Venus","Mars","Jupiter","Saturn","Uranus","Neptune","Pluto",
"Chiron","Quaoar","Sedna","Sgr AGalCtr");"""
planets_cal=["Sun","Moon","Moon_Node","Mercury","Venus","Mars","Jupi... |
# uncompyle6 version 2.9.10
# Python bytecode 2.7 (62211)
# Decompiled from: Python 3.6.0b2 (default, Oct 11 2016, 05:27:10)
# [GCC 6.2.0 20161005]
# Embedded file name: __init__.py
import _dsz
import dsz
import dsz.data
import dsz.lp
import mcl.tasking
import re
import sys
import Queue
import xml
import xml.sax
impor... |
#import necessary packages and libraries
import sys
import pandas as pd
import numpy as np
from nltk import pos_tag
import re
import nltk
from nltk.stem import WordNetLemmatizer
nltk.download('punkt')
nltk.download('stopwords')
nltk.download('averaged_perceptron_tagger')
nltk.download('wordnet') # download for lemmatiz... |
# YOLOv5 🚀 by Ultralytics, GPL-3.0 license
"""
Plotting utils
"""
import os
from pathlib import Path
import cv2
import matplotlib
import numpy as np
import torch
from PIL import Image, ImageDraw, ImageFont
from .general import (LOGGER, clip_coords, increment_path, is_ascii, is_chinese,
user_config_dir,... |
"""Visualizes CNN activation maps to see where the CNN focuses on to extract features.
Reference:
- Zagoruyko and Komodakis. Paying more attention to attention: Improving the
performance of convolutional neural networks via attention transfer. ICLR, 2017
- Zhou et al. Omni-Scale Feature Learning for Pers... |
import os
import re
import numpy as np
from collections import defaultdict
from bs4 import BeautifulSoup
import nltk
import spacy
# If needed, download POS tagger:
nltk.download('averaged_perceptron_tagger')
spacy_tagger = spacy.load("en_core_web_sm")
dictionary = defaultdict(set)
def html_to_ascii( writing ):
... |
import numpy as np
import chainer
from chainer import Variable
from chainer import variable
from chainer import reporter
from chainer import initializers
from chainer import Link, Chain
import chainer.functions as F
import chainer.links as L
from PIL import Image
class ConvLSTM(Chain):
def __init__(self, inp = 256... |
import datetime
import pandas as pd
from mlxtend.frequent_patterns import association_rules
from mlxtend.frequent_patterns import fpgrowth
from multiprocessing import Pool
from itertools import repeat
F_DATAS = r'data/dataset_2.csv'
def convert_to_set(value):
try:
return set(value)
except ValueError:... |
from datetime import datetime
from typing import Any, Dict, List, Optional, Tuple, Union
from uuid import uuid4
import pymongo
from box import Box
from cloudpathlib import AnyPath
from pymongo.errors import DuplicateKeyError
from pymongo.operations import UpdateOne
from .artifact import Artifact
YAMLETT_KEY = "__yam... |
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
import dwriteshapepy as dw
from pathlib import Path
import pytest
TESTDATA = Path(__file__).parent / "data"
ADOBE_BLANK_TTF_PATH = TESTDATA / "AdobeBlank.subset.met.ttf"
@pytest.fixture
def blankfont():
"""Return a subset of AdobeBlank.ttf... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Definition of kernels used for all particles (both in active and passive modes).
"""
import math
def StoreVariables(particle, fieldset, time):
"""
Store lon/lat before the are re-written.
Has to be the first kernel.
"""
if particle.active:
... |
import os
import re
import difflib
import shutil
from operator import itemgetter
def similar(seq1, seq2):
return difflib.SequenceMatcher(a=seq1.lower(), b=seq2.lower()).ratio()
artillery = re.compile(r"ar{1}.*y{1}")
cavalry = re.compile(r"ca{1}.*y{1}")
infantry = re.compile(r"inf{1}.*y{1}")
reserves = re.compile(... |
import os
import sys
import shutil
sys.path.append("model")
sys.path.append("utils")
import math
import numpy as np
import tensorflow as tf
from vae import VAE
from config import FLAGS
from batchloader import BatchLoader
def log_and_print(log_file, logstr, br=True):
print(logstr)
if(br):
logstr = l... |
import json
from fuzzywuzzy import fuzz, process
from sklearn.feature_extraction.text import TfidfVectorizer
import nltk
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize, sent_tokenize
from nltk.corpus import wordnet
import numpy as np
import sys
import re
import os
import pickle
# return docs... |
"""nftfw LogReader - used by the blacklist operation
Creates a data structure used by blacklist
"""
from pathlib import Path
from hashlib import md5
import logging
from .fileposdb import FileposDb
from .patternreader import pattern_reader
log = logging.getLogger('nftfw')
def log_reader(cf, update_position=True):
... |
import typing as t
from configuration.providers import DefaultConfigProvider
from configuration.enums import ConfigurationType, ConfigurationEnvVar
from configuration.helpers import ConnectionHelper
from configuration.renderers import ConfigRenderer, DefaultConfigRenderer
from configuration.defaults import DEFAULT_APP_... |
# coding=utf-8
# Copyright 2021 Google LLC
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed ... |
from functools import partial
import numpy as np
import pandas as pd
from sklearn.base import clone
from sklearn.model_selection import cross_val_score
from sklearn.metrics import make_scorer, mean_absolute_error, log_loss, accuracy_score
from dask import compute, delayed
np.random.seed(42)
def regression_accuracy(... |
import copy
import sys
from typing import Any, Generator
def flattenDictIter(d: dict,
prefix: list = []
) -> Generator[tuple[str, Any], None, None]:
for k in d:
if isinstance(d[k], dict):
yield from flattenDictIter(d[k], prefix=[*prefix, k])
else... |
#%%
from __future__ import print_function
import numpy as np
from edRVFL import tune_RVFL, calculate_acc
from Utils import to_categorical
import scipy.io
np.random.seed(813306)
# Function to collect the dataset
def read_mat_data(problem_path):
mat_data = scipy.io.loadmat(problem_path + '_R.mat')
x_data_mat... |
### This program inputs the dimensions and weight of a parcel then outputs ###
### the smallest parcel type available from a data table ###
import time
def data_table(rowname):
r0 = 'Type Max_weight/kg Max_length/mm Max_width/mm Max_height/mm'
r1 = 'Letter 0.1 240 165 5'
r2 = 'Large_letter 0.75 353 250 25... |
"""
Author: <NAME>
Copyright: (C) 2019-2020 <http://www.dei.unipd.it/
Department of Information Engineering> (DEI), <http://www.unipd.it/ University of Padua>, Italy
License: <http://www.apache.org/licenses/LICENSE-2.0 Apache License, Version 2.0>
"""
from visdom import Visdom
import time
import torch... |
#!/usr/bin/env python3
"""Common library for working with one-dimensional arrays.
This module provides functions for operating on lists and other array-like
collections. Examples include finding the argmin/argmax of a sequence,
calculating the cumulative sums of a list of numbers, and checking if two
sequences are pe... |
# Copyright 2020 ByteDance Inc.
#
# 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 writin... |
"""
Code to enable coverage of any external code called by the
notebook.
"""
import os
import coverage
import warnings
# Coverage setup/teardown code to run in kernel
# Inspired by pytest-cov code.
_python_setup = """\
import coverage
__cov = coverage.Coverage(
data_file=%r,
source=%r,
... |
import argparse
import pandas as pd
import swifter
import re
from typing import List, Optional, Dict
from pythainlp.tokenize import word_tokenize, sent_tokenize
def break_long_sentence(text:str, sent_tokenizer=sent_tokenize,
word_toknizer=word_tokenize,
max_sent_len=30... |
from fuzzywuzzy import fuzz
from itertools import zip_longest as zip
import gzip
import sys
import argparse
import re
def parse_args(argv):
parser = argparse.ArgumentParser(description = 'Help information')
parser.add_argument('file1', help='xxx.R1.fq')
parser.add_argument('file2', help='xxx.R2.fq')
... |
"""
Module with functions used in parrot-preprocess
.............................................................................
idptools-parrot was developed by the Holehouse lab
Original release ---- 2020
Question/comments/concerns? Raise an issue on github:
https://github.com/idptools/parrot
Licensed under ... |
'''
custom_install.py
This is a template to help users install custom grids to kiauhoku. The template
is based on the installation for YREC grids.
Necessary:
(1) a function called `setup` that returns a pandas MultiIndexed
DataFrame containing all your evolution tracks
(2) a variable `name` that is set to whatev... |
"""Module responsible for asynchronous data conversion."""
import io
import os
from tempfile import NamedTemporaryFile
from typing import List
import numpy as np
import SimpleITK as sitk
from PIL import Image
from celery.utils.log import get_task_logger
from medtagger.types import ScanID
from medtagger.workers import... |
#!/usr/bin/env python
# coding: utf-8
import streamlit as st
import streamlit.components.v1 as components
import matplotlib.pyplot as plt
import kayak
from PIL import Image
import numpy as np
filename_airport = './assets/airports.csv'
filename_aircraft = './assets/aircraft.csv'
output = './assets/output.xlsx'
blan... |
# Copyright 2021 The Bellman Contributors
#
# 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... |
import time
from collections import namedtuple
import numpy as np
import tensorflow as tf
with open('anna.txt') as f:
text = f.read() # reads some quantity of data and return it as a string or bytes object
vocab = sorted(set(text))
vocab_to_int = {c: i for i, c in enumerate(vocab)}
int_to_vocab = dict(enumerate(voc... |
import numpy as np
import scipy.linalg as la
import pyccl as ccl
import matplotlib.pyplot as plt
import copy
import sacc
## settings
lmin=10
lmax=500
dl=10
zbins=[0.5,0.7,0.9,1.1]
zbin_size=0.1
def main(dic_par):
cosmo=ccl.Cosmology(ccl.Parameters(Omega_c=dic_par['omega_c'],Omega_b=dic_par['omega_b'],h=dic_par... |
from nylas.client.restful_models import RestfulModel, Message, File, Contact
import re
def _add_options_to_body(body, options):
options_dict = options.__dict__
# Only append set options to body to prevent a 400 error
options_filtered = {k: v for k, v in options_dict.items() if v is not None}
return bo... |
import tkinter.messagebox as msgbox
import tkinter as tk
from numpy import array
from tkinter import *
from tkinter import filedialog
from tkinter import ttk
from copy import deepcopy
N=0
A = []
L = []
U = []
I = []
B = []
temp = []
x = []
y = []
def resize(N): # 테이블 재할당
global A, L, U, temp... |
import itertools
import os
import random
import sys
import inspect
import numpy as np
import collections
import ast
def get_arguments(insp_classes):
"""
Get args and kwargs of the class methods
Parameters
----------
insp_classes : list
Classes to inspect
"""
mapped_classes = []
... |
import os
import re
import sys
import time
from datetime import datetime
from forex_python.converter import CurrencyRates
from pathlib import Path
def validate_date(date_text):
"""Validates that the date is in ISO 8601 format: YYYY-MM-DD"""
try:
if date_text != datetime.strptime(date_text, "%Y-%m-%d"... |
# Liet ke cac ky tu
list_character = []
for i in range(65, 91):
if chr(i) != 'J':
list_character.append(chr(i))
# Tao khoa
key = 'playfairexample'
key = key.upper()
print('Khoa: %s' %key)
list_key = []
for i in range(0, len(key)):
if key[i] not in list_key:
list_key.append(key[i])
#print(li... |
# -*- coding: utf-8 -*-
# @Time : 2020/7/14
# @Author : <NAME>
# @File : .py
# @Role :
from datetime import datetime
import shortuuid
from tornado.web import RequestHandler
from libs.base_handler import BaseHandler
from sqlalchemy import or_
from libs.pagination import pagination_util
from models.pocsutie_d... |
#
# For licensing see accompanying LICENSE file.
# Copyright (C) 2020 Apple Inc. All Rights Reserved.
#
import torch
from torch import nn, Tensor
from typing import Optional
import argparse
from utils import logger
from .base_layer import BaseLayer
class LinearLayer(BaseLayer):
def __init__(self,
... |
import argparse
import os
import pathlib
import sys
from matplotlib import ticker
import config
import matplotlib.pyplot as plt
from matplotlib.offsetbox import OffsetImage, AnnotationBbox
def scatterImage(paths, similarities, zoom=0.03, jenks_breaks=3, size=(50,50)):
fig, ax = plt.subplots(figsize=size)
... |
import os
from ..plotting.plotmultifiles import PlotMultiFiles
from ..plotting.plotmultitough import PlotMultiTough
from ..plotting.plottough import PlotTough
class FileReadSingle(object):
def __init__(self, simulatortype, filelocation, filetitle, **kwargs):
"""
Class for processing single file r... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from behave import *
import urllib3
import json
import socket
import time
from helpers.eventually import eventually
@given('{service} {tenant} is onboarded')
def onboard_unit(context, service, tenant):
assert service in ['vault', 'ledger']
uri = "https://127.0.0.1:... |
import copy
from typing import Dict, Tuple
from collections import deque
from parse_toys.grammar import Symbol, Grammar
__all__ = ['eliminate_epsilon_rules', 'eliminate_unit_rules', 'to_chomsky_normal_form']
def eliminate_epsilon_rules(grammar: Grammar,
init_nullable: bool = True,
... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** 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... |
from django.http import Http404, HttpResponseRedirect
from django.shortcuts import get_object_or_404, render
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.urls import reverse
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from d... |
import argparse
import functools
import numpy as np
import equations
import data
from scipy.stats import ks_2samp
import pickle
from gp_utils import *
import sys
import os
def gp_post(f_star, ode, tol=None, expand=False):
VarDict = ode.get_var_dict()
f_star_list, var_list, coef_list = parse_program_to_list(... |
import tensorflow as tf
import tensorflow_io as tfio
import os
import time
''' Util functions used for the tf.data.Dataset pipeline '''
#============================== PREPROCESSING ==============================
def wrapper_cast(x):
x['audio'] = tf.cast(x['audio'], tf.float32)
try:
x['noise_wav'] = ... |
import os
import re
import time
from django.test import TestCase
from django.conf import settings
from django.core import mail
from django.core.exceptions import FieldError
from django.urls.base import reverse_lazy
from django.test.client import Client
from django.contrib import auth
from selenium.webdriver.common.ke... |
#!/usr/bin/env python3
# Copyright 2017-present, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
"""Rank documents with TF-IDF scores"""
import logging
import numpy as np
import scipy.sparse as sp
from mult... |
###############################################################################
# Module Imports
###############################################################################
import scpper.utils
from typing import Callable, List, Any
import json
try:
from functools import cached_property
except ImportError:
... |
# Copyright 2019 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 required by applicable law or a... |
import os
from io import StringIO
from fastapi import FastAPI, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates
from uuid import uuid4
from starlette.responses import StreamingResponse
from src.core.sequence_utils imp... |
#!/usr/bin/env python3
#-*-coding:utf-8-*-
import base64
import configparser
import click
import csv
import glob
import json
import pathlib
import requests
import shutil
import sys
import time
import urllib
from datetime import datetime
from tqdm import tqdm
def print_version(ctx, param, value):
if not value or ... |
from flask import render_template, url_for, flash, redirect,request
from Restaurant import app,db
from Restaurant.forms import RestaurantForm
from Restaurant.model import Restaurant, MenuItem
""" """
#JSON APIs to view Restaurant Information
@app.route('/restaurant/<int:restaurant_id>/menu/JSON')
def restaurantMenuJS... |
import pygame as pg
import time
# pylint has problems detecting members of pygame, so disabling it
#pylint: disable=no-member
pg.init()
pg.font.init()
WHITE = (217, 217, 217)
BLACK = (55, 55, 55)
RED = (255, 0, 0)
GRN = (0, 255, 0)
VEHIC = (100, 100, 200)
VEH_RAD = ((18)**0.5)*4
def scale(v, a, b, c, d):
inp_... |
from tqdm import tqdm
import numpy as np
import cv2
import os
from random import shuffle
from tensorflow.keras.preprocessing.image import ImageDataGenerator, img_to_array, load_img
def augmentation(source,labels,image_size):
datagen = ImageDataGenerator(
# rotation_range=40,
width... |
import json
import requests
from django.http import JsonResponse, HttpResponse
from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt
from apps.web.forms.file import FileFolderModelForm, FileUploadModelForm
from apps.web.models import FileRepository
from utils.cos import delete_file, ... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals, division
import six
import requests
from xml.etree import cElementTree
from xml.etree.cElementTree import ParseError
from beam.resource import Resource
@six.python_2_unicode_compatible
class HostIdentity(object):
"""
Represents identification ... |
# Copyright (c) Django Software Foundation and individual contributors.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright no... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.