content stringlengths 5 1.05M |
|---|
import queue
import cards
import random
#create card decks
class constructBoard:
def __init__(self, lowLevelCards = queue.Queue(), midLevelCards = queue.Queue(), highLevelCards = queue.Queue()):
self.lowlevelcards = lowLevelCards
self.midlevelcards = midLevelCards
self.highlevelcar... |
from pytest import raises
class IndexedPropertyMapper(object):
def __init__(self, desc, instance):
self.desc = desc
self.instance = instance
def __getitem__(self, item):
return self.desc.fget(self.instance, item)
def __setitem__(self, item, value):
# hmm. is this order of ... |
import asyncio
import shutil
from collections import namedtuple
from concurrent.futures.thread import ThreadPoolExecutor
from datetime import datetime, timedelta, timezone
from shlex import split as lex
from subprocess import DEVNULL, Popen
import bottle as bt
import httpx
import peewee as pw
import toml
from waitress... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'ui/ForgottenPassword2.ui'
#
# Created by: PyQt5 UI code generator 5.15.6
#
# WARNING: Any manual changes made to this file will be lost when pyuic5 is
# run again. Do not edit this file unless you know what you are doing.
from PyQt5 impor... |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... |
# -*- coding: utf-8 -*-
import re
from pybuilder.core import init
from pybuilder.core import task
from pybuilder.core import depends
from pybuilder.errors import BuildFailedException
from pybuilder.pluginhelper.external_command import ExternalCommandBuilder
from pybuilder.utils import assert_can_execute
@init
def i... |
"""Class hierarchy for base gates."""
import math
from dataclasses import dataclass
from functools import singledispatch, reduce
from numbers import Number
from typing import Tuple, Union, Callable, Dict, Optional, Iterable, Any, List
import sympy
from typing_extensions import Protocol
import numpy as np
from ...util... |
import pygame, sys
from pygame.locals import *
import random
pygame.init() #initializing the pygame library
#creating sample questions
data = [
{
'question': 'Who is the president of America?',
'right-answer': 'Barack Obama',
'option1' : 'George Washington',
'option2' : 'Paul Kagame',
'option3' : 'Barack O... |
# example of setting up, running, and graphing landau damping in 3D
import os
import py_platypus as plat
from py_platypus.utils.params import Parameters as Parameters
from py_platypus.vis.plotter import Plotter as Plotter
if __name__ == "__main__":
# override default parameters
params = {
"dimen... |
#from app import Util
import aiml
import sys
def formatOutPut(text):
text = text.replace('\\t','\t')
text = text.replace('\\n','\n')
return text
def stripCommand(text):
if(text[0] == '/'):
return text[1:]
return text
def main():
#create and configurate bot knowledbase
ctfbot = ... |
from trackstats.models import Domain, Metric
# Domains
Domain.objects.INVESTMENT = Domain.objects.register(
ref='investment',
name='investment'
)
# Metrics, these are associated with a domain
Metric.objects.INVESTMENT_COUNT = Metric.objects.register(
domain=Domain.objects.INVESTMENT,
ref='investment_... |
import logging
import json
import transaction
from pyramid.view import view_config
from pyramid.request import Response
__author__ = 'max'
log = logging.getLogger(__name__)
MODULE_DIR = "newsbomb_recommends.views"
@view_config(route_name='generic', renderer='json')
def api(request):
try:
module = req... |
"""
Define the abstract Game class for providing a structure/ interface for agent environments.
Notes:
- Base implementation done.
- Documentation 15/11/2020
"""
from abc import ABC, abstractmethod
import typing
import numpy as np
from utils.game_utils import GameState
class Game(ABC):
"""
This class spe... |
x="There are %d types of people." % 10
binary="binary"
do_not="dont't"
y="Those who know %s and those who %s." % (binary,do_not)
print(x)
print(y)
print("I said: %r" % x)
print("I also said: '%s'." % y)
hilarious=False
joke_evaluation="Isn't that joke so funny?! %r"
print(joke_evaluation % hilarious)
w="This is t... |
# -*- encoding: utf-8 -*-
from bs4 import Tag
from datetime import datetime
from dateutil.parser import parse
from dateutil.relativedelta import relativedelta
from scrapers.helpers import jsonify_seminars
#########################################################
# This part will seriously depend on the structure of ... |
#============================== IBM Code Challenge =============================
# mat_gui.py
#
# Creates GUI for user to interact with
#
# Description:
# This generates a GUI that allows the user to enter two matrices, select
# a mathematical operation, and displays the operation result to the user.
# The ... |
"""
Uses docspec to parse docstrings to markdown.
Intended for use with static site generators where further linting / linking / styling is done downstream.
Loosely based on Numpy-style docstrings.
Automatically infers types from signature typehints. Explicitly documented types are NOT supported in docstrings.
"""
i... |
from django.shortcuts import render, get_object_or_404, redirect
from django.utils import timezone
from django.urls import reverse_lazy
from status import models, forms
from django.contrib.auth.decorators import login_required
# Create your views here.
@login_required
def add_comment(request,pk):
post = get_obj... |
def countingSort(arr):
counter = [0]*100 # as per the constraint that arr[i] < 100
for num in arr:
counter[num] += 1
sorted = []
for num, cnt in enumerate(counter):
sorted += [num]*cnt
return sorted
|
#
# relu paddle model generator
#
import numpy as np
from save_model import saveModel
import sys
def relu(name: str, x):
import paddle as pdpd
pdpd.enable_static()
node_x = pdpd.static.data(name='x', shape=x.shape, dtype='float32')
out = pdpd.nn.functional.relu(node_x)
cpu = pdpd.static.cpu_plac... |
import os
import os.path
from dataclasses import dataclass
from os import path
import sys
from typing import List
import requests
from bs4 import BeautifulSoup
import re
import win32console # needs pywin32
import time
_stdin = win32console.GetStdHandle(win32console.STD_INPUT_HANDLE)
def input_def(prompt, default=''... |
import numpy as np
def get_box_from_point(x,y,kernel,pad,stride):
kernel_x = kernel[0]
kernel_y = kernel[1]
pad_x = pad[0]
pad_y = pad[1]
stride_x = stride[0]
stride_y = stride[1]
x_min = (x - 1) * stride_x + 1 - pad_x
x_max = (x - 1) * stride_x - pad_x + kernel_x
y_min = (y - 1) *... |
from django.urls import path
from . import views
urlpatterns = [
path("", views.OrderDetailsView.as_view()),
path("<uuid:order_id>", views.OrderDetailsView.as_view()),
path("status/<str:order_status_value>", views.OrderStatusView.as_view()),
path("incoming", views.IncomingOrders.as_view()),
path("s... |
# Copyright (c) 2021 PaddlePaddle 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 applic... |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
import hungrybotlib as l
from random import choice
import config as cfg
l.cacheMenus(cfg.menu_file, cfg.menu_url, cfg.days)
with open("counter", "r") as f:
count = int(f.read())
text = ["Une nouvelle semaine de bouffe !", "Et voila, je viens de mettre à jour les m... |
"""Output an NML file cataloging a set of audio files.
NML is an XML-based file format used by Traktor. This code generates
NML version 11, which is used by Traktor Pro.
"""
import time
import xml.sax.saxutils
from chirp.common import timestamp
from chirp.common import unicode_util
from chirp.library import artists... |
input = open('input/input12.txt').readlines()
plants = []
ZERO = 5
BASE_GEN_COUNT = 0
FINAL_GEN_COUNT = 50000000000
will_grow = set()
wont_grow = set()
for line in input:
line = line.strip()
if line.startswith('initial'):
pots = list(line.split(' ')[2])
BASE_GEN_COUNT = len(pots)
plants ... |
SOCIAL_AUTH_GITHUB_KEY = '0ec5adf60f9d0db84213'
SOCIAL_AUTH_GITHUB_SECRET = 'c4b6cd88aac6b4515c5b396be2727b21ee54725e'
SOCIAL_AUTH_LOGIN_URL = '/login'
SOCIAL_AUTH_LOGIN_REDIRECT_URL = '/'
SOCIAL_AUTH_LOGIN_ERROR_URL = '/login-error/'
SESSION_COOKIE_DOMAIN = '.localhost.be'
USE_X_FORWARDED_HOST = True
S... |
from functools import lru_cache
import os
from time import time
import json
from io import StringIO
import markdown
import jwt
import requests
import github
import datetime
import logging
from time import sleep
from ruamel.yaml import YAML
yaml = YAML()
ZOOM_API = "https://api.zoom.us/v2/"
SPEAKERS_CORNER_USER_ID = ... |
# Clase 24. Curso Píldoras Informáticas.
# Control de Flujo. POO1.
# Clase de Teoría.
# Lenguajes orientados a objetos: C++, Java, VisualNet...
# Atributos/Propiedades: elementos que definen las clases y objetos.
# Ventajas POO:
# Se pueden establecer Módulos.
# Código muy reciclable (esto con Fo... |
#coding=utf-8
import tensorflow as tf
import wmodule
import basic_tftools as btf
import wml_tfutils as wmlt
from object_detection2.datadef import EncodedData
import tfop
import functools
from object_detection2.datadef import *
import numpy as np
import wnn
import wsummary
from .build import HEAD_OUTPUTS
import object_d... |
from sqlalchemy import Integer, Text, DateTime, func, Boolean, text
from models.database_models import Base, Column
class Comment(Base):
__tablename__ = "comment"
id = Column(Integer, primary_key=True, )
user_id = Column(Integer, nullable=False, comment="评论用户的 ID")
post_id = Column(Integer, nullable... |
#!/usr/bin/env python
# Copyright (C) 2009 Chia-I Wu <olv@0xlab.org>
# All Rights Reserved.
#
# This is based on extension_helper.py by Ian Romanick.
#
# 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... |
# -*- coding: utf-8 -*-
# see LICENSE.rst
# ----------------------------------------------------------------------------
#
# TITLE : Code for the Examples
# AUTHOR : Nathaniel Starkman
# PROJECT : TrackStream
#
# ----------------------------------------------------------------------------
"""Examples Code."""
__a... |
def keep_evens(nums):
new_seq = filter(lambda num: num % 2 == 0, nums)
return list(new_seq)
print(keep_evens([3, 4, 6, 7, 0, 1]))
# Saída [4, 6, 0]
'''
1. Write code to assign to the variable filter_testing all the elements in lst_check that have a w in them using filter.
'''
lst_check = ['plums', 'watermelon... |
from django.dispatch import Signal
signup_complete = Signal(providing_args=["user",])
activation_complete = Signal(providing_args=["user",])
confirmation_complete = Signal(providing_args=["user","old_email"])
password_complete = Signal(providing_args=["user",])
order_complete = Signal(providing_args=["user",])
email_c... |
#!/usr/bin/env python3
from setuptools import setup
setup(
name='lilist',
version='0.1.0',
description='A linear interpolation list class',
url='http://github.com/MatthewScholefield/lilist',
author='Matthew Scholefield',
author_email='matthew331199@gmail.com',
license='MIT',
py_modules... |
from unittest import TestCase
import json
import attr
from marshmallow_helpers import RegisteredEnum, attr_with_schema
def enum_to_schema(enum_cls):
@attr_with_schema(register_as_scheme=True, strict=True)
@attr.s(auto_attribs=True)
class MyEnum:
enum: enum_cls
return MyEnum.schema
def enum... |
from flask import Flask
from flask_cors import CORS
import json, sys, os, base64
app = Flask(__name__)
CORS(app)
import logging
logging.getLogger("werkzeug").setLevel(logging.ERROR)
@app.route("/set_contest/<contestname>/<userhash>")
def set_contest(contestname, userhash):
print(base64.b64decode(contestname.repl... |
from operator import mul
numstr = '73167176531330624919225119674426574742355349194934\
96983520312774506326239578318016984801869478851843\
85861560789112949495459501737958331952853208805511\
12540698747158523863050715693290963295227443043557\
66896648950445244523161731856403098711121722383113\
622298934233803081353362... |
import asyncio
import unittest.mock
import pytest
START = object()
END = object()
RETVAL = object()
@pytest.fixture
def mock():
return unittest.mock.Mock(return_value=RETVAL)
@pytest.fixture
async def async_fixture(mock):
return await asyncio.sleep(0.1, result=mock(START))
@pytest.mark.asyncio
async def... |
r = float(input('Quanto dinheiro você tem na carteira?: R$'))
print('Com R${:.2f} você pode comprar US${:.2f}'.format(r, (r/3.27)))
|
"""
XMLAction module.
"""
from pineboolib.core.utils import logging
import os.path
from pineboolib.core.utils.struct import ActionStruct
from .utils.path import _path, coalesce_path
from typing import Optional, Any, Union, TYPE_CHECKING
if TYPE_CHECKING:
from pineboolib.fllegacy.flaction import FLAction # noqa:... |
from datetime import datetime
from pathlib import Path
import unittest
import pandas as pd
import numpy as np
import vak
import article.syntax
HERE = Path(__file__).parent
DATA_DIR = HERE.joinpath('test_data')
class TestSyntax(unittest.TestCase):
def test_date_from_cbin_filename(self):
CBIN_FILENAME = ... |
"""
The ``fine_tune.py`` file is used to continue training (or `fine-tune`) a model on a `different
dataset` than the one it was originally trained on. It requires a saved model archive file, a path
to the data you will continue training with, and a directory in which to write the results.
. code-block:: bash
$ pyt... |
#!/usr/bin/python3
from brownie import HuskyTokenDeployer, accounts, HuskyToken, HuskyTokenMinter, Wei
def main():
provost = accounts.load('husky')
admin = provost
is_live = False
if provost.balance() == 0:
accounts[0].transfer(provost, Wei('1 ether'))
husky_token = HuskyToken.deploy("Husky... |
from pprint import pprint
import gym
env = gym.make('ChessVsRandomBot-v0')
def available_moves():
state = env.state
moves_p1 = env.get_possible_moves(state, 1)
moves_p2 = env.get_possible_moves(state, -1)
pprint(moves_p1)
pprint(moves_p2)
# no actions left -> resign
if len(moves_p1) == ... |
def is_valid(phrase):
words = phrase.split()
word_letters = list(map("".join, map(sorted, words)))
return len(set(word_letters)) == len(words)
passphrases = open("day4.txt").readlines()
valid_phrases = list(filter(is_valid, passphrases))
print('Valid Passphrases:', len(valid_phrases)) # = 231
|
import os
import datetime
import argparse
import numpy
import networks
import torch
modelnames = networks.__all__
# import datasets
datasetNames = ('Vimeo_90K_interp') #datasets.__all__
parser = argparse.ArgumentParser(description='DAIN')
parser.add_argument('--debug',action = 'store_true', help='Enable debug mode'... |
# Copyright 2019 Xilinx 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 writing, ... |
# -*- coding: utf-8 -*-
import argparse
import pandas as pd
from zvt import init_log, zvt_env
from zvt.api.quote import get_stock_factor_schema
from zvt.contract import IntervalLevel
from zvt.contract.api import df_to_db
from zvt.contract.recorder import FixedCycleDataRecorder
from zvt.recorders.joinquant.common import... |
import sys, re
def alphaprint(code):
r = "^(abcdefghijklmnopqrstuvwxyz)*(a(b(c(d(e(f(g(h(i(j(k(l(m(n(o(p(q(r(s(t(u(v(w(x(y(z?)?)?)?)?)?)?)?)?)?)?)?)?)?)?)?)?)?)?)?)?)?)?)?)?)?)?$"
if re.match(r, code, re.I):
last=""
for i in range(len(code)):
if code[i].isupper():
print(end=chr(i % 256))
... |
# Create your models here.
from django.db import models
from django.contrib.auth.models import AbstractUser
from django.conf import settings
from .common import *
class User(AbstractUser):
#Boolean fields to select the type of account.
is_job_hunter = models.BooleanField(default=False)
is_company = models.Bo... |
#!/bin/python
"""
Title: The DISEMVOWLER
Author: Maxwell Haley
Description: Takes in a line of text from stdin, strips it of all vowles,
then prints the mangled text and it's vowel remains. Done for
/r/DailyProgrammer challenge #149.
You can invoke this script in two ways. First, call the script with no arguments
and ... |
import unittest
from pulsar.apps.test.wsgi import HttpTestClient
from pulsar.utils.httpurl import HttpParser, CHttpParser
class TestPyParser(unittest.TestCase):
__benchmark__ = True
__number__ = 1000
@classmethod
async def setUpClass(cls):
http = HttpTestClient()
response = await htt... |
from . import ash
from . import grm
from . import rdi
from . import srf
from . import sxn
from . import tnl
from . import ubx
# jaykaron
from . import adb
from . import tnt
|
from quiche.egraph import EGraph
from quiche.analysis import MinimumCostExtractor
from .prop_test_parser import PropParser, PropTree, PropTreeCost
from .test_egraph import verify_egraph_shape # , print_egraph
def make_rules():
rules = [
# x -> y ===> ~x | y
PropTree.make_rule("(-> ?x ?y)", "(| ... |
import math
import time
import random
# Print the Main Menu
def menu():
print("---- Public Key Cryptography, RSA ----\n")
print("1) Extended Euclidean Algorithm.")
print("2) Fast Modular Exponentiation.")
print("3) Miller-Rabin Test (True=Composite).")
print("4) Prime Number Generator.")
print... |
from source_hunter import hunter
from source_hunter.hunter import hunt
__all__ = [
'hunter', 'hunt'
]
|
#!/usr/bin/env python
# coding=utf-8
from __future__ import absolute_import
from collections import namedtuple
from difflib import get_close_matches
from warnings import warn
from pytest import mark
from tests.utils import PY34, PY35, PY33, PY26, PY27, PYPY, PY2, PY3
try:
from collections import OrderedDict
exc... |
##############################################################################
# For copyright and license notices, see __manifest__.py file in module root
# directory
##############################################################################
from odoo import _
from odoo.http import request, route
from odoo.addons.... |
#! /usr/bin/env python
# Author: Nuha Nishat
# Date: 1/30/20
import rospy
import sys, os
import math
import geometry_msgs.msg
from geometry_msgs.msg import PoseStamped
from sensor_msgs.msg import JointState
import tf, math
import tf.transformations
import pdb
import moveit_commander
import moveit_msgs.msg
import geom... |
"""Activation Functions Module.
"""
import numpy as np
class Activation:
"""Base class for the activation function.
Warning: This class should not be used directly.
Use derived classes instead.
"""
def f(self, x):
"""Compute the activation function on x.
Warning: Overrides th... |
#
# This file is part of Orchid and related technologies.
#
# Copyright (c) 2017-2020 Reveal Energy Services. All Rights Reserved.
#
# LEGAL NOTICE:
# Orchid contains trade secrets and otherwise confidential information
# owned by Reveal Energy Services. Access to and use of this information is
# strictly limited and... |
from django import forms
class AgendaForm(forms.Form):
date=forms.DateField()
lc=forms.CharField(max_length=50)
|
info = input()
animal_food = {}
areas = {}
while True:
if info == 'Last Info':
break
tokens = info.split(':')
command = tokens[0]
name = tokens[1]
number = int(tokens[2])
area = tokens[3]
if command == 'Add':
if name in animal_food:
animal_food[name] += number
... |
from typing import Any, Callable, Dict, Type
from marshmallow import Schema, fields, post_load
from typing_extensions import Protocol
from .dataclasses import Picture, Product, ProductPage, Size, StockItem
class Dataclass(Protocol):
def __init__(self, **kwargs):
...
def get_dataclass_maker(cls: Type[D... |
from typing import List
class Solution:
def checkPossibility(self, nums: List[int]) -> bool:
flag = False
for i in range(0, len(nums)-1):
if nums[i] > nums[i+1]:
if flag:
return False
if i == 0:
nums[i] = nums[i+1]... |
from tpdataset import RawDataSet, DataDownloader
from torchvision import datasets
from torchvision import transforms
from torch.utils.data import DataLoader
from pyctlib import vector, path, fuzzy_obj
import math
import torch
from ..download_googledrive import download_file_from_google_drive
from functools import par... |
"""Model for blog."""
from django.db import models
from django.utils import timezone
from django.conf import settings
class Post(models.Model):
"""Post model for blog."""
author = models.ForeignKey(
settings.AUTH_USER_MODEL,
on_delete=models.CASCADE,
)
title = models.CharField(max_len... |
"""Números
Faça um programa que produza o resultado abaixo (sendo N fornecido pelo
utilizador). O exercício deve ser resolvido utilizando recursão.
1
1 2
1 2 3
...
1 2 3 ... N
"""
def show(n: int) -> None:
if n > 0:
show(n - 1)
i = 1
while i < n + 1:
print(f'{i:>3} ', end='')
i +=... |
from django.contrib import admin
from website.models import (Category, SubCategory, WebsiteRecommendation,
WebsiteComment, BookRecommendation, BookComment,
VideoRecommendation, VideoComment)
class CategoryAdmin(admin.ModelAdmin):
prepopulated_fields = {'slug... |
"""
Created on 9 Dec 2020
@author: Bruno Beloff (bruno.beloff@southcoastscience.com)
The A4CalibratedDatum is designed to provide a model training data set that encapsulates the calibration of the
electrochemical sensor - the fields we_v_cal, ae_v_zero_cal and cal_x_v have no meaning beyond this.
cal_x_v is only rele... |
from application.domain.application import Application
from application.domain.iBaseWatcher import IBaseWatcher
from application.domain.iCerebrum import ICerebrum
from application.infrastructure.championshipBaseWatcher import ChampionshipBaseWatcher
from application.infrastructure.remoteBaseWatcher import RemoteBaseWat... |
'''
Author : MiKueen
Level : Medium
Company : Google
Problem Statement : Count Unival Subtrees
A unival tree (which stands for "universal value") is a tree where all nodes under it have the same value.
Given the root to a binary tree, count the number of unival subtrees.
For example, the following tree has 5 unival s... |
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
import numpy as np
import {{cookiecutter.project_name}}.parameters as P
class Animation:
'''
A matplotlib window containing an animation for the system. There are
no parameters for initialization, as the Animation object can directly
... |
# -*- coding: utf-8 -*-
"""
Created on Mon Sep 10 13:15:23 2018
@author: sshekhar
"""
from nseurls import *
import six
from nsecommons import *
from nseconstants import *
from datetime import date, timedelta
from bs4 import BeautifulSoup
import pandas as pd
import six
import inspect
dd_mmm_yyyy = StrDate.default_fo... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright 2011 Yesudeep Mangalapilly <yesudeep@gmail.com>
# Copyright 2012 Google 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 ... |
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not... |
# -*- coding: utf-8 -*-
import numpy as np
top = 4000000
fibo1 = 2
fibo2= 1
cumSum = 2
while fibo1 < top:
temp = fibo1
fibo1 = fibo1+fibo2
fibo2 = temp
if fibo1%2==0 and fibo1<top:
print fibo1
cumSum=cumSum+fibo1
print cumSum
|
from django.http import request
from django.shortcuts import render
from . import regresion
import json
def fit(f_type, xvalues, yvalues):
if f_type == 'cuadratic':
print(f_type)
return
# Create your views here.
def RegresionCuadratica(request):
if request.method == 'POST':
xvalues = reque... |
import gym
from baselines import ampi
from baselines import bench
from baselines.ampi import mlp_policy
from baselines import logger
def callback(lcl, _glb):
# stop training if reward exceeds 199
is_solved = lcl['t'] > 100 and sum(lcl['episode_rewards'][-101:-1]) / 100 >= 199
return is_solved
LOG_DIR="/h... |
"""Test suite for pytorch_ranking."""
|
#!/usr/bin/env python
'''
File name: do_color_propagation.py
Author: Varun Jampani
'''
# ---------------------------------------------------------------------------
# Video Propagation Networks
#----------------------------------------------------------------------------
# Copyright 2017 Max Planck Society
# ... |
import argparse
import PIL.Image as pil_image
import numpy as np
from utils import AverageMeter, calc_psnr, calc_ssim, convert_rgb_to_y, denormalize,calc_psnr_for_eachimg,calc_ssim_for_eachimg
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--lr_image_file', type... |
import warnings
from typing import Any, Callable, Dict, List, Optional, Union
from cognite.client import utils
from cognite.client._api.assets import AssetsAPI
from cognite.client._api.data_sets import DataSetsAPI
from cognite.client._api.datapoints import DatapointsAPI
from cognite.client._api.entity_matching import ... |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
import logging
import time
# 专注于 IO多路复用 可以实现一个可并发的服务器
import select
# 用于类的序列化和反序列化
import json
from master import *
import server_pool
from master2 import *
import socket
class EventLoop(object):
def __init__(self):
self._stopping = False
# 创建一个sock... |
"""Timers Tests"""
from datetime import datetime, timedelta
from itertools import starmap
from operator import sub
from time import time
import pytest
from circuits import Component, Event, Timer, sleep
from circuits.six.moves import map, zip
@pytest.fixture
def app(request, manager, watcher):
app = App().reg... |
from django.apps import AppConfig
class Lab1Config(AppConfig):
name = 'lab1'
|
#######################################################################
# Name: test_semantic_action_results
# Purpose: Tests semantic action results passed to first_pass call
# Author: Igor R. Dejanović <igor DOT dejanovic AT gmail DOT com>
# Copyright: (c) 2014 Igor R. Dejanović <igor DOT dejanovic AT gmail DOT com>
... |
from pathlib import Path
from unittest.mock import MagicMock
from unittest.mock import patch
import pytest
from zelt.kubernetes import deployer
from zelt.kubernetes.manifest import Manifest
from zelt.kubernetes.manifest_set import ManifestSet
from zelt.kubernetes.storage.configmap import ConfigmapStorage
@pytest.fi... |
from DB_Tables.Comments_Table import Comment_Table
from DB_Tables.InlineComment_Table import InlineComment_Table
from DB_Tables.PatchDetail_Table import PatchDetail_Table
from DB_Tables.Patch_Table import Patch_Table
from DB_Tables.People_Table import People_Table
from DB_Tables.RequestDetail_Table import RequestD... |
# flake8: noqa F401
from wagtailregulations.models.django import (
EffectiveVersion,
Part,
Section,
Subpart,
sortable_label,
)
from wagtailregulations.models.pages import RegulationPage, RegulationPageMixin
|
# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from django.conf.urls import url
from . import views
urlpatterns = [
url(
regex=r'^$',
view=views.chat,
name='chatRoom'
),
url(r'^new/$', views.new_room, name='new_room'),
url(r'^(?P<label>[\w-]{,5... |
__author__ = """Romain Picard"""
__email__ = 'romain.picard@oakbits.com'
__version__ = '0.1.0'
from .types import NamedObservable, Update, Updated
from . import pullable
|
from __future__ import absolute_import
# flake8: noqa
# import apis into api package
from swagger_client.api.aliens_api_api import AliensApiApi
from swagger_client.api.games_api_api import GamesApiApi
from swagger_client.api.logs_api_api import LogsApiApi
from swagger_client.api.scoreboard_api_api import ScoreboardAp... |
import uuid
from django.conf import settings
from django.test import TestCase
from mock import patch
from sqlalchemy import create_engine
from sqlalchemy.exc import ProgrammingError
from corehq.apps.userreports.models import DataSourceConfiguration, ReportConfiguration
from corehq.apps.userreports.pillow import Configu... |
"""
Model class for Message.
Refer: https://developers.facebook.com/docs/graph-api/reference/message
"""
from dataclasses import dataclass
from typing import List, Optional
from dataclasses_json import config
from pyfacebook.models.base import BaseModel, field
@dataclass
class Tag(BaseModel):
"""
... |
# -*- mode: python; coding: utf-8 -*-
# Copyright 2017 Peter Williams and collaborators.
# Licensed under the MIT License.
"""Various properties of plasma oscillations.
Most equation references are to Stix (1992), "Waves in Plasmas".
"""
from __future__ import absolute_import, division, print_function
__all__ = '''... |
from smtplib import SMTPException
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.core.validators import MinLengthValidator
from django.core.mail.message import EmailMultiAlternatives
from django.conf import settings
from django.template.loader import render_to_string
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.