id int64 0 190k | prompt stringlengths 21 13.4M | docstring stringlengths 1 12k ⌀ |
|---|---|---|
22,825 | from rlcard.games.uno.card import UnoCard
def _print_action(action):
''' Print out an action in a nice form
Args:
action (str): A string a action
'''
UnoCard.print_cards(action, wild_color=True)
class UnoCard:
info = {'type': ['number', 'action', 'wild'],
'color': ['r', 'g', '... | Print out the state of a given player Args: player (int): Player id |
22,826 | import os
from PIL import Image, ImageTk, ImageDraw
def reporthook(count, block_size, total_size):
global start_time
if count == 0:
start_time = time.time()
return
duration = time.time() - start_time
progress_size = int(count * block_size)
speed = int(pro... | null |
22,827 | import os
from PIL import Image, ImageTk, ImageDraw
image_dir = os.path.abspath(os.path.dirname(__file__))
def long_rank_name_for(rank: str) -> str:
rank_exceptions = {'A': 'ace', 'T': '10', 'J': 'jack', 'Q': 'queen', 'K': 'king'}
result = rank if rank not in rank_exceptions.keys() else rank_exceptions[rank]
... | null |
22,828 | import os
from PIL import Image, ImageTk, ImageDraw
image_dir = os.path.abspath(os.path.dirname(__file__))
def get_card_back_image(scale_factor: float):
card_filename = "{}/cards_png/back.jpg".format(image_dir)
image = Image.open(card_filename)
image_width, image_height = image.size
card_scale_factor =... | null |
22,829 | from typing import TYPE_CHECKING
from typing import List
import tkinter as tk
import rlcard.games.gin_rummy.utils.utils as gin_rummy_utils
from rlcard.games.gin_rummy.utils.gin_rummy_error import GinRummyProgramError
from .canvas_item import CardItem, CanvasItem
from .player_type import PlayerType
from .configurations ... | null |
22,830 | from typing import TYPE_CHECKING
from typing import List
import tkinter as tk
import rlcard.games.gin_rummy.utils.utils as gin_rummy_utils
from rlcard.games.gin_rummy.utils.gin_rummy_error import GinRummyProgramError
from .canvas_item import CardItem, CanvasItem
from .player_type import PlayerType
from .configurations ... | null |
22,831 | from typing import TYPE_CHECKING
from typing import List
import tkinter as tk
import rlcard.games.gin_rummy.utils.utils as gin_rummy_utils
from rlcard.games.gin_rummy.utils.gin_rummy_error import GinRummyProgramError
from .canvas_item import CardItem, CanvasItem
from .player_type import PlayerType
from .configurations ... | null |
22,832 | from typing import TYPE_CHECKING
from typing import List
import tkinter as tk
import rlcard.games.gin_rummy.utils.utils as gin_rummy_utils
from rlcard.games.gin_rummy.utils.gin_rummy_error import GinRummyProgramError
from .canvas_item import CardItem, CanvasItem
from .player_type import PlayerType
from .configurations ... | null |
22,833 | from typing import TYPE_CHECKING
from typing import List
import tkinter as tk
import rlcard.games.gin_rummy.utils.utils as gin_rummy_utils
from rlcard.games.gin_rummy.utils.gin_rummy_error import GinRummyProgramError
from .canvas_item import CardItem, CanvasItem
from .player_type import PlayerType
from .configurations ... | null |
22,834 | from typing import TYPE_CHECKING
import tkinter as tk
from ..gin_rummy_human_agent import HumanAgent
from . import configurations
from . import info_messaging
from . import utils
from .env_thread import EnvThread
import rlcard.games.gin_rummy.utils.utils as gin_rummy_utils
from rlcard.games.gin_rummy.utils.gin_rummy_er... | null |
22,835 | from typing import TYPE_CHECKING
from .canvas_item import CanvasItem
from .player_type import PlayerType
from . import handling_tap
from . import utils
from rlcard.games.gin_rummy.utils.gin_rummy_error import GinRummyProgramError
def handle_tap_to_arrange_held_pile(hit_item: CanvasItem, game_canvas: 'GameCanvas'):
... | null |
22,836 | from PIL import Image, ImageDraw, ImageFilter
def rounded_rectangle(self: ImageDraw, xy, corner_radius, fill=None, outline=None): # FIXME: not used
upper_left_point = xy[0]
bottom_right_point = xy[1]
self.rectangle(
[
(upper_left_point[0], upper_left_point[1] + corner_radius),
... | null |
22,837 | from typing import TYPE_CHECKING
from . import configurations
from . import info_messaging
from . import utils
from .configurations import DECLARE_DEAD_HAND_ACTION_ID
from rlcard.games.gin_rummy.game import GinRummyGame
def show_put_card_message(player_id: int, game_canvas: 'GameCanvas'):
is_human_player = game_can... | null |
22,838 | from typing import TYPE_CHECKING
from . import configurations
from . import info_messaging
from . import utils
from .configurations import DECLARE_DEAD_HAND_ACTION_ID
from rlcard.games.gin_rummy.game import GinRummyGame
def show_epilog_message_on_declare_dead_hand(game_canvas: 'GameCanvas'):
game_canvas.info_label... | null |
22,839 | from typing import TYPE_CHECKING
from . import configurations
from . import info_messaging
from . import utils
from .configurations import DECLARE_DEAD_HAND_ACTION_ID
from rlcard.games.gin_rummy.game import GinRummyGame
DECLARE_DEAD_HAND_ACTION_ID = 4
class GinRummyGame:
''' Game class. This class will interact w... | null |
22,840 | from rlcard.utils.utils import print_card
def print_card(cards):
''' Nicely print a card or list of cards
Args:
card (string or list): The card(s) to be printed
'''
if cards is None:
cards = [None]
if isinstance(cards, str):
cards = [cards]
lines = [[] for _ in range(9... | Print out the state Args: state (dict): A dictionary of the raw state action_record (list): A list of the each player's historical actions |
22,841 | from rlcard.utils.utils import print_card
def print_card(cards):
''' Nicely print a card or list of cards
Args:
card (string or list): The card(s) to be printed
'''
if cards is None:
cards = [None]
if isinstance(cards, str):
cards = [cards]
lines = [[] for _ in range(9... | Print out the state Args: state (dict): A dictionary of the raw state action_record (list): A list of the each player's historical actions |
22,842 | from rlcard.utils.utils import print_card
def print_card(cards):
''' Nicely print a card or list of cards
Args:
card (string or list): The card(s) to be printed
'''
if cards is None:
cards = [None]
if isinstance(cards, str):
cards = [cards]
lines = [[] for _ in range(9... | Print out the state Args: state (dict): A dictionary of the raw state action_record (list): A list of the historical actions |
22,843 | import logging
import traceback
import numpy as np
import torch
def get_batch(
free_queue,
full_queue,
buffers,
batch_size,
lock
):
with lock:
indices = [full_queue.get() for _ in range(batch_size)]
batch = {
key: torch.stack([buffers[key][m] for m in indices], dim=1)
... | null |
22,844 | import logging
import traceback
import numpy as np
import torch
def create_buffers(
T,
num_buffers,
state_shape,
action_shape,
device_iterator,
):
buffers = {}
for device in device_iterator:
buffers[device] = []
for player_id in range(len(state_shape)):
specs = d... | null |
22,845 | import logging
import traceback
import numpy as np
import torch
def create_optimizers(
num_players,
learning_rate,
momentum,
epsilon,
alpha,
learner_model
):
optimizers = []
for player_id in range(num_players):
optimizer = torch.optim.RMSprop(
learner_model.parameter... | null |
22,846 | import logging
import traceback
import numpy as np
import torch
log = logging.getLogger('doudzero')
log.propagate = False
log.addHandler(shandle)
log.setLevel(logging.INFO)
def act(
i,
device,
T,
free_queue,
full_queue,
model,
buffers,
env
):
try:
log.info('Device %s Actor %... | null |
22,847 | import os
import threading
import time
import timeit
import pprint
from collections import deque
import torch
from torch import multiprocessing as mp
from torch import nn
from .file_writer import FileWriter
from .model import DMCModel
from .pettingzoo_model import DMCModelPettingZoo
from .utils import (
get_batch,
... | Performs a learning (optimization) step. |
22,849 | import traceback
import numpy as np
import torch
from .utils import log
from rlcard.utils import run_game_pettingzoo
def create_buffers_pettingzoo(
T,
num_buffers,
env,
device_iterator,
):
buffers = {}
for device in device_iterator:
buffers[device] = []
for agent_name in env.age... | null |
22,850 | import traceback
import numpy as np
import torch
from .utils import log
from rlcard.utils import run_game_pettingzoo
def _get_action_feature(action, action_space):
out = np.zeros(action_space)
out[action] = 1
return out
log = logging.getLogger('doudzero')
log.propagate = False
log.addHandler(shandle)
log.s... | null |
22,851 | import numpy as np
from rlcard.games.mahjong.card import MahjongCard as Card
for _type in ['bamboo', 'characters', 'dots']:
for _trait in ['1', '2', '3', '4', '5', '6', '7', '8', '9']:
card = _type+"-"+_trait
card_encoding_dict[card] = num
num += 1
for _trait in ['green', 'red', 'white']:
... | null |
22,852 | import numpy as np
from rlcard.games.mahjong.card import MahjongCard as Card
def pile2list(pile):
cards_list = []
for each in pile:
cards_list.extend(each)
return cards_list | null |
22,853 | import numpy as np
from rlcard.games.mahjong.card import MahjongCard as Card
card_encoding_dict = {}
num = 0
card_encoding_dict['pong'] = num
card_encoding_dict['chow'] = num + 1
card_encoding_dict['gong'] = num + 2
card_encoding_dict['stand'] = num + 3
def cards2list(cards):
cards_list = []
for each in cards:
... | null |
22,854 | from typing import List
import numpy as np
from .bridge_card import BridgeCard
class BridgeCard(Card):
def card(card_id: int):
def get_deck() -> [Card]:
def __init__(self, suit: str, rank: str):
def __str__(self):
def __repr__(self):
def encode_cards(cards: List[BridgeCard]) -> np.ndarray: #... | null |
22,855 | import os
import json
import numpy as np
from collections import OrderedDict
import rlcard
from rlcard.games.uno.card import UnoCard as Card
The provided code snippet includes necessary dependencies for implementing the `init_deck` function. Write a Python function `def init_deck()` to solve the following problem:
Gen... | Generate uno deck of 108 cards |
22,856 | import os
import json
import numpy as np
from collections import OrderedDict
import rlcard
from rlcard.games.uno.card import UnoCard as Card
The provided code snippet includes necessary dependencies for implementing the `cards2list` function. Write a Python function `def cards2list(cards)` to solve the following probl... | Get the corresponding string representation of cards Args: cards (list): list of UnoCards objects Returns: (string): string representation of cards |
22,857 | import os
import json
import numpy as np
from collections import OrderedDict
import rlcard
from rlcard.games.uno.card import UnoCard as Card
COLOR_MAP = {'r': 0, 'g': 1, 'b': 2, 'y': 3}
TRAIT_MAP = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7,
'8': 8, '9': 9, 'skip': 10, 'reverse': 11, '... | Encode hand and represerve it into plane Args: plane (array): 3*4*15 numpy array hand (list): list of string of hand's card Returns: (array): 3*4*15 numpy array |
22,858 | import os
import json
import numpy as np
from collections import OrderedDict
import rlcard
from rlcard.games.uno.card import UnoCard as Card
COLOR_MAP = {'r': 0, 'g': 1, 'b': 2, 'y': 3}
TRAIT_MAP = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7,
'8': 8, '9': 9, 'skip': 10, 'reverse': 11, '... | Encode target and represerve it into plane Args: plane (array): 1*4*15 numpy array target(str): string of target card Returns: (array): 1*4*15 numpy array |
22,859 | from typing import TYPE_CHECKING
from typing import List, Tuple
from .utils.action_event import *
from .utils.scorers import GinRummyScorer
from .utils import melding
from .utils.gin_rummy_error import GinRummyProgramError
from rlcard.games.gin_rummy.utils import utils
def _get_going_out_cards(meld_clusters: List[List[... | :param hand: List[Card] -- must have 11 cards :param going_out_deadwood_count: int :return List[Card], List[Card: cards in hand that be knocked, cards in hand that can be ginned |
22,860 | from typing import List
from rlcard.games.base import Card
from rlcard.games.gin_rummy.utils import utils
from rlcard.games.gin_rummy.utils.gin_rummy_error import GinRummyProgramError
class Card:
'''
Card stores the suit and rank of a single card
Note:
The suit variable in a standard card game sho... | null |
22,861 | from typing import List, Iterable
import numpy as np
from rlcard.games.base import Card
from .gin_rummy_error import GinRummyProgramError
class Card:
'''
Card stores the suit and rank of a single card
Note:
The suit variable in a standard card game should be one of [S, H, D, C, BJ, RJ] meaning [Sp... | null |
22,862 | from typing import List, Iterable
import numpy as np
from rlcard.games.base import Card
from .gin_rummy_error import GinRummyProgramError
_deck = [card_from_card_id(card_id) for card_id in range(52)]
class Card:
'''
Card stores the suit and rank of a single card
Note:
The suit variable in a standa... | null |
22,863 | from typing import List, Iterable
import numpy as np
from rlcard.games.base import Card
from .gin_rummy_error import GinRummyProgramError
_deck = [card_from_card_id(card_id) for card_id in range(52)]
class Card:
'''
Card stores the suit and rank of a single card
Note:
The suit variable in a standa... | null |
22,864 | from typing import List, Iterable
import numpy as np
from rlcard.games.base import Card
from .gin_rummy_error import GinRummyProgramError
def get_card_id(card: Card) -> int:
class Card:
def __init__(self, suit, rank):
def __eq__(self, other):
def __hash__(self):
def __str__(self):
def get_inde... | null |
22,865 | from typing import TYPE_CHECKING
from typing import Callable
from .action_event import *
from ..player import GinRummyPlayer
from .move import ScoreNorthMove, ScoreSouthMove
from .gin_rummy_error import GinRummyProgramError
from rlcard.games.gin_rummy.utils import melding
from rlcard.games.gin_rummy.utils import utils
... | Get the payoff of player: a) 1.0 if player gins b) 0.2 if player knocks c) -deadwood_count / 100 otherwise Returns: payoff (int or float): payoff for player (higher is better) |
22,866 | import os
import json
from collections import OrderedDict
import threading
import collections
import rlcard
CARD_RANK_STR = ['3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K',
'A', '2', 'B', 'R']
The provided code snippet includes necessary dependencies for implementing the `doudizhu_sort_str` fun... | Compare the rank of two cards of str representation Args: card_1 (str): str representation of solo card card_2 (str): str representation of solo card Returns: int: 1(card_1 > card_2) / 0(card_1 = card2) / -1(card_1 < card_2) |
22,867 | import os
import json
from collections import OrderedDict
import threading
import collections
import rlcard
CARD_RANK = ['3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K',
'A', '2', 'BJ', 'RJ']
The provided code snippet includes necessary dependencies for implementing the `doudizhu_sort_card` function... | Compare the rank of two cards of Card object Args: card_1 (object): object of Card card_2 (object): object of card |
22,868 | import os
import json
from collections import OrderedDict
import threading
import collections
import rlcard
The provided code snippet includes necessary dependencies for implementing the `get_landlord_score` function. Write a Python function `def get_landlord_score(current_hand)` to solve the following problem:
Roughl... | Roughly judge the quality of the hand, and provide a score as basis to bid landlord. Args: current_hand (str): string of cards. Eg: '56888TTQKKKAA222R' Returns: int: score |
22,869 | import os
import json
from collections import OrderedDict
import threading
import collections
import rlcard
The provided code snippet includes necessary dependencies for implementing the `cards2str_with_suit` function. Write a Python function `def cards2str_with_suit(cards)` to solve the following problem:
Get the cor... | Get the corresponding string representation of cards with suit Args: cards (list): list of Card objects Returns: string: string representation of cards |
22,870 | import os
import json
from collections import OrderedDict
import threading
import collections
import rlcard
CARD_RANK_STR = ['3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K',
'A', '2', 'B', 'R']
The provided code snippet includes necessary dependencies for implementing the `encode_cards` function... | Encode cards and represerve it into plane. Args: cards (list or str): list or str of cards, every entry is a character of solo representation of card |
22,871 | import os
import json
from collections import OrderedDict
import threading
import collections
import rlcard
def cards2str(cards):
''' Get the corresponding string representation of cards
Args:
cards (list): list of Card objects
Returns:
string: string representation of cards
'''
resp... | Provide player's cards which are greater than the ones played by previous player in one round Args: player (DoudizhuPlayer object): the player waiting to play cards greater_player (DoudizhuPlayer object): the player who played current biggest cards. Returns: list: list of string of greater cards Note: 1. return value c... |
22,872 | import numpy as np
class Hand:
def __init__(self, all_cards):
self.all_cards = all_cards # two hand cards + five public cards
self.category = 0
#type of a players' best five cards, greater combination has higher number eg: 0:"Not_Yet_Evaluated" 1: "High_Card" , 9:"Straight_Flush"
sel... | Compare all palyer's all seven cards Args: hands(list): cards of those players with same highest hand_catagory. e.g. hands = [['CT', 'ST', 'H9', 'B9', 'C2', 'C8', 'C7'], ['CJ', 'SJ', 'H9', 'B9', 'C2', 'C8', 'C7'], ['CT', 'ST', 'H9', 'B9', 'C2', 'C8', 'C7']] Returns: [0, 1, 0]: player1 wins [1, 0, 0]: player0 wins [1, 1... |
22,873 | import importlib
registry = EnvRegistry()
The provided code snippet includes necessary dependencies for implementing the `register` function. Write a Python function `def register(env_id, entry_point)` to solve the following problem:
Register an environment Args: env_id (string): The name of the environent entry_point... | Register an environment Args: env_id (string): The name of the environent entry_point (string): A string the indicates the location of the envronment class |
22,874 | import importlib
DEFAULT_CONFIG = {
'allow_step_back': False,
'seed': None,
}
registry = EnvRegistry()
The provided code snippet includes necessary dependencies for implementing the `make` function. Write a Python function `def make(env_id, config={})` to solve the following problem:
Create and... | Create and environment instance Args: env_id (string): The name of the environment config (dict): A dictionary of the environment settings env_num (int): The number of environments |
22,875 | import numpy as np
from collections import OrderedDict
from rlcard.envs import Env
from rlcard.games.blackjack import Game
rank2score = {"A":11, "2":2, "3":3, "4":4, "5":5, "6":6, "7":7, "8":8, "9":9, "T":10, "J":10, "Q":10, "K":10}
def get_score(hand):
score = 0
count_a = 0
for card in hand:
score... | null |
22,876 | from collections import Counter, OrderedDict
import numpy as np
from rlcard.envs import Env
def _get_one_hot_array(num_left_cards, max_num_cards):
one_hot = np.zeros(max_num_cards, dtype=np.int8)
one_hot[num_left_cards - 1] = 1
return one_hot | null |
22,877 | from collections import Counter, OrderedDict
import numpy as np
from rlcard.envs import Env
def _cards2array(cards):
if cards == 'pass':
return np.zeros(54, dtype=np.int8)
matrix = np.zeros([4, 13], dtype=np.int8)
jokers = np.zeros(2, dtype=np.int8)
counter = Counter(cards)
for card, num_tim... | null |
22,878 | from collections import Counter, OrderedDict
import numpy as np
from rlcard.envs import Env
def _process_action_seq(sequence, length=9):
sequence = [action[1] for action in sequence[-length:]]
if len(sequence) < length:
empty_sequence = ['' for _ in range(length - len(sequence))]
empty_sequence... | null |
22,879 | import importlib
model_registry = ModelRegistry()
The provided code snippet includes necessary dependencies for implementing the `register` function. Write a Python function `def register(model_id, entry_point)` to solve the following problem:
Register a model Args: model_id (string): the name of the model entry_point... | Register a model Args: model_id (string): the name of the model entry_point (string): a string the indicates the location of the model class |
22,880 | import importlib
model_registry = ModelRegistry()
The provided code snippet includes necessary dependencies for implementing the `load` function. Write a Python function `def load(model_id)` to solve the following problem:
Create and model instance Args: model_id (string): the name of the model
Here is the function:
... | Create and model instance Args: model_id (string): the name of the model |
22,881 | import numpy as np
from rlcard.games.base import Card
def set_seed(seed):
if seed is not None:
import subprocess
import sys
reqs = subprocess.check_output([sys.executable, '-m', 'pip', 'freeze'])
installed_packages = [r.decode().split('==')[0] for r in reqs.split()]
if 'tor... | null |
22,882 | import numpy as np
from rlcard.games.base import Card
def get_device():
import torch
if torch.backends.mps.is_available():
device = torch.device("mps:0")
print("--> Running on the GPU")
elif torch.cuda.is_available():
device = torch.device("cuda:0")
print("--> Running on the... | null |
22,883 | import numpy as np
from rlcard.games.base import Card
class Card:
'''
Card stores the suit and rank of a single card
Note:
The suit variable in a standard card game should be one of [S, H, D, C, BJ, RJ] meaning [Spades, Hearts, Diamonds, Clubs, Black Joker, Red Joker]
Similarly the rank va... | Initialize a standard deck of 52 cards Returns: (list): A list of Card object |
22,884 | import numpy as np
from rlcard.games.base import Card
class Card:
'''
Card stores the suit and rank of a single card
Note:
The suit variable in a standard card game should be one of [S, H, D, C, BJ, RJ] meaning [Spades, Hearts, Diamonds, Clubs, Black Joker, Red Joker]
Similarly the rank va... | Initialize a standard deck of 52 cards, BJ and RJ Returns: (list): Alist of Card object |
22,885 | import numpy as np
from rlcard.games.base import Card
The provided code snippet includes necessary dependencies for implementing the `rank2int` function. Write a Python function `def rank2int(rank)` to solve the following problem:
Get the coresponding number of a rank. Args: rank(str): rank stored in Card object Retur... | Get the coresponding number of a rank. Args: rank(str): rank stored in Card object Returns: (int): the number corresponding to the rank Note: 1. If the input rank is an empty string, the function will return -1. 2. If the input rank is not valid, the function will return None. |
22,886 | import numpy as np
from rlcard.games.base import Card
The provided code snippet includes necessary dependencies for implementing the `reorganize` function. Write a Python function `def reorganize(trajectories, payoffs)` to solve the following problem:
Reorganize the trajectory to make it RL friendly Args: trajectory (... | Reorganize the trajectory to make it RL friendly Args: trajectory (list): A list of trajectories payoffs (list): A list of payoffs for the players. Each entry corresponds to one player Returns: (list): A new trajectories that can be fed into RL algorithms. |
22,887 | import numpy as np
from rlcard.games.base import Card
The provided code snippet includes necessary dependencies for implementing the `remove_illegal` function. Write a Python function `def remove_illegal(action_probs, legal_actions)` to solve the following problem:
Remove illegal actions and normalize the probability ... | Remove illegal actions and normalize the probability vector Args: action_probs (numpy.array): A 1 dimention numpy array. legal_actions (list): A list of indices of legal actions. Returns: probd (numpy.array): A normalized vector without legal actions. |
22,888 | import numpy as np
from rlcard.games.base import Card
The provided code snippet includes necessary dependencies for implementing the `tournament` function. Write a Python function `def tournament(env, num)` to solve the following problem:
Evaluate he performance of the agents in the environment Args: env (Env class): ... | Evaluate he performance of the agents in the environment Args: env (Env class): The environment to be evaluated. num (int): The number of games to play. Returns: A list of avrage payoffs for each player |
22,889 | import numpy as np
from rlcard.games.base import Card
import os
if not os.path.isfile(os.path.join(ROOT_PATH, 'games/doudizhu/jsondata/action_space.txt')) \
or not os.path.isfile(os.path.join(ROOT_PATH, 'games/doudizhu/jsondata/card_type.json')) \
or not os.path.isfile(os.path.join(ROOT_PATH, 'games... | Read data from csv file and plot the results |
22,890 | import hashlib
import numpy as np
import os
import struct
def error(msg, *args):
print(colorize('%s: %s'%('ERROR', msg % args), 'red'))
def hash_seed(seed=None, max_bytes=8):
"""Any given evaluation is likely to have many PRNG's active at
once. (Most commonly, because the environment is running in
multi... | null |
22,891 | from collections import defaultdict
import numpy as np
def wrap_state(state):
# check if obs is already wrapped
if "obs" in state and "legal_actions" in state and "raw_legal_actions" in state:
return state
wrapped_state = {}
wrapped_state["obs"] = state["observation"]
legal_actions = np.fl... | null |
22,892 | from collections import defaultdict
import numpy as np
def run_game_pettingzoo(env, agents, is_training=False):
env.reset()
trajectories = defaultdict(list)
for agent_name in env.agent_iter():
obs, reward, done, _, _ = env.last()
trajectories[agent_name].append((obs, reward, done))
i... | null |
22,893 | import os
import sys
import asyncio
from multiprocessing import Process, Manager
from platform import system
import websockets
from config import ServerConfig as Config
from util.server_cosmic import Cosmic, console
from util.server_check_model import check_model
from util.server_ws_recv import ws_recv
from util.server... | null |
22,894 | import os
import sys
import asyncio
import signal
from pathlib import Path
from platform import system
from typing import List
import typer
import colorama
import keyboard
from config import ClientConfig as Config
from util.client_cosmic import console, Cosmic
from util.client_stream import stream_open, stream_close
fr... | null |
22,895 | import os
import sys
import asyncio
import signal
from pathlib import Path
from platform import system
from typing import List
import typer
import colorama
import keyboard
from config import ClientConfig as Config
from util.client_cosmic import console, Cosmic
from util.client_stream import stream_open, stream_close
fr... | 用 CapsWriter Server 转录音视频文件,生成 srt 字幕 |
22,896 | import argparse
import asyncio
import logging
import wave
import subprocess
from typing import List, Tuple
import shlex
import json
import time
import numpy as np
def get_args():
parser = argparse.ArgumentParser(
formatter_class=argparse.ArgumentDefaultsHelpFormatter
)
parser.add_argument(
... | null |
22,897 | import argparse
import asyncio
import logging
import wave
import subprocess
from typing import List, Tuple
import shlex
import json
import time
try:
import websockets
except ImportError:
print("please run:")
print("")
print(" pip install websockets")
print("")
print("before you run this script... | null |
22,898 | import sys
from pathlib import Path
from typing import Dict
import yaml
def write_tokens(tokens: Dict[int, str]):
with open("tokens.txt", "w", encoding="utf-8") as f:
for idx, s in enumerate(tokens):
f.write(f"{s} {idx}\n") | null |
22,899 | import json
from datetime import timedelta
from pathlib import Path
import typer
import srt
from rich import print
def lines_match_words(text_lines: list[str], words: list[dict[str, str | float]]) -> list[srt.Subtitle]:
def get_words(json_file: Path) -> list[dict[str, str | float]]:
def get_lines(txt_file: Path) -> lis... | null |
22,900 | from pathlib import Path
from typing import Dict
import numpy as np
import onnx
import yaml
def load_cmvn():
neg_mean = None
inv_stddev = None
with open("am.mvn", encoding="utf-8") as f:
for line in f:
if not line.startswith("<LearnRateCoef>"):
continue
t = ... | null |
22,901 | from pathlib import Path
from typing import Dict
import numpy as np
import onnx
import yaml
def load_lfr_params(config):
with open("config.yaml", encoding="utf-8") as f:
for line in f:
if "lfr_m" in line:
lfr_m = int(line.split()[-1])
elif "lfr_n" in line:
... | null |
22,902 | from pathlib import Path
from typing import Dict
import numpy as np
import onnx
import yaml
The provided code snippet includes necessary dependencies for implementing the `add_meta_data` function. Write a Python function `def add_meta_data(filename: str, meta_data: Dict[str, str])` to solve the following problem:
Add ... | Add meta data to an ONNX model. It is changed in-place. Args: filename: Filename of the ONNX model to be changed. meta_data: Key-value pairs. |
22,903 | import argparse
import shutil
import subprocess
import sys
import json
import time
import re
from dataclasses import dataclass
from datetime import timedelta
from pathlib import Path
from copy import copy
import numpy as np
import sherpa_onnx
def get_args():
parser = argparse.ArgumentParser(
formatter_clas... | null |
22,904 | import argparse
import shutil
import subprocess
import sys
import json
import time
import re
from dataclasses import dataclass
from datetime import timedelta
from pathlib import Path
from copy import copy
import numpy as np
import sherpa_onnx
def assert_file_exists(filename: str):
assert Path(filename).is_file(), (... | null |
22,905 | import json
import base64
import asyncio
from multiprocessing import Queue
from util.server_cosmic import console, Cosmic
from util.server_classes import Result
from util.asyncio_to_thread import to_thread
from rich import inspect
console = Console(highlight=False)
class Cosmic:
class Result:
def __init__... | null |
22,906 | from importlib.util import find_spece
import os
import sys
from os import remove
from pathlib import Path
from typing import List
from pprint import pprint
from urllib.parse import unquote
from markdown_it import MarkdownIt
from markdown_it.token import Token
from rich.console import Console
markdown_ext = ['md', 'mark... | null |
22,907 | from importlib.util import find_spece
import os
import sys
from os import remove
from pathlib import Path
from typing import List
from pprint import pprint
from urllib.parse import unquote
from markdown_it import MarkdownIt
from markdown_it.token import Token
from rich.console import Console
def get_links(text: str): ... | null |
22,908 | from importlib.util import find_spece
import os
import sys
from os import remove
from pathlib import Path
from typing import List
from pprint import pprint
from urllib.parse import unquote
from markdown_it import MarkdownIt
from markdown_it.token import Token
from rich.console import Console
def absolutify_links(file,... | null |
22,909 | import sys
from pathlib import Path
from config import ModelPaths
from util.server_cosmic import console
# 输出时是否将中文数字转为阿拉伯数字
# 输出时是否启用标点符号引擎
# 输出时是否调整中英之间的空格
# Server 地址
# Server 端口
# 控制录音的快捷键,默认是 CapsLock
# 长按模式,按下录音,松开停止,像对讲机一样用。
... | null |
22,910 | import json
import time
import base64
import asyncio
import websockets
from base64 import b64decode
from util.server_cosmic import console, Cosmic
from util.server_classes import Task, Result
from util.my_status import Status
status_mic = Status('正在接收音频', spinner='point')
class Cache:
# 定义一个可变对象,用于保存音频数据、偏移时间
... | null |
22,911 | import time
import sherpa_onnx
from multiprocessing import Queue
import signal
from platform import system
from config import ServerConfig as Config
from config import ParaformerArgs, ModelPaths
from util.server_cosmic import console
from util.server_recognize import recognize
from util.empty_working_set import empty_c... | null |
22,912 | import os
import sys
import glob
import platform
import shutil
from setuptools import find_packages
from setuptools import setup, Extension
from setuptools.command.build_ext import build_ext
The provided code snippet includes necessary dependencies for implementing the `copy_compiled_libs` function. Write a Python fun... | Copy compiled libraries to the destination directory. |
22,913 | import os
import sys
import glob
import platform
import shutil
from setuptools import find_packages
from setuptools import setup, Extension
from setuptools.command.build_ext import build_ext
The provided code snippet includes necessary dependencies for implementing the `copy_fonts` function. Write a Python function `d... | Copy fonts to the destination directory. |
22,914 | import os
import sys
import glob
import platform
import shutil
from setuptools import find_packages
from setuptools import setup, Extension
from setuptools.command.build_ext import build_ext
The provided code snippet includes necessary dependencies for implementing the `process_develop_setup` function. Write a Python ... | Clean up (if necessary) some directories before or after running setup in development (a.k.a. editable) mode (`pip install -e .`). |
22,915 | from . import *
def build_scenario(builder):
builder.config().game_duration = 400
builder.config().deterministic = False
builder.config().offsides = False
builder.config().end_episode_on_score = True
builder.config().end_episode_on_out_of_play = True
builder.config().end_episode_on_possession_change = True... | null |
22,916 | from . import *
def build_scenario(builder):
builder.config().game_duration = 3000
builder.config().second_half = 1500
builder.config().right_team_difficulty = 1.0
builder.config().left_team_difficulty = 1.0
builder.config().deterministic = False
if builder.EpisodeNumber() % 2 == 0:
first_team = Team.e... | null |
22,917 | from . import *
def build_scenario(builder):
builder.config().game_duration = 400
builder.config().deterministic = False
builder.config().offsides = False
builder.config().end_episode_on_score = True
builder.config().end_episode_on_out_of_play = True
builder.config().end_episode_on_possession_change = True... | null |
22,918 | from . import *
def build_scenario(builder):
builder.config().game_duration = 400
builder.config().deterministic = False
builder.config().offsides = False
builder.config().end_episode_on_score = True
builder.config().end_episode_on_out_of_play = True
builder.config().end_episode_on_possession_change = True... | null |
22,919 | from . import *
def build_scenario(builder):
builder.config().game_duration = 400
builder.config().deterministic = False
builder.config().offsides = False
builder.config().end_episode_on_score = True
builder.config().end_episode_on_out_of_play = True
builder.config().end_episode_on_possession_change = True... | null |
22,920 | from . import *
def build_scenario(builder):
builder.config().game_duration = 500
builder.config().right_team_difficulty = 0.0
builder.config().left_team_difficulty = 0.0
builder.config().deterministic = False
if builder.EpisodeNumber() % 2 == 0:
first_team = Team.e_Left
second_team = Team.e_Right
... | null |
22,921 | from . import *
def build_scenario(builder):
builder.config().game_duration = 400
builder.config().deterministic = False
builder.config().offsides = False
builder.config().end_episode_on_score = True
builder.config().end_episode_on_out_of_play = True
builder.config().end_episode_on_possession_change = True... | null |
22,922 | from . import *
def build_scenario(builder):
builder.config().game_duration = 3000
builder.config().right_team_difficulty = 0.05
builder.config().deterministic = False
if builder.EpisodeNumber() % 2 == 0:
first_team = Team.e_Left
second_team = Team.e_Right
else:
first_team = Team.e_Right
seco... | null |
22,923 | from . import *
def build_scenario(builder):
builder.config().game_duration = 400
builder.config().deterministic = False
builder.config().offsides = False
builder.config().end_episode_on_score = True
builder.config().end_episode_on_out_of_play = True
builder.config().end_episode_on_possession_change = True... | null |
22,924 | from . import *
def build_scenario(builder):
builder.config().game_duration = 400
builder.config().deterministic = False
builder.config().offsides = False
builder.config().end_episode_on_score = True
builder.config().end_episode_on_out_of_play = True
builder.config().end_episode_on_possession_change = Fals... | null |
22,925 | from . import *
def build_scenario(builder):
builder.config().game_duration = 400
builder.config().deterministic = False
builder.config().offsides = False
builder.config().end_episode_on_score = True
builder.config().end_episode_on_out_of_play = True
builder.config().end_episode_on_possession_change = True... | null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.