content stringlengths 0 894k | type stringclasses 2
values |
|---|---|
from .duration import Duration
from .numeric import Numeric
from .rate import Rate
from .size import Size
| python |
import clr
clr.AddReference('RevitAPI')
from Autodesk.Revit.DB import *
fams = UnwrapElement(IN[0])
ptypes = list()
for fam in fams:
if fam.GetType().ToString() == "Autodesk.Revit.DB.Family":
ptypes.append(fam.FamilyPlacementType)
else: ptypes.append(None)
OUT = ptypes | python |
from sys import stdin, stdout
from operator import itemgetter
cases = int(stdin.readline())
for c in range(cases):
text = stdin.readline().strip().lower()
text = [ch for ch in text if ch.isalpha()]
freq = {}
max_f = 0
for ch in text:
if not ch in freq:
freq[ch] = 1
else:
freq[ch] += 1
... | python |
from temboo.Library.LinkedIn.PeopleAndConnections.GetMemberProfile import GetMemberProfile, GetMemberProfileInputSet, GetMemberProfileResultSet, GetMemberProfileChoreographyExecution
| python |
import time
import asyncio
import concurrent.futures
from functools import partial
def a():
time.sleep(1)
return 'A'
async def b():
await asyncio.sleep(1)
return 'B'
async def c():
loop = asyncio.get_running_loop()
return await loop.run_in_executor(None, a)
def show_perf(func):
print... | python |
import logging
def _cancel_pending_orders(client, orders):
pending = [(order['variety'], order['order_id'])
for order in orders if 'OPEN' in order['status']]
# ToDo: if doesn't work in time, try to run it async.
for p in pending:
try:
order_id = client.cancel_order(*p)
... | python |
import appdaemon.plugins.hass.hassapi as hass
import os
import glob
import random
#
# A helper app providing random template selection and rendering.
#
# This app could be used by Smart Assistants to provide some "randomness" in the assistant words.
#
# noinspection PyAttributeOutsideInit
class AssistantTemplate(h... | python |
#!/usr/bin/env python
################################################################
#
# osm.py - Obsidian Settings Manager
# Copyright 2021 Peter Kaminski. Licensed under MIT License.
# https://github.com/peterkaminski/obsidian-settings-manager
#
################################################################
VER... | python |
import os
import argparse
from misc import date_str, get_dir
def model_args():
parser = argparse.ArgumentParser()
# Paths
parser.add_argument('--train_dir',
help='Directory of train data',
default='./data/poetryDB/txt/')
# parser.add_argument('--test_di... | python |
# Copyright 2020 Mark Dickinson. 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law... | python |
import logging
import os
import sys
import pandas as pd
import re
from collections import OrderedDict
import numpy as np
import argparse
import zipfile
import paramiko
import time
from sqlalchemy.exc import IntegrityError
from dataactcore.models.domainModels import DUNS
from dataactcore.interfaces.db import GlobalDB
f... | python |
import os , csv
# relative path to find the csv file
os.chdir(os.path.abspath(os.path.dirname(__file__)))
path = os.getcwd()
my_path = os.path.join('.', 'Resources', 'budget_data.csv')
#defining our variables
totalMonths = 0
total = 0
averageChange = 0
greatestIncrease = 0
greatestDecrease = 0
#extra variables used ... | python |
import numpy as np
ip_list=[int(x) for x in input().split()]
ip_list=np.asfarray(ip_list)
def listmul(ip_list):
op_list=[]
for i in range(0,len(ip_list)):
temp=1
for j in range(0,len(ip_list)):
if i!=j:
temp=temp*ip_list[j]
op_list.append(temp)
return op_list
op_list = listmul(ip_list)
print(op_list) | python |
from time import time
from typing import Any
from flask import render_template
def login_render(auth_url: str) -> Any:
"""Return login page.
Arguments:
auth_url {str} -- Link to last.fm authorization page.
"""
return render_template("login.html", auth_url=auth_url, timestamp=time... | python |
# -*- coding: utf-8 -*-
"""
Created on Tue Apr 7 18:10:42 2020
Small module to allow multiprocessing of the point in polygon problem
@author: Matthew Varnam - The University of Manchester
@email: matthew.varnam(-at-)manchester.ac.uk
"""
#Import numpy for mathematical calculations
import numpy as np
#I... | python |
import sys, os
import librosa
import torch
import numpy as np
from typing import Union, Tuple, List
from collections import defaultdict
import configparser
config = configparser.ConfigParser(allow_no_value=True)
config.read("config.ini")
from vectorizer.model import Model
from vectorizer.utils import chunk_data
from ... | python |
#!/usr/bin/env python3
import re
import pysam
from .most_common import most_common
from .sequence_properties import repeat
cigar_ptn = re.compile(r"[0-9]+[MIDNSHPX=]")
def realn_softclips(
reads, pos, ins_or_del, idl_seq, idl_flanks, decompose_non_indel_read
):
template = make_indel_template(idl_seq, idl_fl... | python |
"""Config namespace."""
from flask_restx import Namespace, Resource, fields # type: ignore
from jsonschema import ValidationError # type: ignore
from configmodel.logic.config import (
create_config,
delete_config,
get_config,
get_configs,
validate_config,
)
api = Namespace("config", descripti... | python |
# coding: utf-8
# In[1]:
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
# In[2]:
# 载入数据集
mnist = input_data.read_data_sets('./../../datas/mnist/', one_hot=True)
# 输入图片是28*28
n_inputs = 28 # 输入一行,一行有28个数据
max_time = 28 # 一共28行
lstm_size = 100 # 隐层单元
n_classes = 10 # 10个分类
bat... | python |
from framework.types import RequestT
from framework.types import ResponseT
from framework.utils import build_status
from framework.utils import read_static
def handle_image(_request: RequestT) -> ResponseT:
payload = read_static("image.jpg")
status = build_status(200)
headers = {"Content-type": "image/jpe... | python |
import pandas as pd
import googlemaps
import json
from shapely.geometry import shape, Point
with open('static/GEOJSON/USCounties_final.geojson') as f:
geojson1 = json.load(f)
county = geojson1["features"]
with open('static/GEOJSON/ID2.geojson') as f:
geojson = json.load(f)
district = geojson["features"]
pr... | python |
# coding=utf-8
# Copyright 2020 The Google Research Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicab... | python |
import sqlite3
from .utility import exception_info, enquote2
class SQLighter:
def __init__(self, db):
self.connection = sqlite3.connect(db)
self.cursor = self.connection.cursor()
def db_query(self, query, args=None):
with self.connection:
if args is None or args == ():
... | python |
from selfdrive.car import limit_steer_rate
from selfdrive.car.hyundai.hyundaican import create_lkas11, create_lkas12, \
create_1191, create_1156, \
learn_checksum, create_mdps12, create_clu11
from selfdrive.car.hyundai.values imp... | python |
##==========================================================
## 2016.02.09 vsTAAmbk 0.4.1
## Ported from TAAmbk 0.7.0 by Evalyn
## Email: pov@mahou-shoujo.moe
## Thanks (author)kewenyu for help
##==========================================================
## Requirements:
## EEDI2 ... | python |
#!/usr/bin/env python3
from setuptools import setup
setup(
name='asyncpgsa',
version=__import__('asyncpgsa').__version__,
install_requires=[
'asyncpg~=0.9.0',
'sqlalchemy',
],
packages=['asyncpgsa', 'asyncpgsa.testing'],
url='https://github.com/canopytax/asyncpgsa',
license=... | python |
import torch
import torch.nn as nn
class Ensemble(nn.Module):
"""
Ensemble decoding.
Decodes using multiple models simultaneously,
Note:
Do not use this class directly, use one of the sub classes.
"""
def __init__(self, models):
super(Ensemble, self).__init__()
self.mo... | python |
# -*- coding: utf-8 -*-
from gui.shared.tooltips.module import ModuleTooltipBlockConstructor
ModuleTooltipBlockConstructor.MAX_INSTALLED_LIST_LEN = 1000
print '[LOAD_MOD]: [mod_tooltipsCountItemsLimitExtend 1.00 (11-05-2018), by spoter, gox]'
| python |
from .utils import validator
@validator
def ipv4(value):
"""
Return whether or not given value is a valid IP version 4 address.
This validator is based on `WTForms IPAddress validator`_
.. _WTForms IPAddress validator:
https://github.com/wtforms/wtforms/blob/master/wtforms/validators.py
... | python |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""TC77: Serially accessible digital temperature sensor particularly suited for low cost and small form-factor applications."""
__author__ = "ChISL"
__copyright__ = "TBD"
__credits__ = ["Microchip"]
__license__ = "TBD"
__version__ = "0.1"
__maintainer__ = "h... | python |
file = open('Day 10 input.txt','r')
#file = open('Advent-of-Code-2021\\Day 10 testin.txt','r')
illegal = [0,0,0,0]
completescores = []
for line in file:
line = line.strip()
illegalflag = False
stack = []
for char in line:
if ((ord(char) == 40) or (ord(char) == 91) or (ord(char) == 123) or (o... | python |
import numpy as np
import pyautogui
def screenshot(bounds=None):
image = pyautogui.screenshot()
open_cv_image = np.array(image)
open_cv_image = open_cv_image[:, :, ::-1]
if bounds is not None:
x = bounds[0]
y = bounds[1]
open_cv_image = open_cv_image[x[0]:x[1], y[0]:y[1]]
r... | python |
from pathlib import PurePath
from typing import Dict, List
from lab import util
from lab.logger import internal
from .indicators import Indicator, Scalar
from .writers import Writer
class Store:
indicators: Dict[str, Indicator]
def __init__(self, logger: 'internal.LoggerInternal'):
self.values = {}
... | python |
#Verilen listenin içindeki elemanları tersine döndüren bir fonksiyon yazın.
# Eğer listenin içindeki elemanlar da liste içeriyorsa onların elemanlarını da tersine döndürün.
# Örnek olarak:
# input: [[1, 2], [3, 4], [5, 6, 7]]
# output: [[[7, 6, 5], [4, 3], [2, 1]]
liste = [[1, 2], [3, 4], [5, 6, 7]]
liste.reverse() ... | python |
import discord
from discord.ext import commands
from typing import Union
from CatLampPY import isGuild, hasPermissions, CommandErrorMsg # pylint: disable=import-error
class Moderation(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.bot.cmds.append(self.purge)
self.bot.cmds.app... | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Low-level feature detection including: Canny, corner Harris, Hough line,
Hough circle, good feature to track, etc.
"""
from __future__ import annotations
| python |
from dataclasses import dataclass
from typing import Optional
from pyhcl.core._repr import CType
from pyhcl.ir import low_ir
@dataclass(eq=False, init=False)
class INT(CType):
v: int
def __init__(self, v: int):
self.v = int(v)
@property
def orR(self):
return Bool(not not self.v)
c... | python |
"""
Main Methods are declared here
"""
from picocv._settings import Settings
from picocv.utils.train import Trainer
from picocv.utils.augment import DatasetAugmenter
def autoCorrect(model_func, dataset_func, settings : Settings):
"""
Performs Auto Correct Algorithm (Main Method)
:param model_func: Function... | python |
from .run import wait, load
__all__ = ['wait', 'load']
| python |
# Админка раздел редактор курсов
# Энпоинты меню редактора курсов ДШ в тек. уг
path_admin_schedules_grade_1 = '/schedules?grade=1&school=true&'
path_admin_schedules_grade_2 = '/schedules?grade=2&school=true&'
path_admin_schedules_grade_3 = '/schedules?grade=3&school=true&'
path_admin_schedules_grade_4 = '/schedules?gra... | python |
import os
import re
import sys
sys.path.append(os.path.dirname(__file__))
import nb_file_util as fu
class SymbolLister(fu.CellProcessorBase):
def calls_sympy_symbol(self):
"""
if symbol definition line included, return the line numbers and the contents in a list
:return: list of dict(... | python |
class ParserListener:
def update(self, phase, row):
""" Called when the parser has parsed a new record.
"""
pass
def handle(self, event, message, groups):
""" Called when the parser has parsed a registered event.
"""
pass
def registerKey(self, phase, key)... | python |
import math
import matplotlib.pyplot as plt
from .Generaldistribution import Distribution
class Binomial(Distribution):
""" Binomial distribution class for calculating and
visualizing a Binomial distribution.
Attributes:
mean (float) representing the mean value of the distribution
stdev (f... | python |
def f(x):
y = x
return f(y)
f(0)
| python |
import os
import sys
root_path = os.path.abspath("../../../")
if root_path not in sys.path:
sys.path.append(root_path)
import numpy as np
import tensorflow as tf
from _Dist.NeuralNetworks.DistBase import Base, AutoBase, AutoMeta, DistMixin, DistMeta
class LinearSVM(Base):
def __init__(self, *args, **kwargs... | python |
#!/usr/bin/python
#
# Copyright 2019 Fortinet 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 applicab... | python |
import sys
print("Congratulations on installing Python!", '\n')
print("This system is running {}".format(sys.version), '\n')
if "conda" in sys.version:
print("Hello from Anaconda!")
else:
print("Hello from system-installed Python!")
| python |
from collections import defaultdict
import re
from collections import Counter
print("Reactor Reboot")
with open("day22/day22_1_input.txt", "r") as f:
commands = [entry for entry in f.read().strip().split("\n")]
# print(commands)
cubeDict = defaultdict(bool)
for command in commands:
action, cubePositions = ... | python |
from .fp16_optimizer import FP16_Optimizer
from .fused_adam import FusedAdam
| python |
"""
An audio URL.
"""
def audio_url():
return 'https://vecsearch-bucket.s3.us-east-2.amazonaws.com/voices/common_voice_en_2.wav'
| python |
###############################################################
# Autogenerated module. Please don't modify. #
# Edit according file in protocol_generator/templates instead #
###############################################################
from typing import Dict
from ...structs.api.offset_fetch_reque... | python |
import gym
import pybullet as p
import pybullet_data
import os
import numpy as np
from gym import spaces
# Initial joint angles
RESET_VALUES = [
0.015339807878856412,
-1.2931458041875956,
1.0109710760673565,
-1.3537670644267164,
-0.07158577010132992,
.027]
# End-effector boundaries
BOUNDS_XMI... | python |
from discord import Embed
async def compose_embed(bot, msg, message):
names = {
"user_name": msg.author.display_name,
"user_icon": msg.author.avatar_url,
"channel_name": msg.channel.name,
"guild_name": msg.guild.name,
"guild_icon": msg.guild.icon_url
}
if msg.guild ... | python |
import time
import datetime
from haste_storage_client.core import HasteStorageClient, OS_SWIFT_STORAGE, TRASH
from haste_storage_client.interestingness_model import RestInterestingnessModel
haste_storage_client_config = {
'haste_metadata_server': {
# See: https://docs.mongodb.com/manual/reference/connecti... | python |
"""Checkmarx CxSAST source up-to-dateness collector."""
from dateutil.parser import parse
from collector_utilities.functions import days_ago
from collector_utilities.type import Value
from source_model import SourceResponses
from .base import CxSASTBase
class CxSASTSourceUpToDateness(CxSASTBase):
"""Collector ... | python |
#!/usr/bin/env python
import argparse
import re
import sys
# Prevent creation of compiled bytecode files
sys.dont_write_bytecode = True
from core.framework import cli
from core.utils.printer import Colors
# =================================================================================================... | python |
from copy import copy
def _rec(arr, n, m):
if n < 1:
return
yield from _rec(arr, n-1, m)
for i in range(1,m):
arr_loop = copy(arr)
arr_loop[n-1] = i
yield arr_loop
yield from _rec(arr_loop, n-1, m)
def main(n, m):
arr = [0]*n
yield arr
yield from _r... | python |
___assertEqual(0**17, 0)
___assertEqual(17**0, 1)
___assertEqual(0**0, 1)
___assertEqual(17**1, 17)
___assertEqual(2**10, 1024)
___assertEqual(2**-2, 0.25)
| python |
from libqtile.backend.x11 import core
def test_keys(display):
assert "a" in core.get_keys()
assert "shift" in core.get_modifiers()
def test_no_two_qtiles(manager):
try:
core.Core(manager.display).finalize()
except core.ExistingWMException:
pass
else:
raise Exception("expe... | python |
# Copyright (C) 2017-2019 New York University,
# University at Buffalo,
# Illinois Institute of Technology.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of th... | python |
#!/usr/bin/env python3
# author: https://blog.furas.pl
# date: 2020.07.08
#
import requests
import pandas as pd
url = "https://www.pokemondb.net/pokedex/all"
html = requests.get(url)
dfs = pd.read_html(html.text)
print( dfs )
| python |
#
# Autogenerated by Thrift Compiler (0.9.3)
#
# DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
#
# options string: py
#
from thrift.Thrift import TType, TMessageType, TException, TApplicationException
import logging
from ttypes import *
from thrift.Thrift import TProcessor
from thrift.transport imp... | python |
import random
from cocos.actions import Move, CallFunc, Delay
from cocos.layer import Layer, director
from cocos.sprite import Sprite
import cocos.collision_model as CollisionModel
from app import gVariables
from app.audioManager import SFX
class Enemy(Layer):
def __init__(self):
super(Enemy, self).__init... | python |
# SPDX-License-Identifier: Apache-2.0
"""
Tests pipeline within pipelines.
"""
from textwrap import dedent
import unittest
from io import StringIO
import numpy as np
import pandas
try:
from sklearn.compose import ColumnTransformer
except ImportError:
# not available in 0.19
ColumnTransformer = None
try:
... | python |
'''
Created on 09.10.2017
@author: Henrik Pilz
'''
from xml.sax import make_parser
from datamodel import Feature, FeatureSet, Mime, OrderDetails, Price, PriceDetails, Product, ProductDetails, Reference, TreatmentClass
from exporter.xml.bmecatExporter import BMEcatExporter
from importer.xml.bmecatImportHandle... | python |
#!/usr/bin/env python3
# Written by Daniel Oaks <daniel@danieloaks.net>
# Released under the ISC license
import unittest
from girc import formatting
class FormattingTestCase(unittest.TestCase):
"""Tests our formatting."""
def setUp(self):
errmsg = 'formatting.{} does not exist!'
self.assertT... | python |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# 2017 vby
############################ vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4
#---------------------------------------------------------------------------------------------------
import sys
import os, errno
import math
import collections
import subprocess
i... | python |
import pandas as pd
import numpy as np
from trav_lib.data_prep import reduce_memory
def test_reduce_memory():
df = pd.DataFrame({'ints':[1,2,3,4],'floats':[.1,.2,.3,.4],'strings':['a','b','c','d']})
df2 = reduce_memory(df)
assert df2['ints'].dtype == np.dtype('int8')
assert df2['floats'].dtype ... | python |
from plotly.graph_objs import Ohlc
| python |
'''
Created on May 28, 2015
@author: local
'''
import sys
import argparse
import logging
import subprocess
import os
import json
logging.getLogger("spectrumbrowser").disabled = True
def getProjectHome():
command = ['git', 'rev-parse', '--show-toplevel']
p = subprocess.Popen(command,
... | python |
import numpy as np
import pytest
from inspect import currentframe, getframeinfo
from pathlib import Path
from ..flarelc import FlareLightCurve
from ..lcio import from_K2SC_file
#example paths:
target1 = 'examples/hlsp_k2sc_k2_llc_210951703-c04_kepler_v2_lc.fits'
target2 = 'examples/hlsp_k2sc_k2_llc_211119999-c04_ke... | python |
# Copyright (c) Niall Asher 2022
from socialserver.util.test import (
test_db,
server_address,
create_post_with_request,
create_user_with_request,
create_user_session_with_request
)
from socialserver.constants import ErrorCodes
import requests
def test_get_unliked_post(test_db, server_address):
... | python |
import sys
import struct
""" Takes data from the Android IMU app and turns it into binary data.
Data comes in as csv, data points will be turned into the format:
Time Stamp Accelerometer Gyroscope
x y z x y z
=========================================
0 1 2 3 4 5 ... | python |
from Compiler.types import *
from Compiler.instructions import *
from Compiler.util import tuplify,untuplify
from Compiler import instructions,instructions_base,comparison,program
import inspect,math
import random
import collections
from Compiler.library import *
from Compiler.types_gc import *
from operator import i... | python |
from flask_app.factory import create_app
app = create_app('meeting-scheduler') | python |
#!/usr/bin/env python3
import numpy as np
class BPTTBatches(object):
"""Wraps a list of sequences as a contiguous batch iterator.
This will iterate over batches of contiguous subsequences of size
``seq_length``. TODO: elaborate
Example:
.. code-block:: python
# Dictionary
# Se... | python |
# A module to make your error messages less scary
import sys
from characters import AsciiCharacter
def output_ascii(err_message="You certainly messed something up."):
one_line = False
err_line_1 = err_message.split('--')[0]
try:
err_line_2 = err_message.split('--')[1]
except:
on... | python |
from keras.preprocessing.image import load_img, img_to_array
target_image_path = 'img/a.jpg'
style_image_path = 'img/a.png'
width, height = load_img(target_image_path).size
img_height = 400
img_width = int(width * img_height / height)
import numpy as np
from keras.applications import vgg19
def preproces... | python |
#!/usr/bin/python
# -*- coding: utf-8 -*-
class Demo(object):
__x = 0
def __init__(self, i):
self.__i = i
Demo.__x += 1
def __str__(self):
return str(self.__i)
def hello(self):
print("hello " + self.__str__())
@classmethod
def getX(cls):
return cls.__... | python |
import abc
from typing import Callable
from typing import Iterator
from typing import List
from typing import Optional
from xsdata.codegen.models import Class
from xsdata.models.config import GeneratorConfig
from xsdata.utils.constants import return_true
class ContainerInterface(metaclass=abc.ABCMeta):
"""Wrap a... | python |
#testing the concept
import re
#file_name = raw_input("Enter textfile name (ex. hamlet.txt): ")
def app(f_name):
fd = open(f_name, 'r')
fd = fd.read()
lines = fd.split('\n')
c1 = 0
while(c1 < len(lines)):
#lines[c1] = re.sub('[^0-9a-zA-Z]+', '', lines[c1])
if len(lines[c1]) == 0:
... | python |
import pytest
import os, time
import sys
from datetime import date, datetime
from pytest_html_reporter.template import html_template
from pytest_html_reporter.time_converter import time_converter
from os.path import isfile, join
import json
import glob
from collections import Counter
from PIL import Image
from io impor... | python |
import datetime
import logging
import time
import googleapiclient
class TaskList:
def __init__(self, id):
self.id = id
self.tasks = []
def update(self, service):
try:
results = service.tasks().list(tasklist = self.id, showCompleted = False, dueMax = rfc3339_today_midnight()).execute()
except... | python |
from datetime import *
from dateutil.relativedelta import *
now = datetime.now()
print(now)
now = now + relativedelta(months=1, weeks=1, hour=10)
print(now) | python |
FLASK_HOST = '0.0.0.0'
FLASK_PORT = 5000
FLASK_DEBUG = False
FLASK_THREADED = True
import os
ENV_SETUP = os.getenv('MONGO_DATABASE', None) is not None
MONGO_DATABASE = os.getenv('MONGO_DATABASE', 'avoid_kuvid')
MONGO_ROOT_USERNAME = os.getenv('MONGO_ROOT_USERNAME', 'admin')
MONGO_ROOT_PASSWORD = os.getenv('MONGO_ROOT_... | python |
# -*- coding: utf-8 -*-
# @Author: Marc-Antoine
# @Date: 2019-03-17 17:18:42
# @Last Modified by: Marc-Antoine Belanger
# @Last Modified time: 2019-03-17 17:20:31
from gym.envs.registration import register
register(
id='cribbage-v0',
entry_point='gym_cribbage.envs:CribbageEnv',
)
| python |
# coding:utf-8
# 2019/9/3
"""
给定一个整数的数组,找出其中的pair(a, b),使得a+b=0,并返回这样的pair数目。(a, b)和(b, a)是同一组。
输入
整数数组
输出
找到的pair数目
样例输入
-1, 2, 4, 5, -2
样例输出
1
"""
def solver(nums):
maps = {}
ret = 0
retList = []
for n in nums:
if n in maps:
if maps[n] == 1:
if n no... | python |
class UserErrorMessage(object):
OPERATION_NOT_SUPPORTED = "Operation is not supported."
NO_MODEL_PUBLISHED = "No model published for the current API."
NO_ENDPOINT_PUBLISHED = "No service endpoint published in the current API."
NO_OPERATION_PUBLISHED = "No operation published in the current API."
CAN... | python |
# -*- encoding: utf-8 -*-
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.http import Http404, HttpResponse
from django.shortcuts import render, get_object_or_404, redirect
from accounts.... | python |
#!/usr/bin/env python
# coding: utf-8
from xumm.resource import XummResource
from typing import List
class UserTokenValidity(XummResource):
"""
Attributes:
model_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is a... | python |
#!/usr/bin/python
import unittest
import GT3
from tests.ShotBase import *
from matplotlib.axes._axes import Axes
from matplotlib.pyplot import Figure
class CommonFunctions(object):
"""Tests to see if a shot has the expected attributes typical for a fully run shot."""
def test_gt3_has_core(cls):
cls.... | python |
import datetime
def current_year():
"""current_year
This method used to get the current year
"""
return datetime.date.today().year | python |
import streamlit as st
import pandas as pd
st.title("File uploader example")
st.write(
"""
This is an example of how to use a file uploader.
Here, we are simply going to upload a CSV file and display it.
It should serve as a minimal example
for you to jump off and do more complex things.
"""
)
st.header("Upload... | python |
"""
ASGI config for scheduler project.
It exposes the ASGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/3.1/howto/deployment/asgi/
"""
from os import environ
from django.core.asgi import get_asgi_application # type: ignore
envi... | python |
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: MIT-0
import json
import datetime
import time
import os
import boto3
from datetime import timedelta
import random
# Tries to find an existing or free game session and return the IP and Port to the client
def lambda_handle... | python |
import anachronos
from test.runner import http
class PingTest(anachronos.TestCase):
def test_ping(self):
res = http.get("/ping")
self.assertEqual(200, res.status_code)
self.assertEqual("Pong!", res.text)
| python |
from setuptools import setup
setup(
name="minigit",
version="1.0",
packages=["minigit"],
entry_points={"console_scripts": ["minigit = minigit.cli:main"]},
)
| python |
__author__ = 'cvl'
class Domain_model():
def __init__(self, json_dict):
self.free_domains = json_dict['free_domains']
self.paid_domains = json_dict['paid_domains'] | python |
import pandas as pd
class CurrentPositionStatusSettler:
def __init__(self, calculation_source):
self.__calculation_source = calculation_source
def settle_current_position_status(self) -> pd.DataFrame:
self.__calculation_source = self.__calculation_source[
~self.__calculat... | python |
'''
Stanle Bak
Python F-16
Thrust function
'''
import numpy as np
import tensorflow as tf
from util import fix, fix_tf
def thrust(power, alt, rmach):
'thrust lookup-table version'
a = np.array([[1060, 670, 880, 1140, 1500, 1860], \
[635, 425, 690, 1010, 1330, 1700], \
[60, 25, 345, 755, 1130... | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.