text stringlengths 3.07k 12.6k |
|---|
"""AI trainer."""
# credit:
# <NAME>'s example
import string
# pylint: disable=E0401
import torch
from torch import nn, optim
from torch.nn import functional as fnl
from torch.utils import data
import torchtext
import numpy as np
import pandas
import nltk
from transformers import AutoTokenizer, BertModel, BertCon... |
import numpy as np
import tensorflow as tf
import h5py
from sklearn.preprocessing import OneHotEncoder
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import time
import sys
# Download data from .mat file into numpy array
print('==> Experiment 5a')
filepath = 'exp1l_C1.mat'
print('... |
"""Save DOT code objects, render with Graphviz dot, and open in viewer."""
import codecs
import logging
import os
import typing
from . import backend
from . import base
from . import encoding
from . import saving
__all__ = ['Pipe', 'Render']
log = logging.getLogger(__name__)
class Pipe(base.Base, backend.Graphvi... |
import nltk
from nltk.stem import WordNetLemmatizer
import json
# things we need for Tensorflow
import numpy as np
import keras
from keras.preprocessing.sequence import pad_sequences
from keras.models import Sequential
from keras.layers import Dense, Activation, Dropout
from keras.layers import Dense, Embedding
from... |
import os
import struct
import numpy as np
import paddle.fluid as fluid
from paddletools import logger
from paddletools.config import short2size, type2short
from paddletools.utils.decoder import _decode_buf
from paddletools.utils.encoder import _encode_tensor_desc
__all__ = ["static2dynamic", "pdparams2static", "torc... |
import random
import re
# lets create a board object to represent the minesweeper game
# this is so that we can just say "create a new board object", or
# "dig here", or "render this game for this object"
class Board:
def __init__(self, dim_size, num_bombs):
# let's keep track of the parameters.
sel... |
# reference EVO toolkit
from evo.tools import file_interface
from evo.tools.file_interface import csv_read_matrix, FileInterfaceException
from pysvso.lib.maths.rotation import Euler, Quaternion
import numpy as np
import logging
from pysvso.lib.log import LoggerAdaptor
_logger = logging.getLogger("validation.tum")
f... |
#%% importing libs
import torch
import pytorch_lightning as pl
import torch.nn as nn
import numpy as np
from torch.utils import data as DataUtil
from torchsummaryX import summary
#%% Defining datasets
num_data = 1024
data_dim = 128
batch_size = 1024
out_dim = 4
num_quantize = num_data//4
class my_dataset(DataUtil.Datas... |
#-*- coding: utf-8 -*-
import codecs
from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
import time as tm
from friends_parsing import *
from base_manager import *
from friends_analyzis import find_mutual_friends
def start_browser():
browse = webdriver.Firefox()
browse.get(... |
"""
Database backend that stores the telemetry in PostgreSQL.
The backend leverages JSONB to enable arbitrary queries on the telemetry.
The DATABASE_URL is in the format:
postgres://<user>:<password>@<db_host>:<db_port>/<db_name>
"""
from datetime import timedelta
from itertools import groupby
from operator imp... |
import torch
from torch import tensor, rand
import pyro
import torch.distributions.constraints as constraints
import pyro.distributions as dist
def guide_rnn(category=None, input=None, n_characters=None):
___shape = {}
___shape['n_characters'] = ()
___shape['input'] = n_characters
___shape['category'... |
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin
from django.db import models
from django.db.models import Q
from django.utils import timezone
from datetime import timedelta
from datetime import date
from django.conf import settings
import enum
class UserManager(BaseUserManag... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Copyright (C) 2017-2020 The Project X-Ray Authors.
#
# Use of this source code is governed by a ISC-style
# license that can be found in the LICENSE file or at
# https://opensource.org/licenses/ISC
#
# SPDX-License-Identifier: ISC
'''
This script allows to load a numb... |
import requests
import time
import datetime
import json
import threading
import os
import logging
import sys
REGIONS_FILE_PATH = "regions.cfg"
PIKUD_URL = "https://www.oref.org.il/WarningMessages/alert/alerts.json"
PIKUD_REFERER = "https://www.oref.org.il/"
USER_REGIONS = set()
CURRENT_ALERTS = set()
ALE... |
# -*- coding: utf-8 -*-
"""Utility helper functions."""
from __future__ import absolute_import
import re
from io import IOBase
from numbers import Number
from pprint import pformat
from ._compatibility.abc import ABC
from ._compatibility.collections.abc import ItemsView
from ._compatibility.collections.abc import Iter... |
# Copyright 2018-2019 The glTF-Blender-IO 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 ... |
#
# Copyright (C) 2014-2021 S[&]T, The Netherlands.
#
from __future__ import absolute_import, division, print_function
import datetime
from muninn._compat import long
from muninn._compat import string_types as basestring
import uuid
import muninn.geometry as geometry
def prefix_message_with_path(path, message):
... |
"""
Create an offline browseable version of a CLDF Wordlist.
"""
import shutil
import pathlib
import itertools
import mimetypes
import collections
from tqdm import tqdm
from cldfbench.cli_util import add_dataset_spec, get_dataset
import cldfofflinebrowser
from cldfofflinebrowser import osmtiles
from cldfofflinebrowse... |
"""
Works with a directory of anndata objects which are the result of anndataize_ebi.py
To run change the DATADIR and FULLPATHDB global run and run the script from the repos venv.
python ebi_anndata_in.py
"""
import os
from sqlalchemy.orm import sessionmaker
from sqlalchemy import create_engine, and_
from sqlalche... |
import weakref
import numpy as np
import pytest
from conftest import skipif_yask
from devito import (Grid, Function, TimeFunction, SparseTimeFunction, Constant,
Operator, Eq, clear_cache)
from devito.types import _SymbolCache
@skipif_yask
@pytest.mark.parametrize('FunctionType', [Function, TimeF... |
import sys
import wget
import time
import pytz
import socket
import logging
import pathlib
import colorama
import datetime
import db
import utils
import models
import configs
from urllib.request import urlopen
from sqlalchemy.orm import Session
from sqlalchemy.exc import NoResultFound
CONNECTIVITY_CHECK_URL = 'https... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date : 2018-05-31 21:38:26
# @Author : <NAME> (<EMAIL>)
# @Link : http://iridescent.ink
# @Version : $1.1$
r"""
Functions for pre-processing images.
Functions used by improc functions:
.. autosummary::
:nosignatures:
scalearr
imgdtype
normaliz... |
# -*- coding: utf-8 -*-
"""
created by huash at 2015-04-08 19:19
"""
__author__ = 'huash'
import sys
import os
from functools import lru_cache
class Reader:
def __init__(self, path=None):
self.path = path
self.index = -1
self.data = []
def next_int(self):
self.index += 1
... |
"""
Contours analysis based mainly on moments
"""
# Import required packages:
import numpy as np
import cv2
from matplotlib import pyplot as plt
# the aspect ratio is defined as: width/height
def aspect_ratio(contour):
"""Returns the aspect ratio of the contour based on the dimensions of the bounding rect"""
... |
from typing import Any, Dict, List, Optional
class Model(object):
pass
class User(Model):
@classmethod
def from_json(cls, json: Dict[str, Any]) -> Optional['User']:
if json:
return cls(
json.get('name') or '', json['displayName'], json.get('emailAddress')
... |
# !/usr/bin/env python3
""" Factorio mod deployement script
Just move you code in a separate Directory like .../Deploy/ModName
This will be your root/Workspace which is preset to "."
The script will create a tempDir in which it copies all files and folders
and then creates a zip file which is moved to ./_release... |
"""Everything connected to setup of the app."""
__author__ = "opliko"
__license__ = "MIT"
__version__ = "0.8.b0"
__status__ = "Prototype"
import asyncio
import base64
import os
from hashlib import sha256
from typing import Any, Dict
import aiohttp_csrf
import sentry_sdk
from aiohttp import web
from aiohttp_jinja2 im... |
############################################
# Copyright (c) 2016 Microsoft Corporation
#
# Basic core and correction set enumeration.
#
# Author: <NAME> (nbjorner)
############################################
"""
Based on Z3's 'Basic core and correction set enumeration' implementation of Marco,
by <NAME> (nbjorner)
... |
import pygame, random
import pygameMenu
import sys
from patterns import blinker
# Define some colors and other constants
BLUE = (66, 87, 245)
WHITE = (255, 255, 255)
PINK = (242, 172, 241)
GRAY = (228, 230, 235)
DGRAY = (192, 192, 192)
WIN_SIZE = 500
CELL_SIZE = 20
# This sets the margin between each cell
MARGIN =... |
#
# SPDX-FileCopyrightText: Copyright (c) 1993-2022 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
#
# 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... |
import vapoursynth as vs
from acsuite.types import Trim
from lvsfunc.misc import replace_ranges
from lvsfunc.types import Range
from vsutil import depth
import glob
import os
from abc import ABC, abstractmethod
from typing import Any, Dict, List, NamedTuple, Optional, Tuple, Union
from .audio import AudioStream, C... |
#!/usr/bin/env python3
import os
import sys
import json
import zipfile
import datetime
import shutil
from wearebeautiful import model_params as param
MAX_SCREENSHOT_SIZE = 256000 # 256Kb is enough!
bundles_json_file = "bundles.json"
def bundle_setup(bundle_dir_arg):
''' Make the bundle dir, in case it doesn't e... |
# -*- coding: utf-8 -*-
#
# inventory/projects/api/serializers.py
#
"""
Project API Serializers
"""
__docformat__ = "restructuredtext en"
import logging
from django.contrib.auth import get_user_model
from django.utils.translation import gettext_lazy as _
from rest_framework import serializers
from inventory.common.... |
from __future__ import print_function, absolute_import, division
import pytest
import numpy as np
from numpy.testing import assert_allclose
import os
from astropy import units as u
from ..io.casa_masks import make_casa_mask
from ..io.casa_image import wcs_casa2astropy
from .. import SpectralCube, BooleanArrayMask, V... |
#!/usr/bin/env python3
# To get a logger for the script
import logging
import re
import shlex
import subprocess
import time
from pyats import aetest
from pyats.log.utils import banner
from typing import List
# Genie Imports
from genie.conf import Genie
# To handle errors with connections to devices
from unicon.co... |
import os
import time
import re
from inspect import signature
import boto3
from retrying import retry
from fabric2 import Connection
from botocore.config import Config
from botocore.exceptions import ClientError
from invoke import run
from invoke.context import Context
from . import DEFAULT_REGION, IAM_INSTANCE_PROF... |
#!/usr/bin/env python3
import numpy as np
import json
import os.path
STARTER_FILE = "../test-sets/diff_starter.json"
ESTIMATE_FILE_PAT = "../test-sets/diff_estimates_with_tow_{d}_128_9012.txt"
INFLATION_RATIO = 1.38 # for 128
UNION_SIZE = 100000
N_TEST = 1000
AVG = 5
FURTHER_DECOMP = 3
def diff_start_gen():
if os... |
import os
import discord
from cogs.utils import checks
from discord.ext import commands
from cogs.utils.dataIO import dataIO
from __main__ import settings
from cogs.utils.chat_formatting import pagify
class WhiteList:
'''Allow only whitelisted words in a channel'''
def __init__(self, bot):
self.bot =... |
#!/usr/bin/env python
"""
Utility functions
<NAME> - <EMAIL>
University of Victoria
"""
import os
import numpy as np
from scipy.signal import ellip, sosfilt
import essentia.standard as es
def get_audio_files(location, sort=True):
"""
Search the location provided for audio files
:param location: (str) ... |
#!/usr/bin/env python
""" Notification service which informs admins about any issue in agents.
Copyright 2017 California Institute of Technology
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... |
from os.path import dirname, join
import wisdomhord
import datetime as dt
import datarum
from math import floor
from .utils import format_timedelta
class FaereldBisen(wisdomhord.Bisen):
__invoker__ = "Færeld"
__description__ = "Productive task time tracking data produced by Færeld"
area = wisdomhord.Swe... |
from toolbox.parameters import *
from toolbox.paths import *
from argparse import ArgumentParser
def standard_parser():
""" Create an argument parser, add the parsing arguments relative to the options and return it. """
ap = ArgumentParser()
ap.add_argument("--random_seed",
type=int... |
from hyperopt.base import STATUS_STRINGS
from hyperopt.base import STATUS_NEW
from hyperopt.base import STATUS_RUNNING
from hyperopt.base import STATUS_SUSPENDED
from hyperopt.base import STATUS_OK
from hyperopt.base import STATUS_FAIL
from hyperopt.base import JOB_STATES
from hyperopt.base import JOB_STATE_NEW
from h... |
import numpy as np
from ._jit import jit
@jit
def _kepler_equation(E, M, ecc):
return E - ecc * np.sin(E) - M
@jit
def _kepler_equation_prime(E, M, ecc):
return 1 - ecc * np.cos(E)
@jit
def _kepler_equation_hyper(F, M, ecc):
return -F + ecc * np.sinh(F) - M
@jit
def _kepler_equation_prime_hyper(F, ... |
# -*- coding: utf-8 -*-
"""NOISE ROUTINES.
This module contains methods for adding and removing noise from data.
:Author: <NAME> <<EMAIL>>
"""
from builtins import zip
import numpy as np
from modopt.base.backend import get_array_module
def add_noise(input_data, sigma=1.0, noise_type='gauss'):
"""Add noise ... |
import numpy as np
import scipy.signal
import functools
@functools.lru_cache()
def gen_thirdoct_filter(fs, fft_size, cf0):
"""
To generate 1/3 octave filter, where octave frequency defined here is based 2.
params:
fs: samplerate of signal.
fft_size: fft size.
num_bands: number of ... |
"""igvm - Host Model
Copyright (c) 2018 InnoGames GmbH
"""
from io import BytesIO
from datetime import datetime
import fabric.api
import fabric.state
from fabric.contrib import files
from uuid import uuid4
from paramiko import transport
from igvm.exceptions import RemoteCommandError, InvalidStateError
from igvm.set... |
from warnings import warn
import numpy as np
__all__ = [
'all_bounds',
'error_bounds',
'wasserstein_bounds',
'divergence_bound'
]
def all_bounds(log_weights, samples=None, moment_bound_fn=None,
q_var=None, p_var=None, log_norm_bound=None):
"""Compute all error and distance bounds.... |
import abc
import numpy as np
import sqlite3
import math
from astropy.table import Table
import logging
import os.path
import astropy.units as u
from astropy.coordinates import SkyCoord
from astroquery.gaia import Gaia
__author__ = '<EMAIL>'
log = logging.getLogger(__name__)
class ReferenceCatalogProvider(metaclass... |
from __future__ import annotations
from collections import defaultdict
from dataclasses import dataclass, field
from datetime import datetime
from typing import DefaultDict, Dict, List, Optional
from discord import Guild, Role
from commanderbot.ext.roles.roles_store import (
RoleIDNotRegistered,
RoleNotRegis... |
import json
import logging
import os
import fileinput
import re
from .data_manipulation import DataManipulation
# Logger
logging.basicConfig(level=os.environ.get("LOGLEVEL", "INFO"))
LOGGER = logging.getLogger(__name__)
# Macros
PULSAR_SOURCE_CONNECTION_ID_PLAYGROUND = f"29fb61f1-9342-48f5-9793-1afa008c377b"
PULSAR... |
import torch
import torch.nn as nn
import torch.nn.functional as F
class CompTransTTSLoss(nn.Module):
""" CompTransTTS Loss """
def __init__(self, preprocess_config, model_config, train_config):
super(CompTransTTSLoss, self).__init__()
self.pitch_feature_level = preprocess_config["p... |
import numpy as np
import tensorflow as tf
def get_angles(pos, i, embedding_size):
angle_rates = 1 / np.power(10000, (2 * (i // 2)) / np.float32(embedding_size))
return pos * angle_rates
def positional_encoding(max_len, embedding_size):
angle_rads = get_angles(np.arange(max_len)[:, np.newaxis],
... |
from django.shortcuts import render
from django.http import HttpResponse
from backendCode.geocoding import reverse_geocoding, geocoding_from_address
from backendCode.nearbyplaces import search_nearby_places
from home_page.models import BusInformation
from backendCode.findBusByDirection import find_distance
from decoupl... |
from decimal import Decimal
import logging
from django.conf import settings
from django.utils.dateparse import parse_date
from mtp_common.api import retrieve_all_pages_for_path
from . import disbursements_config as config, DISBURSEMENTS_LABEL
from .exceptions import EmptyFileError
from .utils import (
get_start_a... |
"""
Copyright 2021 <NAME>
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
distrib... |
# -*- coding: utf-8 -*-
import asyncio
from asyncio import Future # noqa: F401
from asyncio import StreamReader
from asyncio import StreamWriter
from asyncio import Task # noqa: F401
from typing import Any # noqa: F401
from typing import Callable
from typing import Optional
from typing import Set # noqa: F401
f... |
# Copyright 2021 Huawei Technologies Co., Ltd
#
# 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 boto3
import csv
import dateutil.relativedelta
import json
import logging
import os
import zlib
from dateutil import parser
from .shipper import LogzioShipper
# Set logger
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
class CSVLineGenerator(object):
def __init__(self, csv_like_obj_bo... |
# Copyright (c) 2019-2020 SAP SE or an SAP affiliate company. All rights reserved. This file is
# licensed under the Apache Software License, v. 2 except as noted otherwise in the LICENSE file
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the L... |
@namespace
class SpriteKind:
start = SpriteKind.create()
def on_overlap_tile(sprite, location):
music.ba_ding.play()
info.change_score_by(1)
tiles.set_tile_at(location, myTiles.transparency16)
scene.on_overlap_tile(SpriteKind.player, myTiles.tile8, on_overlap_tile)
def on_overlap_tile2(sprite, locatio... |
import tensorflow as tf
from tensorflow.contrib.rnn import RNNCell
import numpy as np
from utils import *
def orthogonal(shape):
flat_shape = (shape[0], np.prod(shape[1:]))
a = np.random.normal(0.0, 1.0, flat_shape)
u, _, v = np.linalg.svd(a, full_matrices=False)
q = u if u.shape == flat_shape else v
... |
from types import MethodType
from threading import Thread, Event, Condition
from avatar2 import TargetStates
from avatar2.archs import ARMV7M
from avatar2.protocols.coresight import CoreSightProtocol
from avatar2.protocols.armv7m_interrupt import ARMV7MInterruptProtocol
from avatar2.targets import OpenOCDTarget, QemuT... |
import json
import re
import requests
from lxml import html as etree
import pdfcutter
# Import relative Parent Directory for Helper Classes
import os, sys
sys.path.insert(0, os.path.abspath('..')) #Used when call is ` python3 file.py`
sys.path.insert(0, os.path.abspath('.')) #Used when call is ` python3 $COUNTY/file... |
import ast
import copy
from ctypes import c_int8, c_int16, c_int32, c_int64
from ctypes import c_uint8, c_uint16, c_uint32, c_uint64
from dataclasses import dataclass
from py2many.analysis import get_id
@dataclass
class InferMeta:
has_fixed_width_ints: bool
def infer_types(node) -> InferMeta:
visitor = In... |
from django.contrib.auth.models import User
from django.db import models
from django.utils.html import *
# Create your models here.
#===================================================================================
# Location_tbl
#===================================================================================
... |
def isSubinterval(aStart, aEnd, bStart, bEnd, tolerance=0):
return aStart + tolerance >= bStart and aEnd - tolerance <= bEnd
def intersects(aStart, aEnd, bStart, bEnd):
return not (aEnd < bStart or aStart > bEnd)
class Rectangle:
def __init__(self, l, t, r, b):
self.left = l
self.top = t... |
import os
import sys
import labelme
import imgviz
import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf
AUTOTUNE = tf.data.experimental.AUTOTUNE
current_path = os.getcwd()
sys.path.append(current_path) # /plant-record/ ディレクトリをパスに追加
from segmentation.models.unet import unet
MIN_SIZE = 384
def s... |
# 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 to in writing, ... |
#-*- coding:utf-8 -*-
# https://en.wikipedia.org/wiki/Quadric
from __future__ import print_function, division
import numpy as N
from scipy.linalg import lu
from scipy.optimize import fsolve
import traceback
from numpy.linalg import norm
import pytest
from attitude.geom.util import dot, vector, augment, column, angl... |
# https://pytorch.org/tutorials/intermediate/char_rnn_classification_tutorial.html
# https://github.com/spro/practical-pytorch/tree/master/char-rnn-classification
"""
输入:名字 名字所在的国家
目标:名字 和 国家 的 信息量尽可能小
损失: 预测的国家和实际国家的差别
是 char-level 的吗:是的 不是用的词向量 只有57个字母的 one-hot编码
网络架构:hidden 层 在每次 train 时都重置,因为只... |
"""
Copyright (c) 2022-2022 Blue Brain Project/EPFL
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... |
from django.shortcuts import render
from django.http import HttpResponse, JsonResponse
from django.views import generic
from django.views.decorators.csrf import csrf_exempt
from .models import NormEntry, MissingEntry
from .modules.pylink import getNames, getCand, get_persons, get_places, get_organizations, change_XML, ... |
# -*- coding: utf-8 -*-
import tensorflow as tf
from .misc import (is_integer,
is_dynamic_tensor_like,
convert_to_tensor_if_dynamic)
__all__ = [
'get_dimension_size',
'get_dynamic_tensor_shape',
'is_deterministic_shape',
'explicit_broadcast',
'maybe_explicit_b... |
import sys
sys.path.append("..")
import json
from set_up import Setup
from scipy.stats import t
import h5py
from scipy.special import logit
import pandas as pd
from scipy.special import expit
import pymc3 as pm
import numpy as np
true_scores = np.load('../../processed_data/AmpC_short.npy')
setup = Setup('morgan', '... |
#!/usr/bin/env python3
import sys
import math
import pprint
import os
import re
import doctest
import itertools
import types
import logging
from collections import deque
from collections import defaultdict
#import networkx as nx
from copy import deepcopy
try:
import matplotlib.pyplot as plt
except ImportError:
p... |
"""See Jupyter notebooks on how to use these module to assess data quality of .csv data.
Note that python-3.6+ permits '_' as floating point separator, thus this module will treat '_'-separated float string
as valid floating points.
"""
import json
import pandas as pd
import re
ALPHANUMERIC_REGEXP = re.compile(r'[0-... |
from django.shortcuts import render
from .models import WalletAccount, WalletCredit, WalletDeposit, WalletIncome, WalletExpense, WalletCar, WalletHouse
def wallet_generator_year_month(request, year, month):
year_prev = int(year) - 1 if int(month) == 1 else year
month_prev = int(month) - 1 if int(month) > 1 e... |
from os import listdir
from os.path import join
import cv2
import numpy as np
from sklearn.model_selection import train_test_split
from keras.utils import to_categorical
from keras.models import Sequential
from keras.layers import Dense, Dropout, BatchNormalization
from keras.callbacks import EarlyStopping
from keras... |
#!/usr/bin/env python3
# pip install --user pyverilog
import pyverilog
from pyverilog.vparser.parser import parse
import sys
import os
def port_child(port):
children = port.children()
# when register may have more than one
# but eh this seems to work
#assert len(children) == 1
return children[0]
... |
from discord.ext.commands import command, Cog
from discord import Embed, Member, VoiceChannel, Status, Activity, ActivityType, ChannelType
from __database__ import connect, config
from utils.embedUtils import newEmbed, successEmbed, errorEmbed, field, redButton, grayButton, blueButton, greenButton, urlButton
from disco... |
# -*- coding: utf-8 -*-
# Copyright (C) 2010, 2011, 2012, 2013 <NAME> <<EMAIL>>
# This library is free software; you can redistribute it and/or modify it
# under the terms of the GNU Lesser General Public License as published by the
# Free Software Foundation; either version 2.1 of the License, or (at your
# option) a... |
#!/usr/bin/env python
import numpy as np
import h5py
import argparse
def get_track_feature_matrix(track_features_filename, region_features, normalize=False):
num_features = sum([i for n,i in region_features])
track_feature_matrix = np.array([]).reshape(0, num_features)
with h5py.File(track_features_filenam... |
from prompt_toolkit.completion import Completion, Completer
import prompt_toolkit as pt
from prompt_toolkit.validation import Validator, ValidationError
from prompt_toolkit.auto_suggest import AutoSuggest, Suggestion
from .utils import auto_cast
import inspect
style = pt.styles.Style.from_dict({
# User input (defa... |
""" Image Resizer
This module provides functionality to resize images using `pillow`
"""
from PIL import Image
import os
import re
from ConfigParser import ConfigParser
common_img_types = {
# very common
'ico' : 'image/vnd.microsoft.icon',
'jpg' : 'image/jpeg',
'jpeg' : 'image/jpeg',
'gif' : ... |
#!/usr/bin/env python3
'''
sycommands.py
Main Sublime Text Commands. Utilities for controlling or querying ycmd.
'''
import logging
import logging.config
from .lib.subl.view import (
get_path_for_view,
get_file_types,
)
from .lib.util.format import (
json_pretty_print,
json_flat_iterator,
)
from .pl... |
from trakt.core.configuration import DEFAULT_HTTP_RETRY, DEFAULT_HTTP_MAX_RETRIES, DEFAULT_HTTP_TIMEOUT, \
DEFAULT_HTTP_RETRY_SLEEP
from trakt.core.context_stack import ContextStack
from trakt.core.helpers import synchronized
from trakt.core.request import TraktRequest
from requests.adapters import HTTPAdapter, DE... |
import threading
from collections import OrderedDict
import cv2
import dataset
from gui.window import LayerChoices
from nets.keras_models import *
from utils.datautils import MnistImageInput
from utils.experimentutils import RealtimeModel
from utils.miscutils import get_current_time_in_string
def to_dict(layers):
... |
import os.path as op
import shutil
import unittest
import tempfile
import progressbar
import nose
from lib.utils import util
class Test_CopyWithBackup(unittest.TestCase):
def setUp(self):
self.work_dir = tempfile.mkdtemp()
with open(op.join(self.work_dir, 'from.txt'), 'w') as f:
f.wri... |
import os
import time
import numpy as np
from dataset_loaders.parallel_loader import ThreadedDataset
from dataset_loaders.utils_parallel_loader import natural_keys
floatX = 'float32'
class DavisDataset(ThreadedDataset):
name = 'davis'
non_void_nclasses = 2
_void_labels = []
# NOTE: we only load th... |
#####################
# TEMA ESTRUCTURADO #
#####################
Clock.bpm=90
Scale.default='majorPentatonic'
Root.default=0
## CODIGO ##
##### Abajo arriba
def abajo():
d_all.lpf=500
d_all.solo()
def arriba():
d_all.lpf=0
d_all.solo(0)
def abajoarriba(intervalo):
abajo()
Clock.future(interva... |
"""
Created on Wed February 8 2021
@author: <NAME>
GitHub username: esgomezm
"""
import tensorflow as tf
from tensorflow.keras.models import Model
from tensorflow.keras.layers import Input, Conv2D, UpSampling2D, Concatenate, SeparableConv2D, ConvLSTM2D, \
TimeDistributed, Activation
from tensorflow.keras.losses im... |
#<NAME>
#face detection and recognition
import dlib
import numpy as np
from cv2 import cv2
import pandas as pd
import os
import time
from PIL import Image, ImageDraw, ImageFont
from subprocess import call
import second1
# Use frontal face detector of Dlib
detector = dlib.get_frontal_face_detector()
# Get face landmark... |
import glob
import os
import time
from datetime import datetime, timedelta
from pathlib import Path
import pytest
from click.testing import CliRunner
from feathr import (FeatureAnchor, FeatureQuery, ObservationSettings, TypedKey,
ValueType)
from feathr._feature_registry import _FeatureRegistry
from... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
"""
首页面板
"""
from __future__ import print_function
from __future__ import absolute_import
from datetime import datetime, timedelta
from copy import deepcopy
from time import mktime
from pmon.mongo import mongo
from pmon.jobs.count import count_summary, risk_port_list, ris... |
#!/usr/bin/env python
# Copyright 2019 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Extracts an LLD partition from an ELF file."""
import argparse
import hashlib
import math
import os
import struct
import subprocess
... |
import os
import random
from ..config import CHOICE_RES
from .common import wopen
from .file_content import *
def get_random_string(length):
chars = 'abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*(-_=+)'
return ''.join(random.choice(chars) for i in range(length))
def create_application(pro_name, app_conf):
... |
#! /usr/bin/python3
import struct
import datetime
import ht_device
import json
def parse_parameters_pkt_1(data):
fmt = '>BBB10s38s2sHB3sH'
fmt_names = ['cmd_id',
'packet_id',
'address',
'serial',
'test_name',
'unknown_1',
... |
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
import datetime
import pandas as pd
from dateutil.relativedelta import relativedelta
from collections import Iterable
ALLOWED_TIME_COLUMN_TYPES = [
pd.Timestamp,
pd.DatetimeIndex,
datetime.datetime,
datetime.date,
]
def is_date... |
import torch
from torch.utils.data import Dataset
from torchvision import models, transforms
import os
import random
import pandas as pd
import numpy as np
from collections import namedtuple
from skimage import io, transform
from PIL import Image
import h5py
import config
from utils import name_list
class SatUAVDatas... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.