content
stringlengths
0
894k
type
stringclasses
2 values
import numpy as np import pandas as pd from sklearn.ensemble import ExtraTreesRegressor, GradientBoostingRegressor from sklearn.model_selection import train_test_split from sklearn.pipeline import make_pipeline, make_union from sklearn.preprocessing import MaxAbsScaler from tpot.builtins import StackingEstimator # NOT...
python
# 454. 4Sum II import collections class Solution: def fourSumCount(self, A, B, C, D): """ :type A: List[int] :type B: List[int] :type C: List[int] :type D: List[int] :rtype: int """ ab = {} for a in A: for b in B: ab...
python
import soundfile as sf import numpy as np import librosa from scipy import signal import cPickle import src.config as cfg def to_mono(wav): if wav.ndim == 1: return wav elif wav.ndim == 2: return np.mean(wav, axis=-1) def calculate_logmel(rd_fd): wav, fs = sf.read(rd_fd) wav = to_mono...
python
from datetime import datetime as dt from ..ff.window import Window class BrowserSession(object): def __init__(self, ss_json): self._windows = WindowSet(ss_json["windows"]) self._start_time = dt.fromtimestamp(ss_json["session"]["startTime"] / 1000) self._selected_window = ss_json["selectedW...
python
import numpy as np; import xlrd; import xlwt; sheet = xlrd.open_workbook('data1.xls'); workbook = xlwt.Workbook(encoding = 'ascii'); worksheet = workbook.add_sheet('school') data = sheet.sheets()[0]; row = data.nrows; col = data.ncols; for i in range(0,row): for j in range(0,col): worksheet.write(i, j...
python
import json import sys import os import typer from typing import List import time from .logger import get_logger from .config.imports import check_imports os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' logger = get_logger() cli = typer.Typer() @cli.command('setup') def setup_auto(): chk_libs = ['tensorflow', 'torch',...
python
import re import matplotlib.pyplot as plt import numpy as np import sklearn from sklearn import svm from sklearn import linear_model, tree from sklearn.ensemble import RandomForestClassifier from sklearn import neural_network import copy path = r"D:\THU\curriculum\Software Engineering\Course_Project\data_1109_0427_RGB...
python
import csv import re from os import path import numpy as np FIELDNAMES = 'timeStamp', 'response_time', 'request_name', "status_code", "responseMessage", "threadName", "dataType",\ "success", "failureMessage", "bytes", "sentBytes", "grpThreads", "allThreads", "URL", "Latency",\ "IdleTime", "C...
python
from setuptools import setup, find_packages setup( name='taxies', version='0.1.dev', packages=find_packages(), include_package_data=True, install_requires=[ 'Click', ], entry_points=''' [console_scripts] taxies=taxies.scripts.taxies:cli ''', )
python
"""App. """ import logging import sys from django.apps import AppConfig from configs.part_detection import DF_PD_VIDEO_SOURCE_IS_OPENCV logger = logging.getLogger(__name__) class AzurePartDetectionConfig(AppConfig): """App Config.""" name = "vision_on_edge.azure_part_detections" def ready(self): ...
python
""" Query suggestion hierarchical encoder-decoder code. The code is inspired from nmt encdec code in groundhog but we do not rely on groundhog infrastructure. """ __docformat__ = 'restructedtext en' __authors__ = ("Alessandro Sordoni") __contact__ = "Alessandro Sordoni <sordonia@iro.umontreal>" import theano import th...
python
# Copyright 2013-2015 ARM Limited # # 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 w...
python
# 源程序文件名 SOURCE_FILE = "{filename}.hs" # 输出程序文件名 OUTPUT_FILE = "{filename}.out" # 编译命令行 COMPILE = "ghc {source} -o {output} {extra}" # 运行命令行 RUN = 'sh -c "./{program} {redirect}"' # 显示名 DISPLAY = "Haskell" # 版本 VERSION = "GHC 8.0.2" # Ace.js模式 ACE_MODE = "haskell"
python
# Generated by Django 2.1.7 on 2019-10-03 20:35 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('core', '0017_auto_20190921_1849'), ] operations = [ migrations.RemoveField( model_name='estrutu...
python
import torch from torch.optim import Adam,SGD from opt import opt import math import random import collections from torch.utils.data import sampler import torch.nn as nn def extract_feature( model, loader): features = torch.FloatTensor() for (inputs, labels) in loader: ff = torch.FloatTensor(inputs....
python
# WRITE YOUR SOLUTION HERE: def add_numbers_to_list(numbers: list): if len(numbers) % 5 != 0: numbers.append(numbers[-1] +1 ) add_numbers_to_list(numbers) if __name__=="__main__": numbers = [1,3,4,5,10,11] add_numbers_to_list(numbers) print(numbers)
python
#!/usr/bin/env python import os, subprocess from autopkglib import Processor, ProcessorError __all__ = ["IzPackExecutor"] class IzPackExecutor(Processor): """Runs IzPack installer with all install options checked.""" input_variables = { "app_root": { "required": True, "des...
python
""" @author Yuto Watanabe @version 1.0.0 Copyright (c) 2020 Yuto Watanabe """
python
import cProfile import argparse from app import Application def parse_args(): parser = argparse.ArgumentParser( description="A keyboard-oriented image viewer") parser.add_argument("path", type=str, nargs='?', default="", help="the file or directory to open") parser.add_argum...
python
__author__ = 'Mario' import wx import wx.xrc from Engine_Asian import AsianOption ########################################################################### ## Class MainPanel ########################################################################### class PanelAsian ( wx.Panel ): def __init__( self, parent )...
python
import tqdm import numpy as np import torch import torch.nn as nn from torch.autograd import Variable import torch.nn.functional as F from models.generator import ResNetGenerator from train_script.utils import * from utils.val import validation from utils.quantize_model import * def adjust_learning_rate...
python
from flask import Flask from flask.ext.sqlalchemy import SQLAlchemy app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://root@localhost/flask_db' db = SQLAlchemy(app) class UserDB(db.Model): id = db.Column(db.Integer,primary_key=True) username = db.Column(db.String(32),unique=True) passw...
python
from .DtnAbstractParser import DtnAbstractParser from enum import Enum from pydantic import PositiveInt, PositiveFloat import sys from typing import List, Optional, Set, Union class RouterMode(str, Enum): FAST = 'fast' SLOW = 'slow' class RouterAlgorithm(str, Enum): CGR = 'cgr' BFS = 'bfs' class DtnL...
python
import numpy as np import tensorflow as tf class InferenceGraph: def __init__(self): pass def run_inference_for_single_input_frame(self, model, input_frame,log, log_path): """ Method Name: run_inference_for_single_input_frame Description: This function make prediction ...
python
import selenium import glob from numpy import arange from random import sample from sys import exit from time import sleep from progress.spinner import Spinner from progress.bar import ChargingBar from threading import Thread from selenium import webdriver from selenium.webdriver.firefox.options import Option...
python
from .page_article import *
python
SECRET_KEY = "it's-a-secret-to-everyone" INSTALLED_APPS = [ 'channels', 'channels_irc', ] DATABASES = { "default": { "ENGINE": "django.db.backends.sqlite3", } } CHANNEL_LAYERS = { "default": { "BACKEND": "channels.layers.InMemoryChannelLayer", }, }
python
# -*- coding: utf-8 -*- import io import os import time import fcntl import socket import struct import picamera import threading from Led import * from Servo import * from Thread import * from Buzzer import * from Control import * from ADS7830 import * from Ultrasonic import * from Command import COMMAND as cmd class...
python
import os data_path_root = "E:\Projects\projectHO\data" stock_list_path = os.path.join(data_path_root, "stock_list.csv") split_span = 365 * 5 # split dates to download pre-historical data retry_count = 5 # downloader max retry count log_path = "E:\Projects\projectHO\log"
python
# -*- coding: utf-8 -*- # Copyright (c) 2014 Baidu.com, Inc. 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 requi...
python
#!/usr/bin/python3 -OO # Copyright 2007-2022 The SABnzbd-Team <team@sabnzbd.org> # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any late...
python
''' generic functions ''' def myfunc( x:int ): print( x * 100 ) def myfunc( x:string ): print( x + 'world' ) def main(): myfunc( 10 ) myfunc( 'hello' )
python
# Third-Party Imports from django.core.exceptions import ValidationError from django.db.models import ProtectedError # App Imports from core.tests import CoreBaseTestCase from ..models import AssetCategory class AssetCategoryModelTest(CoreBaseTestCase): """ Tests for the Asset Category Model """ def test_c...
python
from unittest.mock import Mock, patch, call import pytest from sqlalchemy import column from sqlalchemy import text from sqlalchemy import func from sqlalchemy import not_ from sqlalchemy_filters import operators from sqlalchemy_filters.exceptions import InvalidParamError from tests.utils import compares_expressions ...
python
import auditor from event_manager.events import tensorboard auditor.subscribe(tensorboard.TensorboardStartedEvent) auditor.subscribe(tensorboard.TensorboardStartedTriggeredEvent) auditor.subscribe(tensorboard.TensorboardSoppedEvent) auditor.subscribe(tensorboard.TensorboardSoppedTriggeredEvent) auditor.subscribe(tens...
python
# -*- coding: utf-8 -*- """ Created on Mon Feb 13 09:50:51 2017 @author: mkonrad """ import math import pytest from hypothesis import given import hypothesis.strategies as st import numpy as np from pdftabextract.geom import (pt, ptdist, vecangle, vecrotate, overlap, lineintersect, ...
python
""" Open stuff in Chromium """ from albertv0 import Item, ProcAction, ClipAction import json from shutil import which __iid__ = "PythonInterface/v0.1" __prettyname__ = "Web Browser" __version__ = "1.0" __trigger__ = "web " __author__ = "Michael Farber Brodsky" def handleQuery(query): if query.isTriggered: ...
python
from urllib.request import urlopen SIMPLE_URL = "http://www.dinopass.com/password/simple" COMPLEX_URL = "http://www.dinopass.com/password/strong" def GetSimplePassword(): response = urlopen(SIMPLE_URL) bytes = response.readline() return bytes.decode() def GetComplexPassword(): response = urlopen(COMPLEX_URL) b...
python
# Copyright (C) 2020 FireEye, Inc. All Rights Reserved. import io import os from urllib.parse import urlparse from io import BytesIO from speakeasy.errors import NetworkEmuError def is_empty(bio): if len(bio.getbuffer()) == bio.tell(): return True return False def normalize_response_path(path): ...
python
from os.path import join, dirname, realpath from re import match def parse_input(): planties = set() with open(join(dirname(realpath(__file__)), "input.txt")) as f: # Parse initial config m = match("initial state: (?P<init>[#.]+)", f.readline()) for i, c in enumerate(m.group("init")): ...
python
#!/usr/bin/env python """ Generate an input MAF file for MutSigCV by converting SNV/INDEL calls by the Genomon2 pipeline. The input is a multi-sample variant call in post_analysis/ directory. Usage: python genomon2maf.py merge_mutation_filt.txt """ __author__ = "Masashi Fujita <mssfjt@gmail.com>" __version__ = "0.0.1" ...
python
import asyncio from pypuss.app import Master async def main(): my_app = Master() await my_app.run() if __name__ == '__main__': print("[info]", "started running") loop = asyncio.get_event_loop() try: loop.run_until_complete(main()) except BaseException: print("[info]", "shuttin...
python
from rest_framework import generics, status, permissions, mixins from .models import Post, Vote from .serializers import PostSerializer, VoteSerializer from .permissions import IsPostAuthorOrReadOnly from helpers.response import Response class PostView(generics.ListCreateAPIView): serializer_class = PostSeriali...
python
import numpy as np import xarray as xr from constants import R_earth from xr_DataArrays import dll_from_arb_da def xr_int_global(da, AREA, DZ): """ global volume integral *[m^3] """ (z, lat, lon) = dll_from_arb_da(da) return (da*AREA*DZ).sum(dim=[z, lat, lon]) # 0D def xr_int_global_level(da, AREA, D...
python
class Packet_Ops(): def __init__( self ): self.frame_id = 1 self.rx_packet_table = { 0x88: self.parse_command_resp, 0x8a: self.parse_modem_status, 0x8b: self.parse_tx_status, 0x8d: self.parse_route_information, 0x8e: self.aggreate_address_update, 0x90: self.parse_rx_indicator, 0x9...
python
from importlib import import_module import six from six.moves import reload_module from typing import Optional, Union # noqa from configloader import ConfigLoader from wrapt import ObjectProxy """ Usage: from flexisettings.conf import settings There are two important env vars: `<inital_namespace>_CONFIG_...
python
""" Contains a class that converts the pre-processed binary file into a numpy array. The logic behind each conversion step is thoroughly document through comments in the code. """ import pickle import os import struct import logging import hashlib import numpy as np from tqdm import tqdm import matplotlib class Prepr...
python
# ConnexionApiGenerator.py - Creates an object implementing a Connexion API import os from jinja2 import Environment, Template, FileSystemLoader from smoacks.sconfig import sconfig class ConnexionApiGenerator: def __init__(self, app_object): self._app_object = app_object self.name = self._app_objec...
python
"""PyTest fixtures and helper functions, etc.""" import pprint import uuid from configparser import ConfigParser from configparser import ExtendedInterpolation from inspect import getframeinfo from pathlib import Path import pytest # ========================================================= # H ...
python
import copy import itertools import re import threading import html5lib import requests import urllib.parse from bs4 import BeautifulSoup from typing import List try: import basesite except (ModuleNotFoundError, ImportError) as e: from . import basesite class DaocaorenshuwuSite(basesite.BaseSite): def _...
python
from flask import render_template, flash, redirect, url_for, session from flask_login import login_user, current_user, login_required from app import app, db, lm from app.models.tables import User, Challenges from app.models.forms import FlagForm import datetime from notifications import * @lm.user_loader def load_us...
python
#!/usr/bin/env python3 # -*- coding: utf-8 -*- __author__ = 'ipetrash' import re import requests from bs4 import BeautifulSoup def get_last_series(url: str) -> int: rs = requests.get(url) root = BeautifulSoup(rs.content, 'html.parser') fields_str = root.select_one('ul.flist').get_text(strip=True) ...
python
import os from pathlib import Path from shutil import rmtree from tests.lib.base import DeloggerTestBase from tests.lib.urlopen_mock import UrlopenMock class TestPresets(DeloggerTestBase): def teardown_method(self): log_dir = self.OUTPUT_DIRPATH if not Path(log_dir).is_dir(): return F...
python
"""Top-level package for the 'dltf' framework. Running ``import dltf`` will recursively import all important subpackages and modules. """ import logging import dogs_vs_cats.src.inception_resnet_v2 logger = logging.getLogger("dogs_vs_cats") __url__ = "https://github.com/ShiNik/DeepLearning_Tensorflow" __version__ =...
python
"""Class for symbolic expression object or program.""" import array import os import warnings from textwrap import indent import numpy as np from sympy.parsing.sympy_parser import parse_expr from sympy import pretty from dsr.functions import PlaceholderConstant from dsr.const import make_const_optimizer ...
python
import os.path import sys import warnings from setuptools import find_packages, setup if sys.version_info < (2, 7): raise NotImplementedError( """\n ############################################################## # globus-sdk does not support python versions older than 2.7 # ###############################...
python
import json from collections import defaultdict from decimal import Decimal import bleach import dateutil.parser import pytz from django.dispatch import receiver from django.urls import reverse from django.utils.formats import date_format from django.utils.html import escape from django.utils.safestring import mark_sa...
python
import mcradar as mcr import xarray as xr import numpy as np import pandas as pd import os from IPython.core.debugger import Tracer ; debug=Tracer() #insert this line somewhere to debug def getApectRatio(radii): # imput radii [mm] # auer et all 1970 (The Dimension of Ice Crystals in Natural Clouds) d...
python
import numpy as np """ v_l object. c*r^{n-2}*exp{-e*r^2} """ class rnExp: def __init__(self, n, e, c): self.n = np.asarray(n) self.e = np.asarray(e) self.c = np.asarray(c) def __call__(self, r): return np.sum( r[:, np.newaxis] ** self.n * self.c ...
python
#!/usr/bin/python3.8 import os import requests import argparse import queue import threading import logging DOWNLOAD_THREADS = 6 IO_THREADS = 2 download_queue = queue.Queue() write_queue = queue.Queue() files_lock = threading.Lock() def download_worker(download_queue, write_queue, url, chunk_size): finished ...
python
from spendfrom import determine_db_dir class Options(object): def __init__(self): self.fromaddresses = list() self.toaddress = None self.new = False self.datadir = determine_db_dir() self.conffile = "crown.conf" self.fee = "0.025" self.amount = None s...
python
# Need to import path to test/fixtures and test/scripts/ # Ex : export PYTHONPATH='$PATH:/root/test/fixtures/:/root/test/scripts/' # # To run tests, you can do 'python -m testtools.run tests'. To run specific tests, # You can do 'python -m testtools.run -l tests' # Set the env variable PARAMS_FILE to point to your ini ...
python
# -*- coding: utf-8 -*- """ @author: Jatin Goel """ import os from flask import Flask APP = Flask(__name__) APP.config['SQLALCHEMY_DATABASE_URI'] = ( 'sqlite:///' f'{os.path.join(os.getcwd(), "database.db")}' ).replace("\\", "/") APP.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False APP.config['SECRET_KEY...
python
import unittest from code.core.enumerations import * import json class TestEnumBase(unittest.TestCase): @classmethod def dummy(cls, One = 1, Two = 2, Three = 3, Four = 4): pass # class TestEnumBase class TestEnum(TestEnumBase): @enumeration class ParsingSample: One = 1 ...
python
import json def load_expressions(): """Returns the expressions_file loaded from JSON""" with open('../data/BotCycle/expressions.json') as expressions_file: return json.load(expressions_file) def load_intents(): """Returns a list of names of the intents""" with open('../data/BotCycle/entities...
python
import os import h5py import numpy as np def copy_file_struct(f, hmap, fo): """ Iteratively copy a HDF5 file structure to a new file Arguments: -f : File from which to copy [OPEN HDF5 file handle] -hmap : Current file object of interest to copy from -fo : File to copy structure to ...
python
""" The child process. """ import time from asyncio import get_event_loop from typing import Callable, Optional from prompt_toolkit.eventloop import call_soon_threadsafe from .backends import Backend from .key_mappings import prompt_toolkit_key_to_vt100_key from .screen import BetterScreen from .stream import BetterS...
python
# Generated by Django 3.2 on 2022-02-19 13:03 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('products', '0005_remove_pr...
python
# -*- coding: utf-8 -*- import scrapy class AdzanItem(scrapy.Item): c = scrapy.Field() # city d = scrapy.Field() # day s = scrapy.Field() # shubuh t = scrapy.Field() # terbit z = scrapy.Field() # zuhur a = scrapy.Field() # ashr m = scrapy.Field() # maghrib i = scrapy.Field() # isya
python
import os import sys from os import path from flask import Flask from flask.ext.login import LoginManager from flask_sqlalchemy import SQLAlchemy from flask_recaptcha import ReCaptcha app = Flask(__name__) sys.path.append(path.dirname(path.dirname(path.abspath(__file__)))) #config for Forms, Register and FCM tokens a...
python
""" Standalone program to copy a file to azure, and return the URL to access the file. The idea is that you can run from the command line and escape to shell because sometimes the write takes awhile. Then look in the log file to get the URL for sharing. To test: run copy_to_azure To copy a file: python copy_to_azure...
python
#!/usr/bin/env python # Copied from https://github.com/xantares/mingw-ldd/blob/master/mingw-ldd.py # Modified to point to right prefix location on Fedora. # WTFPL - Do What the Fuck You Want to Public License from __future__ import print_function import pefile import os import sys def get_dependency(filename): ...
python
import torch import torch.utils.data as tud import numpy as np from utils import create_space import os # from PIL import Image, ImageFile import torchvision.transforms.functional as TF from collections import defaultdict import rasterio from rasterio.windows import Window import pyproj # ImageFile.LOAD_TRUNCATED_IMAG...
python
from distutils.core import setup setup( name='page-objects', version='1.1.0', packages=['page_objects'], url='https://github.com/krizo/page-objects.git', license='MIT', author='Edward Easton', author_email='eeaston@gmail.com', description='Page Objects for Python', requires=['selenium',...
python
from enum import Enum from typing import Union class CONNECTION_STYLE(Enum): angle = 1 angle_3 = 2 arc = 3 arc_3 = 4 bar = 5 def get_name(self) -> str: return { 'angle': 'angle', 'angle_3': 'angle3', 'arc': 'arc', 'arc_3': 'arc3', ...
python
# Librerias Future from __future__ import unicode_literals # Librerias Django from django.contrib.auth.mixins import LoginRequiredMixin from django.shortcuts import render from django.views.generic import DetailView, ListView # Librerias de terceros from apps.website.submodels.post import PyPost def index(request):...
python
###################################################################################### ### This is a read-only file to allow participants to run their code locally. ### ### It will be over-writter during the evaluation, Please do not make any changes ### ### to this file. ...
python
print('Cliente da Vagalume API Iniciado: \n') nome_artista = input('Digite o nome de um Artista\n') import busca resultado = busca.artista(nome_artista) newinput = input('Digite:\n-pos: para saber a posição do artista no ranking\n-album: para saber o ultimo álbum do artista\n-frequencia: para saber as palavras mais...
python
import json import logging from homeassistant.components.http import HomeAssistantView from .util import DOMAIN, XIAOAI_API, matcher_query_state, find_entity from .xiaoai import (XiaoAIAudioItem, XiaoAIDirective, XiaoAIOpenResponse, XiaoAIResponse, XiaoAIStream, XiaoAIToSpeak, XiaoAITTSItem, ...
python
from apistar import Include, Route from settings.config import DEBUG from views.spider import callback from views.crate import crate_list, crate_detail routes = [ Route('/', 'GET', crate_list), Route('/crate/{crate_id}', 'GET', crate_detail), Route('/spider', 'POST', callback), ] if DEBUG: from apis...
python
#!/usr/bin/env python3 """Générateur de service AVAHI pour Freebox en mode bridge Lit les informations depuis http://mafreebox.freebox.fr/api_version Crée un fichier utilisable comme service avahi. Permet d’utiliser Freebox Compagnon avec une Freebox en mode Bridge : https://dev.freebox.fr/bugs/task/22301 """ i...
python
import matplotlib.pyplot as plt from matplotlib import ticker from matplotlib.colors import LogNorm import matplotlib import numpy as np get_ipython().run_line_magic('matplotlib', 'inline') def Plotting(ebs,aps,Na,stime,mus,Np,Ne,Nmu): t,ax = plt.subplots(nrows =2, ncols = 1, figsize=(7,5)) #extent...
python
import re import math import operator import collections import unittest __version__ = (0, 0, 11) _non_word_re = re.compile(r'[^\w, ]+') __all__ = ('FuzzySet',) class FuzzySet(object): def __init__(self, iterable=(), gram_size_lower=2, gram_size_upper=3): self.exact_set = {} self.match_dict = c...
python
import requests import autoscaler.conf.engine_config as eng import os def remove_old_create_new(f_name, header): if os.access(f_name, os.R_OK): os.remove(f_name) write_to_file(header, f_name) def write_to_file(stats, f_name): csv = open(f_name, "a") csv.write(stats) def get_dpid(ip): ...
python
from pathlib import Path from math import ceil from sys import maxsize from pprint import pprint def parse_reactions(raw_text): reactions = dict() r_inputs = reactions["inputs"] = list() r_outputs = reactions["outputs"] = list() for line in raw_text.split("\n"): if len(line) == 0: c...
python
from dependency_injector.wiring import inject, Provide from ...container import Container from ...service import Service @inject def test_function(service: Service = Provide[Container.service]): return service
python
from .models import Podcasts,Votes,Comments,Profile from django import forms class RateForm(forms.ModelForm): class Meta: model=Votes exclude=['user','podcast'] class PostForm(forms.ModelForm): class Meta: model=Podcasts exclude=['user','design','usability','content'] class Re...
python
"""Test suite for the pyproject_cookiecutter_test package."""
python
import tensorflow as tf from einops.layers import tensorflow as tfeinsum from tensorflow.keras import initializers, layers from .layers import DiagonalAffine, PatchEmbed, PerSampleDropPath def mlp_block(x, hidden_units, out_units, activation, dropout_rate, name=None): x = layers.Dense(units=hidden_units, name=na...
python
#!/usr/bin/python # import RPi.GPIO as GPIO import spidev, time, math, random, logging class Gibson_LED_Driver: ## name constants ## proglist = {'static':0, 'fadeupdown':1, 'flyingcolor':2, 'throb':3, 'randomstatic':4, 'spin':5} colorlist = {'single':0, 'alternating':1, 'wide-alternating':2, 'colorwheel':...
python
# Copyright (c) Meta Platforms, Inc. and affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. from __future__ import annotations import math from typing import Dict, Optional from tabulate import tabulate class StatsItem: de...
python
# encoding: utf-8 import copy import datetime from secrets import token_urlsafe from sqlalchemy import types, Column, Table, ForeignKey, orm from sqlalchemy.dialects.postgresql import JSONB from sqlalchemy.ext.mutable import MutableDict import ckan.plugins.toolkit as tk from ckan.model import meta, User, DomainObjec...
python
# Copyright (c) 2021, NVIDIA 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 i...
python
#!/usr/bin/env python import os import re import sys try: from setuptools import setup except ImportError: from distutils.core import setup def read(*names, **kwargs): with open(os.path.join(os.path.dirname(__file__), *names), 'r') as fp: return fp.read() def find_version(*file_paths): versi...
python
import bcrypt from app.database import BaseMixin, db from app.serializer import ma class User(db.Model, BaseMixin): __tablename__ = 'user_table' userID = db.Column(db.Integer, primary_key=True) username = db.Column(db.String, nullable=False) _password = db.Column(db.Binary(60)) email = db.Column...
python
import boto3 from .. import config # Module API def change_acl_on_s3(bucket, acl, path='', endpoint_url=None): def func(package): # Prepare client s3_url = endpoint_url or config.S3_ENDPOINT_URL s3_client = boto3.client('s3', endpoint_url=s3_url) # Change ACL # list_obj...
python
# Description: Count number of *.log files in current directory. # Source: placeHolder """ cmd.do('print("Count the number of log image files in current directory.");') cmd.do('print("Usage: cntlogs");') cmd.do('myPath = os.getcwd();') cmd.do('logCounter = len(glob.glob1(myPath,"*.log"));') cmd.do('print("Number of ...
python
""" A terminal based ray-casting engine. 'esc' to exit 't' to turn off textures 'wasdqe' or arrow-keys to move 'space' to jump Depending on your terminal font, Renderer.ascii_map may need to be adjusted. If you'd like to make an ascii map more suitable to your terminal's font, check my Snippets repository for a scrip...
python
#!/usr/bin/env python # -*- coding: utf-8 -*- """ @author: edwardahn Evaluate a policy and publish metrics. """ import argparse import cProfile import pstats import sys import joblib import matplotlib.pyplot as plt import numpy as np from rllab.sampler.utils import rollout def profile_code(profiler): """ ...
python
#!/usr/bin/env python3 # Copyright (c) Microsoft Corporation. # Licensed under the MIT license. import tensorflow as tf from tensorflow.contrib import antares if tf.version.VERSION.startswith('2.'): tf = tf.compat.v1 tf.disable_eager_execution() from _common import * x = create_variable([64, 224, 224, 3], dtyp...
python