content stringlengths 5 1.05M |
|---|
import numpy as np
import streamlit as st
import torch
import torchvision.transforms as T
import urllib
from PIL import Image
from torchvision.utils import make_grid, save_image
from model import RestorationModel
import albumentations as A
from albumentations.pytorch import ToTensorV2
CHECKPOINT = "https://github.com... |
# NHD_CalculateNLCDSummaries.py
#
# Description: Adds new fields to the catchment NLCD tables (cumulative and
# incremental) and computes the total area of Anderson Level I (not II)
# land covers (.e.g classes 21,22,23, and 24 are combbined into "NLCD2".
#
# Spring 2015
# John.Fay@Duke.edu
import sys, os, arcpy
#T... |
name = u'wechatbotexec'
_all = [u'command'] |
from tests.integration.build_invoke.build_invoke_base import BuildInvokeBase
"""
sam build does not support to build dotnetcore 2.1 templates using container,
here we put them in a separate file and use a dedicate codebuild project with .net 2.1 runtime to build them.
For each template, it will test the following sa... |
import time
import threading
import traceback
import json
import nose
import sys
import linecache
import inspect
import os.path
import queue as queue
import urllib.parse
from io import StringIO
from http.server import HTTPServer, BaseHTTPRequestHandler
import socketserver as socketserver
from mpi4py import MPI
from no... |
from PySide import QtGui
from functools import partial
from maya.app.general.mayaMixin import MayaQWidgetBaseMixin
import maya.cmds as cmds
_win = None
def show():
global _win
if _win == None:
_win = BindingDialog()
_win.show()
class BindingDialog(MayaQWidgetBaseMixin, QtGui.QDialog):
def __... |
# coding: utf-8
from __future__ import unicode_literals
from admitad.items.base import Item
__all__ = [
'BrokenLinks',
'ManageBrokenLinks'
]
class BrokenLinks(Item):
SCOPE = 'broken_links'
URL = Item.prepare_url('broken_links')
SINGLE_URL = Item.prepare_url('broken_links/%(broken_link_id)s')
... |
from flask import Flask, render_template
app = Flask(__name__, template_folder='templates')
@app.route("/")
def index():
return render_template("index.html")
# otro
@app.route("/video")
def video():
return render_template("video.html")
# material
@app.route("/material")
def material():
... |
import typing as t
from .filters import FILTERS as DEFAULT_FILTERS # noqa: F401
from .tests import TESTS as DEFAULT_TESTS # noqa: F401
from .utils import Cycler
from .utils import generate_lorem_ipsum
from .utils import Joiner
from .utils import Namespace
if t.TYPE_CHECKING:
import typing_extensions a... |
"""
.. module: lemur.users.schemas
:platform: unix
:copyright: (c) 2015 by Netflix Inc., see AUTHORS for more
:license: Apache, see LICENSE for more details.
.. moduleauthor:: Kevin Glisson <kglisson@netflix.com>
"""
from marshmallow import fields
from lemur.common.schema import LemurInputSchema, LemurOutp... |
"""Module responsible for Ground Truth data set generation."""
|
"""This file defines django models for editor app."""
from __future__ import unicode_literals
from django.db import models
from django.contrib.auth.models import User
from time import time
from hashids import Hashids
from django.conf import settings
def get_photo_path(instance, filename):
"""Define the upload pa... |
import argparse
import glob
import os
import cv2
from yolo import YOLO
ap = argparse.ArgumentParser()
ap.add_argument('-i', '--images', default="images", help='Path to images or image file')
ap.add_argument('-n', '--network', default="normal", help='Network Type: normal / tiny / prn / v4-tiny')
ap.add_argument('-d',... |
#
# PySNMP MIB module CISCO-ENTITY-SENSOR-EXT-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-ENTITY-SENSOR-EXT-MIB
# Produced by pysmi-0.3.4 at Wed May 1 11:57:12 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python versio... |
#当前问题
#1,翻页到最后三种情况,一种是404状态(),一种是200正常但是无标题,一种是200正常但是有标题仍然显示最后一页
from pyquery import PyQuery as pq
import urllib,sys
def get_article_list(url,page_rule,titles_selector,links_selector,page_second_num,encoding="utf-8"):
#如果为空则文章不分页
if page_rule:
#预处理
if "<num>" not in page_rule:
ra... |
#!/usr/bin/python3.6
import argparse
import os
import re
import sys
import logging
def main():
parser = argparse.ArgumentParser("ya-remove")
parser.add_argument("--input", required=False, default=".", type=str, help="""
directory where all the files needs to be replaced. Default to cuyrrent workin... |
number = int(input())
day = ''
if number == 1:
day = 'Monday'
elif number == 2:
day = 'Tuesday'
elif number == 3:
day = 'Wednesday'
elif number == 4:
day = 'Thursday'
elif number == 5:
day = 'Friday'
elif number == 6:
day = 'Saturday'
elif number == 7:
day = 'Sunday'
else:
day = 'Error... |
# Copyright (c) 2016 Uber Technologies, Inc.
#
# 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, publ... |
import re
import markdown
from django.http import Http404
from django.shortcuts import render, get_object_or_404
from markdown.extensions.toc import TocExtension, slugify
from blog.models import Post, Category, Label
def index(request):
posts = Post.objects.filter(is_delete=False).order_by('-c_time', '-pk')
... |
from pathlib import Path
from pyhdx import VERSION_STRING
from importlib.metadata import version
from datetime import datetime
import sys
import os
import platform
def write_log(script_name):
log_name = Path(script_name).stem
out_name = log_name + '.log'
lines = [f"Log file for python script: {log_name}.... |
# =============================================================================
# PROJECT CHRONO - http://projectchrono.org
#
# Copyright (c) 2014 projectchrono.org
# All rights reserved.
#
# Use of this source code is governed by a BSD-style license that can be found
# in the LICENSE file at the top level of the distr... |
class Solution:
def removeDigit(self, number: str, digit: str) -> str:
last_idx = -1
for i in range(len(number)-1):
if number[i] == digit:
last_idx = i
if number[i] < number[i+1]:
return number[:i] + number[i+1:]
if number[-1] =... |
from PyQt5.QtNetwork import QNetworkAccessManager
HTTP_METHOD_TO_QT_OPERATION = {
"HEAD": QNetworkAccessManager.HeadOperation,
"GET": QNetworkAccessManager.GetOperation,
"PUT": QNetworkAccessManager.PutOperation,
"POST": QNetworkAccessManager.PostOperation,
"DELETE": QNetworkAccessManager.DeleteOp... |
from .context import *
from .frontend import *
from .signals import *
from .stdlib import * |
# Tested with Python 2.1
import re
#
# The simplest, lambda-based implementation
#
def multiple_replace(dict, text):
""" Replace in 'text' all occurences of any key in the given
dictionary by its corresponding value. Returns the new tring."""
# Create a regular expression from the dictionary keys
reg... |
"""setup.py
Upload to PyPI:
python setup.py sdist
twine upload --repository pypitest dist/qpack-X.X.X.tar.gz
twine upload --repository pypi dist/qpack-X.X.X.tar.gz
"""
import setuptools
from distutils.core import setup, Extension
from qpack import __version__
module = Extension(
'qpack._qpack',
define_macros... |
# coding: utf-8
# Standard
import sys
import json
# Third-party
from flask import Flask, request
# Local
from v1api import V1API
VERSION = 0.11
APPNAME = 'BI-Beacon Open Source Server'
state = {}
flask_app = Flask(APPNAME)
def tuple2command(tup):
if len(tup) == 3:
return 'color %d %d %d\n' % tup
... |
from modules import engine
from modules import out
from modules import run
from modules import php
from time import sleep
@engine.prepare_and_clean
def execute():
#make sure we have the php command file online
php.upload_command_file()
#open it with the phpinfo parameter
run.local('open ' + engine.REMO... |
from g_module import some_awesome_func
def a_func():
return "a func"
from a_module.b_module.b_file import b_func
def some_other_func():
return "other_value" |
import inspect
import re
import sys
from typing import (
Any,
Callable,
Dict,
Generic,
Iterable,
List,
Optional,
Tuple,
TypeVar,
Union,
cast,
overload,
)
from redun.expression import SchedulerExpression, TaskExpression
from redun.hashing import hash_arguments, hash_struc... |
from django.contrib import admin
from supervisor.models import TA, Notification, Example, Comment, News, Flag
admin.site.register(TA)
admin.site.register(Notification)
admin.site.register(Example)
admin.site.register(Comment)
admin.site.register(News)
admin.site.register(Flag) |
from tapis_cli.display import Verbosity
from tapis_cli.search import SearchWebParam
from .mixins import AppIdentifier
from tapis_cli.commands.taccapis import SearchableCommand
from .create import AppsCreate
from . import API_NAME, SERVICE_VERSION
from .models import App
from .formatters import AppsFormatOne
__all__ ... |
#!/usr/bin/env python3
###############################################################################
# Main entrypoint to the Question Classification project
# Starts training or test given an experiment config
###############################################################################
import os
import hydra
fr... |
from ...expressions import (
Expression,
Symbol,
FunctionApplication as Fa,
Constant as C,
)
from ...expression_walker import (
add_match,
ExpressionWalker,
ReplaceSymbolWalker,
)
from .chart_parser import Quote, CODE_QUOTE
from .english_grammar import S, V, NP, VP, PN, DET, N, VAR, SL, LIT
... |
from setuptools import setup, find_packages
from codecs import open
with open("README.md", "r") as fh:
long_description = fh.read()
setup(
name='websites_metrics_consumer',
version='0.0.4',
packages=find_packages(exclude=['contrib', 'docs', 'tests*']),
install_requires=["psycopg2","confluent_kafka... |
#commands is a list, st
def filewriter(commands):
with open("ans", "w") as file:
file.write(len(commands))
for i in xrange(len(0, commands)):
if commands[i][1] != "L" and commands[i][1] != "U" and commands[i][1] != "W" and commands[i][1] != "D":
raise ValueError("Inv... |
import typing
import uvicorn
from starlette.routing import Match
from starlette.types import Scope
from fastapi import FastAPI
from fastapi.routing import APIRoute, APIRouter
class NewRoute(APIRoute):
def matches(self, scope: Scope) -> typing.Tuple[Match, Scope]:
if scope["type"] == "http":
m... |
# -*- coding: utf-8 -*-
r"""
Extract your project's __version__ variable
When creating a ``setup.py`` for a new project, do you find yourself always
writing the same block of code for parsing ``__version__`` from your project's
source? Something like this?
::
with open(join(dirname(__file__), 'package_name', '_... |
"""TP-Link adapter for WebThings Gateway."""
from gateway_addon import Property
class BusproProperty(Property):
"""TP-Link property type."""
def __init__(self, device, name, description, value):
"""
Initialize the object.
device -- the Device this property belongs to
name -- ... |
import os
import json
import sqlite3
import datetime, time
import itertools
from common import util
import queue
import threading
from threading import Thread
import logging
import sqlite3
import datetime, time
import itertools
from common import util
class IDEBenchDriver:
def init(self, options, schema, driver... |
from typing import Dict, Mapping, Optional, Tuple, Union, Set
from enum import Enum, auto
import os
import warnings
import numpy as np
from numpy.random.mtrand import seed
import torch as th
from ail.common.type_alias import GymEnv
from ail.common.math import normalize
class Buffer:
__slots__ = [
"_capa... |
from functools import partialmethod
class PartialMethod:
def method(self, value, expected, lower: bool = False):
if lower is True:
value = value.lower()
assert value == expected
partial_method = partialmethod(method, expected='value')
|
import discord
import os
from discord.ext import commands
import json
import asyncio
import datetime
import traceback
import sys
import pathlib
import time
class Owner(commands.Cog):
def __init__(self, client):
self.client = client
@commands.command()
#------------------------------
# Get info... |
'''
Aim: Determine whether the entered string is palindrome or not.
'''
class Solution:
def __init__(self):
self.stack = []
self.queue = []
return(None)
def pushCharacter(self, char):
self.stack.append(char)
def popCharacter(self):
return(... |
import argparse
from bbworld import save_pic, load_pic, iterate_board
def _save_iteration(savename, save_board, iteration, max_iterations):
if (savename):
filename = savename[0]
num_digits = len(str(max_iterations))
filename += "_" + str(iteration).zfill(num_digits) + ".png"
save_pi... |
# encoding: utf-8
"""
Script to train handwriting model
Change global vars if you want to change how data is loaded or to change major model training params
"""
import os
import json
import time
import torch
import torch.nn.functional as F
import torchvision.models as models
import torchvision.transforms as transfor... |
"""
This module contains the classes that encapsulate the business logics to
collect tweets.
The collectors available are:
* OfficialAPICollector - It collects tweets through the official
Twitter API.
Notes
-----
It is wanted to add web scraping collectors to bypass the official API
limitations. Feel free to ... |
import numpy as np
x_data = np.float32(np.random.rand(2,100))
y_data = np.dot([0.1, 0.2], x_data) + 0.300
print(y_data) |
#
# Copyright 2015 Horde Software Inc.
#
import sys
from PySide import QtGui, QtCore
# Add the pyflowgraph module to the current environment if it does not already exist
import imp
try:
imp.find_module('pyflowgraph')
found = True
except ImportError:
import os, sys
sys.path.insert(0, os.path.abspath(o... |
# -*- coding: utf-8 -*-
'''
# Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
#
# This file was generated and any changes will be overwritten.
'''
from __future__ import unicode_literals
from ..model.windows_delive... |
'''
Name: flowcontrol_if.py
Author: Yang Ze
Created: 2019.04.02
Last Modified:
Version: V1.0
Description: An example for if...elif...else...
'''
# There is no switch statement in Python. You can use an if..elif..else statement to
# do the same thing (and in some cases, use a dictionary to do it quickly)
number = 23
g... |
#!/usr/bin/env python
import argparse
import importlib
import inspect
import struct
import sys
import time
import emuplugin
import disasm
try:
raw_input
except NameError:
raw_input = input
# offsets into DCPU16.memory corresponding to addressing mode codes
SP, PC, O, LIT = 0x1001B, 0x1001C, 0x1001D, 0x1001... |
# Copyright 2017 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... |
name = "Foundation"
|
"""
Amazon MWS Feeds API
"""
from __future__ import absolute_import
from ..mws import MWS
from .. import utils
from ..decorators import next_token_action
# TODO Add FeedProcessingStatus enumeration
# TODO Add FeedType enumeration
def feed_options_str(feed_options):
"""Convert a FeedOptions dict of values into ... |
# Licensed under a 3-clause BSD style license - see LICENSE.rst
try:
# Not guaranteed available at setup time
from .spectrum import BaseSpectrum, AbsorptionSpectrum, CDESpectrum
except ImportError:
if not _ASTROPY_SETUP_:
raise
|
from itertools import izip, izip_longest
import numpy as np
from cocoa.core.entity import is_entity
from cocoa.lib import logstats
from cocoa.model.util import EPS
from cocoa.model.evaluate import BaseEvaluator
from preprocess import markers
from graph import Graph
def remove_entities(entity_tokens):
eoe_inds = ... |
import os
import numpy as np
from PIL import Image
import matplotlib.pyplot as plt
import random
LOCATION = 'images/'
location_src = LOCATION + 'movie_pics/'
location_squares = LOCATION + 'squares/'
location_squares_error = LOCATION + 'error_squares/'
images = os.listdir(location_src)
n_images = len(images)
print(f"[... |
from django.urls import re_path
from . import consumers
websocket_urlpatterns = [
re_path(r"ws/judge/queue/", consumers.QueueUpdateConsumer.as_asgi()),
re_path(r"ws/judge/scoreboard/", consumers.ScoreboardUpdateConsumer.as_asgi()),
]
|
from input import input_file
file = input_file('input_files/day2_input.txt')
def part1(input_values):
horiz = 0
up = 0
down = 0
for i in input_values:
if 'f' in i:
horiz += int(i[-1])
elif 'n' in i:
down += int(i[-1])
elif 'p' in i:
... |
"""Implementation of core Haskell rules"""
load(
"@io_tweag_rules_haskell//haskell:providers.bzl",
"C2hsLibraryInfo",
"HaskellInfo",
"HaskellLibraryInfo",
"HaskellPrebuiltPackageInfo",
)
load(":cc.bzl", "cc_interop_info")
load(
":private/actions/link.bzl",
"link_binary",
"link_library_d... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Import Pygments Package
from pygments.lexers.sql import SqlLexer
# Import PromptToolkit Package
from prompt_toolkit import PromptSession
from prompt_toolkit.completion import WordCompleter
from prompt_toolkit.lexers import PygmentsLexer
from prompt_toolkit.styles impor... |
# Copyright 2020 Robin Scheibler
#
# 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, distrib... |
from .emailutil import * |
import collections
import functools
import logging
import uuid
from ..collections.attrdict import AttrDict
from ..utils import perf
from .run_state import RunState
log = logging.getLogger(__name__)
class Entity(int):
"""Entity is just and integer ID.
All data related to given Entity is stored in Compone... |
from api.lib.testutils import BaseTestCase
import api.companies.unittest
class TestReadCompany(BaseTestCase):
def test_read_company(self):
resp = self.app.get('/companies/exponential')
assert 'Palo Alto' in resp.data
if __name__ == "__main__":
api.companies.unittest.main() |
#!/usr/bin/python
# -*- coding: utf-8 -*-
from NodeGraphQt import QtWidgets, QtCore
from NodeGraphQt.constants import DRAG_DROP_ID
TYPE_NODE = QtWidgets.QTreeWidgetItem.UserType + 1
TYPE_CATEGORY = QtWidgets.QTreeWidgetItem.UserType + 2
class BaseNodeTreeItem(QtWidgets.QTreeWidgetItem):
def __eq__(self, other)... |
# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: primitive.proto
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol... |
import argparse
import asyncio
import os
import socket
import tempfile
from pathlib import Path
from aiohttp import (
ClientSession,
ClientTimeout,
WSMessage,
)
from chia.cmds.init_funcs import create_all_ssl
from chia.protocols.protocol_message_types import ProtocolMessageTypes
from chia.protocols.shared... |
from rubygems_utils import RubyGemsTestUtils
class RubyGemsTestrubygems_mixlib_config(RubyGemsTestUtils):
def test_gem_list_rubygems_mixlib_config(self):
self.gem_is_installed("mixlib-config")
|
from __future__ import unicode_literals
from frappe import _
def get_data():
return [
{
"label": _("Masters"),
"icon": "icon-star",
"items": [
{
"type": "doctype",
"name": "Territory",
"description": _(" "),
},
{
"type": "doctype",
"name": "Customer Group",
"desc... |
"""
This file implements Batch Normalization as described in the paper:
"Batch Normalization: Accelerating Deep Network Training
by Reducing Internal Covariate Shift"
by Sergey Ioffe, Christian Szegedy
This implementation is useful for input... |
"""Define util functions for data preparation"""
import re
from typing import List
import nltk
from nltk import word_tokenize
from nltk.corpus import stopwords
from nltk.stem import WordNetLemmatizer
nltk.download("wordnet")
nltk.download("stopwords")
nltk.download("punkt")
abbr_dict = {
"what's": "what is",
... |
not_yet_food = "cous"
food = not_yet_food * 2
print(food)
|
#!/usr/bin/env python
from constructs import Construct
from cdktf import App, TerraformStack
from imports.aws import SnsTopic
class MyStack(TerraformStack):
def __init__(self, scope: Construct, ns: str):
super().__init__(scope, ns)
# define resources here
SnsTopic(self, 'cdktf-phython-top... |
from typing import List
import pandas as pd
"""
%cd /workspace/twint/app
from app import tools
tools.generate_rss_yahoo_csv(
save_to="./resource/rss_yahoo_us_indicies.csv",
symbol_path="./resource/symbol_indicies.csv")
"""
def generate_rss_yahoo_csv(
save_to="./resource/rss_yahoo_us_stock.csv",
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from instabot_py import InstaBot
bot = InstaBot(
login="",
password="",
like_per_day=7019,
comments_per_day=197,
tag_list=["aviation", "sky", "avgeek", "aviationlovers", "boeing", "aircraft", "pilot", "airplane" ,"plane" ... |
import os
import datetime
import numpy as np
import scipy
import pandas as pd
import torch
from torch import nn
import criscas
from criscas.utilities import create_directory, get_device, report_available_cuda_devices
from criscas.predict_model_training import *
# base_dir = os.path.abspath('...')
base_dir = "/home/da... |
from django import test, forms
from ginger.forms import FileOrUrlInput
class DummyForm(forms.Form):
file = forms.FileField(widget=FileOrUrlInput, required=False)
class RequiredDummyForm(forms.Form):
file = forms.FileField(widget=FileOrUrlInput, required=True)
class TestFileOrUrlInput(test.SimpleTestCase):... |
"""
j is the index to insert when a number not equal to val.
j will never catch up i, so j will not mess up the check.
"""
class Solution(object):
def removeElement(self, nums, val):
j = 0
for n in nums:
if n!=val:
nums[j] = n
j += 1
return j |
"""
Usage:
convert_to_excel.py [options]
Options:
-h --help Show this screen
-v --version Show version
-f, --file <file-name> Path to SSA.gov site XML file
"""
import os
import sys
import xmltodict
from docopt import docopt
from excel_helper import Excel
class EarningsData(object... |
from django.test import TestCase, Client
import http.client
from checkout.models import Order, PickList
from meadery.models import Product
from checkout.checkout import all_in_stock, create_picklist, process_picklist, cancel_picklist
# admin.py
# write tests for processing and cancelling orders from web
# write silly ... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.conf.urls import include, url
from . import rest_api
from . import auth
from ..views.term import RebuildTermTreeView
from ..views.data_mart import RebuildDataMartTreeView
urlpatterns = (
url(r'^rebuild_term_tree/',
RebuildTermTr... |
from django.contrib.auth import get_user_model
from django.test import TestCase
from django.urls import reverse
from .models import Snack
class SnacksTests(TestCase):
def setUp(self):
self.user = get_user_model().objects.create_user(
username="dina", email="dina_albarghouthi@yahoo.com", passw... |
import threading
import os
import hashlib
DATABASE_DIR = "dbFiles"
os.chdir(DATABASE_DIR)
class Database:
def __init__(self, name = None):
if name:
if self.CreateDatabaseFile(name):
print("DB created successfuly")
elif self.SelectDatabaseFile(name):
... |
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
import typing as t
from dataclasses import dataclass, field
from hmalib.common.classification_models import Label
from hmalib.common.config import HMAConfig
@dataclass(unsafe_hash=True)
class ActionLabel(Label):
key: str = field(default="Act... |
try:
from tornado import speedups
except ImportError:
speedups = None
|
from typing import List
from functools import lru_cache
class Solution:
def maxProduct(self, words: List[str]) -> int:
mask = {}
for word in words:
key = 0
for c in word:
key |= 1 << (ord(c) - 97)
mask[key] = max(mask.get(key, 0), len(word))
... |
#!/usr/bin/env python
# encoding: utf-8
"""
power-of-three.py
Created by Shuailong on 2016-01-10.
https://leetcode.com/problems/power-of-three/.
"""
'''Refer to some discussions. Think about it later. '''
class Solution(object):
def isPowerOfThree(self, n):
"""
:type n: int
:rtype: bo... |
import gym.spaces as spaces
from gym import ActionWrapper
class FlattenAction(ActionWrapper):
r"""Action wrapper that flattens the action."""
def __init__(self, env):
super(FlattenAction, self).__init__(env)
self.action_space = spaces.flatten_space(env.action_space)
def action(self, action... |
from os.path import isfile, isdir, join, dirname
from os import listdir, makedirs
import shutil
import numpy as np
from tqdm import tqdm
def transform(h36m_path, target_dir):
from spacepy import pycdf # make sure that this is only imported when actually needed..
assert isdir(h36m_path), h36m_path
if isdi... |
"""Parking Valet, by Al Sweigart al@inventwithpython.com
A sliding tile puzzle game to move cars out of the way.
Inspired by Nob Yoshihagara's Rush Hour.
parkingvaletpuzzle.txt generated from puzzles by Michael Fogleman.
More info at https://www.michaelfogleman.com/rush/
This and other games are available at https://no... |
import logging
from typing import Callable
import numpy as np
# Starting logger
LOGGER = logging.getLogger(__name__)
class EarlyStopping:
"""Early stops the training if validation loss doesn't improve after a given patience."""
def __init__(self, patience: int = 7, delta: float = 1e-6):
"""
... |
from recipes.native_typing import simple
def test_wf():
x, y = simple.t1(a=5)
assert x == 7
|
from django.contrib import admin
from .models import Account;
from django.contrib.auth.admin import UserAdmin;
# Register your models here.
class AccountAdmin(UserAdmin):
list_display = ('email','date_joined','last_login','is_admin','is_staff','profile_pic','first_name','last_name',"id","show_to_public", "chat_keys"... |
# import tensorflow as tf
import numpy as np
import tensorflow.keras.backend as K
from tensorflow.keras.layers import Layer
from tensorflow.keras.layers import Conv1D
from tensorflow.keras.regularizers import Regularizer
from tensorflow.keras import initializers
import scipy.interpolate as si
DNA = ["A", "C", "G", "T... |
#Do not trust this code, does not work
print("This program will transform input into pig latin")
Cont = False
while Cont == False:
beforePig = input("What shalt thou make pig? : ")
#File = open('piglatin.txt', a)
print(len(beforePig))
afterPig = beforePig[0]
beforePig.append(afterPig)
break
prin... |
from base64 import b64encode
from datetime import datetime
from decimal import Decimal
from math import ceil
from flask_sqlalchemy import SQLAlchemy, BaseQuery
from sqlalchemy import orm
from sqlalchemy.orm import joinedload
from functools import wraps
import jwt
from sqlalchemy.orm.state import InstanceState
from vi... |
#!/usr/bin/env python
# Author: Trevor Sherrard
# Since: July 28, 2021
# Purpose: This node translates the current orientation
# of the haptic controller into robot base motion
import rospy
from pyrobot import Robot
import time
import numpy as np
from sensor_msgs.msg import LaserScan
from haptic_orientation_... |
import os
from disnake import ApplicationCommandInteraction
from dotenv import load_dotenv
load_dotenv()
DEBUG = os.getenv("DEBUG", None) is not None
DEFAULT_PREFIX = os.getenv("DEFAULT_PREFIX", "$")
TEST_GUILDS = (
[int(id_) for id_ in os.getenv("TEST_GUILDS").split(",")]
if os.getenv("TEST_GUILDS", None)
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.