text stringlengths 2 999k |
|---|
import unittest
import numpy as np
from demohamiltonian import *
class TestHamGen(unittest.TestCase):
# Test if output has right dimensions
def testDim(self):
N = 2
v,w = Hamiltonian(N,1,1,1,1)
a = np.shape(v)
b = np.shape(w)
self.assertEqual(a,(N,))
... |
import codecs
import os
def get_default_rendering_file_content(file_name="render.html"):
"""
Simply returns the content render.html
"""
with codecs.open(file_name, "r", "utf-8") as f:
return f.read()
def get_fixture_content(file_name):
fixture_file = os.path.join("fixtures", file_name)
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# (c) Kunal Diwan
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
... |
# Copyright 2016 Cloudbase Solutions.
# 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 requ... |
from typing import List, Optional
from blspy import AugSchemeMPL, PrivateKey, G1Element
from taco.util.ints import uint32
# EIP 2334 bls key derivation
# https://eips.ethereum.org/EIPS/eip-2334
# 12381 = bls spec number
# 8444 = Taco blockchain number and port number
# 0, 1, 2, 3, 4, 5, 6 farmer, pool, wallet, local... |
# Copyright 2022 Quantapix 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 applicable l... |
test = {
"name": "q2",
"points": 1,
"hidden": True,
"suites": [
{
"cases": [
{
"code": r"""
>>> import hashlib
>>> hashlib.sha256(bytes(str(round(prob_negative, 4)), "utf-8")).hexdigest()
'22fa3ce4995af8d96fcd771f0e1f5d74d8a98f36c3eec8e95bdf7524926b0141'
""",
"hidden": False... |
# DRUNKWATER TEMPLATE(add description and prototypes)
# Question Title and Description on leetcode.com
# Function Declaration and Function Prototypes on leetcode.com
#290. Word Pattern
#Given a pattern and a string str, find if str follows the same pattern.
#Here follow means a full match, such that there is a bijectio... |
# -*- coding: utf-8 -*-
# Universidade Federal de Goias
# Instituto de Informática - INF
# Compiladores - Compilador para MGol
#
# Módulo: Tabela de Transições
# Este módulo preenche a tabela de transições do
# autômato finito determinístico da linguagem,
# implementado através de uma lista de dicionários.
#
# Alunos:... |
# Do not edit this file directly.
# It was auto-generated by: code/programs/reflexivity/reflexive_refresh
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
def sfml():
http_archive(
name="sfml" ,
build_file="//bazel/deps/sfml:build.BUILD" ,
sha256="6b013624aa9a916da2d37... |
# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: configuration.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protob... |
"""
Write a function `rock_paper_scissors` to generate all of the possible plays that can be made in a game of "Rock Paper Scissors", given some input `n`, which represents the number of plays per round.
For example, given n = 2, your function should output the following:
[['rock', 'rock'], ['rock', 'paper'], ['rock... |
import collections
from rtamt.operation.abstract_operation import AbstractOperation
class OnceBoundedOperation(AbstractOperation):
def __init__(self, begin, end):
self.begin = begin
self.end = end
self.buffer = collections.deque(maxlen=(self.end + 1))
for i in range(self.end + 1):
... |
"""
WSGI config for s10day12bbs project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.8/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_S... |
################################################################################
## Form generated from reading UI file 'FlowchartCtrlTemplate.ui'
##
## Created by: Qt User Interface Compiler version 6.1.0
##
## WARNING! All changes made in this file will be lost when recompiling UI file!
#############################... |
from aioify import aioify
from discord.ext import commands, tasks
import aiohttp
import aiosqlite
import asyncio
import discord
import json
import os
import shutil
class Events(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.os = aioify(os, name='os')
self.shutil = aioify(shuti... |
"""
WSGI config for mozblog project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.11/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
from whitenoise.django import Django... |
from tkinter import *
tab = Tk()
tab.title("Special Midterm Exam in OOP")
tab.geometry("700x500+20+10")
def magic():
btn.configure(bg="yellow")
btn = Button(tab, text="Click to Change Color", command=magic)
btn.place(x=350, y=250, anchor="center")
tab.mainloop() |
# -*- coding: utf-8 -*-
# This file is part of beets.
# Copyright 2016, Adrian Sampson.
#
# 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 t... |
# -*- coding: utf-8 -*-
from django.core.urlresolvers import reverse
from django.db import models
from easy_thumbnails.fields import ThumbnailerImageField
from ..core.models import TimeStampedModel
class Medicos(TimeStampedModel):
"""
Medicos de la institucion
"""
nombre = models.CharField(max_length=... |
from spacy.lang.en import English
from spacy.lang.de import German
from torchtext.datasets import IWSLT2017
from torchtext.vocab import build_vocab_from_iterator
# Define special symbols and indices
PAD_IDX, UNK_IDX, BOS_IDX, EOS_IDX = 0, 1, 2, 3
# Make sure the tokens are in order of their indices to properly insert... |
# -*- coding: utf-8 -*-
# Copyright (c) 2014-18 Richard Hull and contributors
# See LICENSE.rst for details.
"""
Collection of serial interfaces to OLED devices.
"""
# Example usage:
#
# from luma.core.interface.serial import i2c, spi
# from luma.core.render import canvas
# from luma.oled.device import ssd1306,... |
# AutoEncoders
# Importing the libraries
import numpy as np
import pandas as pd
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.optim as optim
import torch.utils.data
from torch.autograd import Variable
# Importing the dataset
movies = pd.read_csv('ml-1m/movies.dat', sep = '::', header = None... |
#Imports
import base64
import algosdk
from algosdk.v2client import algod
from algosdk import account, mnemonic
from algosdk.future.transaction import write_to_file
from algosdk.future.transaction import AssetConfigTxn, AssetTransferTxn
from algosdk.future.transaction import PaymentTxn
# Connection
algod_address = "htt... |
# Generated by Django 4.0 on 2022-01-03 22:14
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('misc', '0002_alter_stateregion_options_alter_timezone_options'),
('observe', '0013_rename_time_zone_observinglocation_... |
#!/usr/bin/python
#
# Test cases for AP VLAN
# Copyright (c) 2013-2014, Jouni Malinen <j@w1.fi>
#
# This software may be distributed under the terms of the BSD license.
# See README for more details.
import time
import subprocess
import logging
logger = logging.getLogger(__name__)
try:
import netifaces
netifa... |
import hashlib
import itertools
import logging
import random
import re
import os
import datetime
from itertools import count, islice
from datetime import timedelta
import bleach
from taggit.models import Tag
from django import template, forms
from django.conf import settings
from django.contrib.auth import get_user_m... |
from rest_framework import permissions
from rest_framework.decorators import (
api_view,
authentication_classes,
permission_classes,
)
from rest_framework.response import Response
from .models import Ingredients
@api_view(["GET", "HEAD"])
@permission_classes([permissions.AllowAny])
@authentication_classes(... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Copyright 2021 Alibaba Group Holding Limited. 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... |
import json
import matplotlib.pyplot as plt
from collections import defaultdict
def main():
# genres = defaultdict(int)
language = defaultdict(int)
# rating = defaultdict(int)
# runtime = []
# tokens = []
# imdb = []
# tmdb = []
# meta = []
for movie in json.load(open("movies.json... |
# ABC015d
import sys
input = sys.stdin.readline
sys.setrecursionlimit(10**6)
W = int(input())
N, K = map(int, input().split())
a = [list(map(int, input().split())) for _ in range(N)]
dp = [[[0]*(W+1) for i in range(K+1)] for _ in range(N+1)]
for i in range(1, N+1):
for j in range(1, K + 1):
for k in ran... |
"""
class Conta: # Classe
def __init__(self): # Método __init__
self.objeto = objeto # atributos
def funcao(): # Método
"""
import datetime
class Historico:
def __init__(self) -> None:
self.data_abertura = datetime.datetime.today()
self.transacoes = []
de... |
[ ## this file was manually modified by jt
{
'functor' : {
'arity' : '1',
'call_types' : [],
'ret_arity' : '0',
'rturn' : {
'default' : 'T',
},
'simd_types' : [],
'special' : ['crlibm'],
'type_defs' : [],
'types' :... |
import pandas as pd
from pandas.tseries.holiday import USFederalHolidayCalendar as calendar
from pandas.tseries.offsets import CustomBusinessDay
import numpy as np
import datetime
def make_baseline(x_days, pivot, name="Temperature", freq="15min"):
baseline=pivot[pivot.index.isin(x_days)].mean(axis=0)
baseline_... |
from model.group import Group
testdata = [
Group(name="name1", header='header1', footer='footer1'),
Group(name="name2", header='header2', footer='footer2')
]
|
# Generated by Selenium IDE
import pytest
import time
import json
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.support import expected_conditions
from selenium.webdriver.support.wait import WebDriverWa... |
"""Core app"""
from django.apps import AppConfig
class CoreConfig(AppConfig):
"""Core app config"""
name = 'raccoons.core'
verbose_name = 'Core'
|
import lib.commandable_state_machine as cmd_state_machine
import lib.state_machine as state_machine
class PausedState(cmd_state_machine.CommandableStateMachine):
def __init__(self):
super().__init__()
self.state_machine: state_machine.StateMachine
def enter(self, parent_state: 'state_machine... |
# coding: utf-8
#-------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#----------------------------------------------------------------------... |
# external files
import numpy as np
import pickle as pk
import torch.optim as optim
from datetime import datetime
import os, time, argparse, csv
from collections import Counter
import torch.nn.functional as F
from sklearn.model_selection import train_test_split
from torch.optim.lr_scheduler import CosineAnnealingLR
fro... |
from flask import url_for
def test_usergroups(client, access_token):
token = access_token
res = client.get(url_for('usergroups'), headers={'authorization': "Bearer {token}".format(token=token)})
assert res.status_code == 200
assert len(res.json) > 0
assert res.json[0]['id'] == 1
assert res.jso... |
import re
from .. import Environ as ENV
from ..Interfaces import Downloadable, Fileable
from ..Models import normal, yId
from pprint import pprint
################################################################################
################################################################################
##... |
import json
from django.test import TestCase
from rest_framework.test import APITestCase
from rest_framework.reverse import reverse
from .views import BookViewset, ExternalBookView
from .models import Book, Author
class ExternalBookViewTest(TestCase):
def test_get_without_data(self):
"""
Test UR... |
import json
from hellpy.utils import valid_type
from hellpy.structures import BaseType
from hellpy.exceptions import InvalidTypeError
class Builder(object):
pass
class UrlBuilder(Builder):
def __init__(self, base_url: str) -> None:
self.query_url = f'{base_url}/query'
self.status_url = f'{b... |
"""
Tools for drawing Python object reference graphs with graphviz.
You can find documentation online at http://mg.pov.lt/objgraph/
Copyright (c) 2008-2010 Marius Gedminas <marius@pov.lt>
Copyright (c) 2010 Stefano Rivera <stefano@rivera.za.net>
Released under the MIT licence.
"""
# Permission is hereby granted, fre... |
# -*- coding: utf-8 -*-
# Copyright 2016 Open Permissions Platform Coalition
# 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 appl... |
#!/usr/bin/env python
"""ur1.py -- command-line ur1.ca client.
ur1.ca is the URL shortening services provided by status.net. This script
makes it possible to access the service from the command line. This is done
by scraping the returned page and look for the shortened URL.
USAGE:
ur1.py LONGURL
RETURN STATUS:
... |
# ------------------------------------------------------------------------------
# Copyright (c) Microsoft
# Licensed under the MIT License.
# Written by Bin Xiao (Bin.Xiao@microsoft.com)
# ------------------------------------------------------------------------------
from __future__ import absolute_import
from __fut... |
import numpy as np
from copy import copy
class StandardScaler:
def __init__(self):
self.mean = None
self.var = None
"""
Standardize features by centering the mean to 0 and unit variance.
The standard score of an instance is calculated by:
z = (x - u) / s
where u is the mean... |
from typing import Tuple
import torchvision
from torch import nn
import backbone.base
class ResNet50(backbone.base.Base):
def __init__(self, pretrained: bool):
super().__init__(pretrained)
def features(self) -> Tuple[nn.Module, nn.Module, int, int]:
# 这里调用的是Resnet50
resnet50 = torc... |
# Copyright 2020-present NAVER Corp. Under BSD 3-clause license
from .matching import *
|
import sys
assert sys.version_info.major >= 3
sys.path.insert(0, '/home/flaskwsgi/public_wsgi/')
from app import app as application |
"""
minus
=====
"""
from ansys.dpf.core.dpf_operator import Operator
from ansys.dpf.core.inputs import Input, _Inputs
from ansys.dpf.core.outputs import Output, _Outputs, _modify_output_spec_with_one_type
from ansys.dpf.core.operators.specification import PinSpecification, Specification
"""Operators from Ans.Dpf.Nativ... |
#!/usr/bin/env python3
# Copyright (c) 2015-2017 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test multiple RPC users."""
from test_framework.test_framework import BitcoinTestFramework
from test_f... |
# Copyright 2022 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
__all__ = ["overturn", "shearstrain", "nsq"]
__version__ = "0.1.0"
from . import nsq, overturn, shearstrain
|
# -*- coding: utf-8 -*-
# Natural Language Toolkit: Probability and Statistics
#
# Copyright (C) 2001-2012 NLTK Project
# Author: Edward Loper <edloper@gradient.cis.upenn.edu>
# Steven Bird <sb@csse.unimelb.edu.au> (additions)
# Trevor Cohn <tacohn@cs.mu.oz.au> (additions)
# Peter Ljunglöf <pete... |
# -*- coding: utf-8 -*-
#
# Configuration file for the Sphinx documentation builder.
#
# This file does only contain a selection of the most common options. For a
# full list see the documentation:
# http://www.sphinx-doc.org/en/master/config
# -- Path setup ------------------------------------------------------------... |
import json
import os
from utils.args_utils import get_directory_or_cwd
from utils.constants import zpspec_file_name
def init_command(args):
name = args.name
version = args.version
zpspec_json_dict = {
'packageName': name,
'version': version
}
directory = get_directory_or_cwd(ar... |
# Helper for the mirror on GAE
# GAE GETs an action gae_file, giving GAE host and a secret
# PyPI GETs /mkupload/secret, learning path and upload session
# PyPI POSTs to upload session
import urllib2, httplib, threading, os, binascii, urlparse
POST="""\
--%(boundary)s
Content-Disposition: form-data; name="secret"
%(s... |
from unittest import TestCase
import nisyscfg.system
import nisyscfg.hardware_resource
from click.testing import CliRunner
from nisyscfgcli import nisyscfgcli
from unittest.mock import patch
class Mock_NI_Hardware_Item:
def __init__(self, expert_user_alias, product_name):
self.expert_user_alias = expert_u... |
# vim: encoding=utf-8
""" Localization table
"""
LITS = {
# pylint: disable=line-too-long
'en': ["New Moon", "First Quarter", "Full Moon", "Last Quarter", "Northern Hemisphere", "Southern Hemisphere"],
'be': ["Маладзік", "Першая чвэрць", "Поўня", "Апошняя чвэрць", "Паўночнае паўшар’е", "Паўднёвае паўшар’е"... |
"""Solution to Project Euler Problem 5
https://projecteuler.net/problem=5
gcd, lcm, and lcmm functions by J.F. Sebastian.
http://stackoverflow.com/a/147539/6119465
"""
from functools import reduce
MAXIMUM = 20
def gcd(num1, num2):
"""Return greatest common divisor using Euclid's Algorithm."""
while num2:
... |
# coding: utf-8
#
# Copyright 2018 The Oppia 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 requi... |
# coding: utf-8
# @时间 : 2022/1/18 8:42 上午
# @作者 : 文山
# @邮箱 : wolaizhinidexin@163.com
# @作用 :
# @文件 : predict.py
# @微信 :qwentest123
import numpy as np
import pandas as pd
from tensorflow.keras.layers import Dense, Flatten, Conv2D, AvgPool2D, MaxPool2D
from tensorflow.keras import Model
import json
from PIL ... |
# -*- coding: utf-8 -*-
from benedict import benedict
import time
import unittest
class github_issue_0039_test_case(unittest.TestCase):
"""
https://github.com/fabiocaccamo/python-benedict/issues/39
To run this specific test:
- Run python -m unittest tests.github.test_issue_0039
"""
def te... |
#
# The Python Imaging Library
# $Id$
#
# Adobe PSD 2.5/3.0 file handling
#
# History:
# 1995-09-01 fl Created
# 1997-01-03 fl Read most PSD images
# 1997-01-18 fl Fixed P and CMYK support
# 2001-10-21 fl Added seek/tell support (for layers)
#
# Copyright (c) 1997-2001 by Secret Labs AB.
# Copyright (c) 1995-20... |
"""Bokeh loopitplot."""
import numpy as np
from bokeh.models import BoxAnnotation
from matplotlib.colors import hsv_to_rgb, rgb_to_hsv, to_hex, to_rgb
from xarray import DataArray
from ....stats.density_utils import kde
from ...plot_utils import _scale_fig_size
from .. import show_layout
from . import backend_kwarg_de... |
from .patient import CreatePatient
from .pathway import CreatePathway
from .decision_point import CreateDecisionPoint
from .user import CreateUser
from .milestone import ImportMilestone
from .role import create_role
|
from diskimgcreator import try_create_image, _parse_size, _set_verbose
from diskimgmounter import try_mount_image
import unittest
import os
import datetime
_set_verbose(True)
class TestParseSize(unittest.TestCase):
def test_parse_size(self):
self.assertEqual(_parse_size("5.5"), 5.5 * 1000 ** 2)
s... |
import typing
from authlib.oauth2.rfc6749 import OAuth2Error
from .authorization_server import AuthorizationServer, RevocationEndpoint
from .resource_protector import ResourceProtector, resource_protected
from .grants import AuthorizationCodeGrant, RefreshTokenGrant
if typing.TYPE_CHECKING:
from aiohttp.web impo... |
#! /usr/bin/python3
import os
import re
import subprocess
# Run checkpatch for the lint-all tool; output:
#
# stdout: lines in the form FILE:LINENUMBER:message
# return: NUMBER-OF-ERRORS, WARNINGS, BLOCKAGES
regex_c = re.compile(r".*\.(c|C|cpp|CPP|h|HH|hxx|cxx)$")
lint_checkpatch_name = "checkpatch"
def lint_checkp... |
from bisect import bisect_left
from functools import lru_cache, reduce
from typing import List, Dict, Set, Tuple, Any, Optional, Union # mypy type checking
from .data import Attribute, Race
from .unit_command import UnitCommand
from .ids.unit_typeid import UnitTypeId
from .ids.ability_id import AbilityId
from .const... |
# Copyright 2018 Microsoft 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 in... |
# -*- coding:utf-8 -*-
import os
from simpleutil.config import cfg
from simpleutil.log import log as logging
from simpleutil.utils import systemutils
from simpleutil.utils.zlibutils.excluder import Excluder
from simpleflow.api import load
from simpleflow.storage import Connection
from simpleflow.storage.middleware imp... |
"""Shared test code for RAOP test cases."""
import asyncio
from typing import cast
import pytest
from pyatv import connect
from pyatv.conf import AppleTV, ManualService
from pyatv.const import Protocol
from tests.fake_device import FakeAppleTV, raop
from tests.fake_device.raop import FakeRaopUseCases
@pytest.fixtu... |
from django.db import models
from polymorphic.base import PolymorphicModelBase
from polymorphic.models import PolymorphicModel
from .handlers import RouteViewHandler
from .managers import RouteManager
from .utils import import_from_dotted_path
from .validators import (
validate_end_in_slash,
validate_no_dotty_... |
import argparse
import os
import sltxpkg.util as su
from sltxpkg.command_config import Arg, Commands
from sltxpkg.commands import (cmd_analyze_logfile, cmd_auto_setup, cmd_cleanse,
cmd_compile, cmd_dependency, cmd_docker,
cmd_gen_gha, cmd_raw_compile, cmd_ver... |
"""Tests for the 'ihate' plugin"""
from _common import unittest
from beets import importer
from beets.library import Item
from beetsplug.ihate import IHatePlugin
class IHatePluginTest(unittest.TestCase):
def test_hate(self):
match_pattern = {}
test_item = Item(
genre='TestGenre',
... |
#
# Base solver class
#
import casadi
import copy
import pybamm
import numbers
import numpy as np
import sys
import itertools
import multiprocessing as mp
import warnings
class BaseSolver(object):
"""Solve a discretised model.
Parameters
----------
method : str, optional
The method to use for... |
#!/usr/bin/env python
# This file is part of the OpenMV project.
# Copyright (c) 2013/2014 Ibrahim Abdelkader <i.abdalkader@gmail.com>
# This work is licensed under the MIT license, see the file LICENSE for
# details.
"""This module implements enough functionality to program the STM32F4xx over
DFU, without requiring d... |
from django.shortcuts import render
import requests
import json
from django.http import JsonResponse, HttpResponse, Http404
import json
from django.views.decorators.csrf import csrf_exempt
import json
import time
import logging
from .mist_smtp.mist_smtp import Mist_SMTP
from .lib.__req import Req
from .lib.psks import... |
import copy
import math
import os
import pickle as pkl
import sys
import time
import numpy as np
import dmc2gym
import hydra
import torch
import torch.nn as nn
import torch.nn.functional as F
import utils
from logger import Logger
from replay_buffer import ReplayBuffer
from video import VideoRecorder
torch.backends.... |
#!/usr/bin/env python
# coding: utf-8
# import necessary libraries
import os
import sys
import unittest
#allow the script to be run directly
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
#import function to test
from youtube_dl.utils import formatSeconds
#Unit test designed to test t... |
import files.prime as prime
p = prime.all_primes(1000)
|
# Copyright 2015 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 the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... |
from Blackjack.src.deck import Deck
import unittest
class TestDeck(unittest.TestCase):
def setUp(self):
self.deck = Deck()
def test_loop_draw(self):
for _ in range(100):
self.deck.draw_card()
|
# Copyright 2018 New Vector 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 in writin... |
#!/usr/bin/env python
"""
Copyright (c) 2006-2019 sqlmap developers (http://sqlmap.org/)
See the file 'LICENSE' for copying permission
"""
import codecs
import doctest
import os
import re
import shutil
import sys
import tempfile
import time
import traceback
from extra.beep.beep import beep
from lib.controller.contro... |
#!/usr/bin/env python
#-*- coding: utf8 -*-
from pygame.locals import *
import pygame
import sys
class EventManager (object):
def __init__(self):
self._stopped = False
self._toggle_full_screen = False
def get_events(self):
ret = []
self._stopped = False
self._toggle_... |
from numpy import genfromtxt
import matplotlib.pyplot as plt
import mpl_finance
import numpy as np
import uuid
import matplotlib
# Input your csv file here with historical data
ad = genfromtxt(f"../financial_data/MEG.csv", delimiter=",", dtype=str)
ad = ad[1500:]
def convolve_sma(array, period):
return np.convo... |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Tue Feb 21 20:05:06 2017
@author: pd
"""
from IPython import get_ipython
get_ipython().magic('reset -sf')
from sklearn import datasets
import numpy as np
from sklearn.datasets import make_classification
from sklearn.linear_model import LogisticRegressio... |
from django.db import models
# Create your models here.
class Post(models.Model):
title = models.CharField(max_length=30)
content = models.TextField()
updated = models.DateTimeField(auto_now=True, auto_now_add=False)
timestamp = models.DateTimeField(auto_now=False, auto_now_add=True)
def __str... |
import matplotlib.pyplot as plt
x = [2, 6, 9, 1]
y = [8, 3, 7, 1]
plt.plot(x,y)
plt.title('line')
plt.xlabel('x')
plt.ylabel('y')
plt.grid(axis='both')
plt.show() |
import json
import os
import pickle
import re
import shutil
from pathlib import Path
def read_file(filepath, encoding="utf-8"):
"""Read text from a file."""
try:
with open(filepath, encoding=encoding) as f:
return f.read()
except FileNotFoundError as e:
raise ValueError(f"File ... |
from creator.cli import cli
__all__ = ['cli']
|
# coding: utf-8
# Copyright (c) 2016, 2022, Oracle and/or its affiliates. All rights reserved.
# This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may c... |
# Copyright 2010 OpenStack LLC.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required b... |
def partition(arr,beg,end):
i = beg-1
pivot = arr[end]
for j in range(beg,end):
if arr[j]>pivot:
i+=1
arr[i],arr[j]=arr[j],arr[i]
arr[i+1],arr[end]=arr[end],arr[i+1]
return i+1
def quicksort(arr,beg,end):
if len(arr)==1:
return arr
if beg<end:
... |
"""
Variáveis de mensagens em português brasileiro.
"""
import discord
# Variáveis
teste = "teste - Locales - PT_BR"
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.