content stringlengths 5 1.05M |
|---|
import math
def collision(state, n):
"""returns true if boulder collides with alien"""
for i in range(n):
p=False
if state[0:n][i]==state[-n:][i] and state[0:n][i]=='1':
return True
return False
def bottom_row_rewards(full_states, n):
"""returns the reward for only the bott... |
from __future__ import absolute_import
from builtins import object
import concurrent
import grpc
from . import bridge_pb2
from . import bridge_message
class PsBridgeServer(object):
def __init__(self, bind, ps_factory):
self.server = grpc.server(concurrent.futures.ThreadPoolExecutor(max_workers=1))
... |
from __future__ import absolute_import, division, print_function, unicode_literals
import textwrap
import pkg_resources
from mock import MagicMock, patch
from pies.overrides import *
from frosted import checker
PyCF_ONLY_AST = 1024
@patch.object(checker.Checker, 'report')
def test_plugins(m_report):
""" Plugin... |
"""
Show a Pareto curve plot for individuals in a given generation.
"""
from __future__ import division
from __future__ import print_function
import pandas as pd
import plotly.graph_objs as go
import cea.plots.optimization
from cea.plots.variable_naming import NAMING
__author__ = "Bhargava Srepathi"
__copyright__ = ... |
# --------------------------------------------------------------------------
# Source file provided under Apache License, Version 2.0, January 2004,
# http://www.apache.org/licenses/
# (c) Copyright IBM Corp. 2018
# --------------------------------------------------------------------------
# gendoc: ignore
# This file... |
import os
import torch
class Multiview_Dataset(torch.utils.data.Dataset):
"""
Dataset class to read bird instances that have multiview matches.
Each index outputs one instance and its multiview annotations
"""
def __init__(self, root='data/cowbird/images',
annfile='data/cowbird/an... |
# Copyright (C) 2018-2020 Apple Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions and ... |
import numpy as np
from neupy import algorithms, layers
from base import BaseTestCase
from helpers import simple_classification
class L2RegularizationTestCase(BaseTestCase):
def test_l2_regularization(self):
network = layers.join(
layers.Input(10),
layers.Relu(5, weight=2, bias=2... |
#!/usr/bin/python3
import os
from os import path
import sys
temp_dir = 'temp'
build_dir = 'out'
run_dir = 'out/run'
jar_out_dir = 'out/jar'
jmod_out_dir = 'out/jmod'
module_dir='.'
dependency_dirs=['dependencies/jars']
jmod_dirs=['dependencies/native/jmods']
timestamp_cachefile=path.join(temp_dir, 'file_timestamp_ca... |
import argparse
import numpy as np
import timeit
import hashlib
import struct
import numba
import os
import sys
# to make sure relative import works in order to import test data
current_script_path = sys.argv[0]
package_home_path = os.path.abspath(os.path.join(os.path.dirname( __file__ ), '..'))
if package_home_path ... |
import pulsar as psr
def load_ref_system():
""" Returns benzaldehyde as found in the IQMol fragment library.
All credit to https://github.com/nutjunkie/IQmol
"""
return psr.make_system("""
C 0.3179 1.0449 -0.0067
C 1.6965 0.8596 -0.0102
C 2.22... |
# coding: utf-8
"""
ChannelDiagnosticDescriptor.py
The Clear BSD License
Copyright (c) – 2016, NetApp, Inc. All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted (subject to the limitations in the disclaimer below) provided that the following conditio... |
# Mathematics > Geometry > Points on a Rectangle
# Determine if a set of points coincides with the edges of a non-degenerate rectangle.
#
# https://www.hackerrank.com/challenges/points-on-rectangle/problem
# https://www.hackerrank.com/contests/101hack42/challenges/points-on-rectangle
#
# le rectangle a ses côtés parr... |
import re
from hashlib import md5
from xml.dom import minidom
from . import JarProvider
class FeedTheBeast(JarProvider):
base = 'http://www.creeperrepo.net/'
def work(self):
self.get(self.base+'getdate', self.handle_date)
def handle_date(self, data):
hash = md5()
hash.update('mcep... |
import csv
import os
import time
import numpy as np # type: ignore # this has some nice mathematics related functions
# using so called sparse linear algebra make stuff run way faster (ignoring zeros)
from scipy.sparse import csr_matrix, diags # type: ignore
# this guy can solve equation faster by taking advantage ... |
"""
Serializes numpy and JSON-like objects
"""
import pickle
import base64
import hashlib
import json
import pyarrow as pa
def pa_serialize(obj):
return pa.serialize(obj).to_buffer()
def pa_deserialize(binary):
return pa.deserialize(binary)
_SERIALIZER = pa_serialize
_DESERIALIZER = pa_deserialize
# _SER... |
import queue
import server_wrapper
import binascii
from socket import *
from pytun import *
from threading import Thread
'''
me = '192.168.77.10'
he = '192.168.77.2'
'''
tun = TunTapDevice(flags=IFF_TUN | IFF_NO_PI)
tun.addr = '192.168.77.10'
tun.netmask = '255.255.255.0'
tun.mtu = 150
tun.up()
class Packet... |
"""
This package is developed jointly between BuildSim team and Professor Adrian Chong.
The original script and example can be found at GITHUB page: https://github.com/adChong/bc-stan
The paper published can be found at: https://www.sciencedirect.com/science/article/pii/S0378778818307539?via%3Dihub
""" |
# -*- coding: utf-8 -*-
# vi: set ft=python sw=4 :
"""SLRD key data type module.
Todo:
- docs
- implement
"""
from super_type import SuperType
class KeyType(SuperType):
"""SLRD key data type.
This data type stores references to corresponding value files.
"""
def __init__(self, raw_yaml=None... |
"""
File: devices/views/configurator.py
Purpose:
This code is a class based view used to render and provide
functions for the device manual configuration view.
Functions allow users to send show commands manually to a device
and send configuration commands manually
"""
from django.contrib import mes... |
from app.data.components import Component, Type
tags = ['base', 'target', 'weapon', 'uses', 'exp', 'class_change', 'extra', 'utility', 'special', 'formula', 'aoe', 'aesthetic', 'advanced']
class ItemComponent(Component):
item = None
def get_items_using(expose: Type, value, db) -> list:
affected_i... |
"""Schema Validation."""
from .validators import Validator
class Scheme(object):
"""Scheme Validator."""
def __init__(self, scheme_spec):
self.validator = Validator.create_validator(scheme_spec)
def validate(self, value):
return self.validator.validate(value)
|
#!/usr/bin/env python
"""
Simple script to create a new incident.
"""
from __future__ import print_function
import time
import logging
import resilient
logging.basicConfig()
class ExampleArgumentParser(resilient.ArgumentParser):
"""Arguments for this command-line application, extending the standard Resilient a... |
# flask_web/app.py
"""
1. Creates the basic flask application
2. Connects the app to the database
3. Creates database tables, if they don't exist
"""
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from pathlib import Path
import os
app = Flask(__name__)
sqlite_location = '/db/digitalesWartenDB.sqlit... |
#!/usr/bin/env python
"""
Takes LDpred.py (or LD_pruning_thres.py) effect estimates, and (validation) genotypes in PLINK bed format as input.
The script then works out overlap and outputs predictions or risk scores as well as some prediction
accuracy statistics.
Note that for maximal accuracy al... |
"""TOTTO table processsing.
Processing the data format in TOTTO into the HybridQA one
"""
import copy
import hashlib
import json
import multiprocessing
from multiprocessing import Pool
import re
import pprint
import nltk
def clean_cell_text(string):
"""Strip off the weird tokens."""
string = string.replace('"',... |
import platform
import schedule
from time import sleep
from queue import Queue
from sys import version
from threading import Thread
from os import access, R_OK, getenv
from distro import linux_distribution
from os.path import isdir, abspath, dirname, join
from argparse import ArgumentParser, RawTextHelpFormatter
from l... |
from TestHelperSuperClass import testHelperSuperClass
from githubAPICalls import githubAPICallsClass
class mockAppParamsClass():
APIAPP_GITHUBREPOLOCATION = 'https://api.github.com/repos/rmetcalf9/dockPondSampleEBOs'
class mockAppObjClass():
appParams = mockAppParamsClass()
class test_appCassandraDatastoreClass(... |
from __future__ import absolute_import
import math
import chainer
import numpy as np
from ..links import CLink
from ..links import BinaryLinear
from ..links import BatchNormalization
from ..links import BST
from ..utils import binary_util as bu
class LinearBNBST(chainer.Chain, CLink):
def __init__(self, out_cha... |
import torch
import torch.nn as nn
import numpy as np
import random
from tqdm import tqdm
import os
import matplotlib.pyplot as plt
from sklearn.metrics import accuracy_score, confusion_matrix
from dataloader import DatasetLoader
from model_arch import Model
from config import *
def train():
'''
This is... |
""" API endpoint to return all the information necessary to construct the
script chart.
"""
# TODO:
# These changes all need to be made in coordination with frontend changes
# * remove empty lists from response
# * change top-level key from 'mss' to 'examples'
# * remove unnecessary fields from response
# all th... |
import webbrowser
# Graphics
HelpBar = '--------------------------------'
# Graphics
# WhiteList/Commands
WhiteList = [
"https://google.com",
"https://irssi.org/",
]
Commands = [
"pyb.help",
"pyb.whitelist",
"pyb.info",
]
# WhiteList/Commands
# Main
print('\x1b[1;35;49m')
print" _____ _ ... |
#!/usr/bin/env python3
import sys
import argparse
import os
import platform
import shutil
import hashlib
import json
from datetime import datetime
from logging import Logger, basicConfig, getLogger, INFO
from os import getenv
from pathlib import Path
from subprocess import (DEVNULL, PIPE, STDOUT, CalledProcessError,
... |
# Copyright 2019 Cambridge Quantum Computing
#
# 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 or agree... |
#!/usr/bin/python3
import logging
import sys
from argparsers import parse_args
from downloaders.downloader_factory import DownloaderFactory
from utils.utils import prepare_download_folder
LOGGER = logging.getLogger(__name__)
def main():
args = parse_args()
configure_logging(args.is_debug)
prepare_downl... |
import os
from pathlib import Path
from shutil import rmtree
from jinja2 import Environment, FileSystemLoader, select_autoescape
from qt_material import export_theme
root_path = os.path.abspath('../')
theme_path = os.path.join(root_path, "theme")
dark_theme_path = os.path.join(theme_path, "dark")
light_theme_path = ... |
#!/usr/bin/env python
# wujian@2020
import numpy as np
import scipy.signal as ss
import scipy.integrate as si
class MCRA(object):
"""
OM-LSA (Optimally Modified Log-Spectral Amplitude Estimator) with MCRA
Reference:
1) Cohen I, Berdugo B. Speech enhancement for non-stationary noise environments[... |
from .vis import flow_to_color, flow_err_to_color, flow_max_rad, tensor_to_color, chw_to_hwc, group_color
from .show_result import ShowResultTool, ShowFlow
from .save_result import SaveResultTool
from .vis_hooks import DistFlowVisHook |
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use ... |
"""
Django scommon settings for polls project.
For more information on this file, see
https://docs.djangoproject.com/en/1.11/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.11/ref/settings/
"""
import pathlib
base_dir = pathlib.Path(__file__).absolute().paren... |
import pygame
def draw():
pygame.init()
screen = pygame.display.set_mode((500,500))
screen.fill([255,255,255])
clock = pygame.time.Clock()
while running:
running = True
while running:
clock.tick(10)
for event in pygame.event.get():
if even... |
# -*- coding: utf-8 -*-
'''
The core behaviors used by minion and master
'''
# pylint: disable=W0232
# Import python libs
from __future__ import absolute_import
import os
import sys
import time
import types
import random
import logging
import itertools
import traceback
import multiprocessing
from collections import de... |
from application import create_app
from os import environ, path
from dotenv import load_dotenv
basedir = path.abspath(path.dirname(__file__))
load_dotenv(path.join(basedir, '.env'))
class Config:
"""Base config."""
STATIC_FOLDER = 'static'
TEMPLATES_FOLDER = 'templates'
SWAGGER_URL = '/api/docs' # UR... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#------------------------------------------------------------------------------
# Main
#------------------------------------------------------------------------------
def main():
# Get the number of particles per cell
number_particle_cell = get_number_particle_cell()... |
import json
import urllib
import urllib.request
import remoteconsole.client_input
def send_request(server_address, request_data):
ip, port = server_address
console_url = 'http://{}:{}'.format(ip, port)
request_body = json.dumps(request_data).encode('utf-8')
request = urllib.request.Request(
conso... |
import pandas as pb
data = pb.read_csv("products.csv")
data = data.groupby("product_name")
|
'''8. Матрица 5x4 заполняется вводом с клавиатуры кроме последних
элементов строк. Программа должна вычислять сумму введенных элементов
каждой строки и записывать в последнюю ячейку строки. В конце следует
вывести полученную матрицу.'''
matrix = []
for i in range(4):
matrix.append([])
sum = 0
for n in ran... |
from __future__ import absolute_import, division, print_function
from dask.utils import Dispatch
is_device_object = Dispatch(name="is_device_object")
@is_device_object.register(object)
def is_device_object_default(o):
return hasattr(o, "__cuda_array_interface__")
@is_device_object.register(list)
@is_device_ob... |
import flask_jwtlogin as jwtl
from flask import Flask, request, jsonify, abort
from threading import Thread
from requests import get, post
from json import loads
import time
app = Flask(__name__)
app.config.update({
'JWT_HEADER_NAME': 'access-token',
'JWT_SECRET_KEY': 'you will never guess me',
'JWT_ENCODI... |
#!/usr/bin/python
# 789234
import getpass
import sys
import telnetlib
HOST = "telephone"
user = "administrator"
password = "789234"
tn = telnetlib.Telnet(HOST)
tn.read_until("Login: ")
tn.write(user)
tn.write("\r")
if password:
tn.read_until("Password: ")
tn.write(password)
tn.write("\r")
tn.read_until(... |
# Generated by Django 3.2.3 on 2021-06-05 05:12
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('opportunities', '0002_alter_opportunity_options'),
]
operations = [
migrations.AlterModelOptions(
name='opportunity',
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function, unicode_literals
import os
import unittest
from glob import glob
from flowgen import language
from pypeg2 import parse, some
class PEGMixin(unittest.TestCase):
def assertPEG(self, obj, cls, value=None):
self.assertIsIn... |
import json
import pandas as pd
class Usuario:
def __init__(self, json_usuario=''):
if not json_usuario:
self.email = ''
self.preferencias = {}
else:
self.email = json.dumps(json_usuario["email"]).strip('"')
self.preferencias = {}
json_preferencias = json_usuario["preference"]
for json_prefer... |
import datetime
import pandas as pd
from iexfinance.base import _IEXBase
class ReferenceData(_IEXBase):
@property
def url(self):
return "ref-data/%s" % self.endpoint
@property
def endpoint(self):
raise NotImplementedError
class TradingDatesReader(ReferenceData):
"""
Base cl... |
def producerColor():
with open("todaysTemMax.txt", "r+") as file:
content = file.readline().splitlines()
for i in content:
i = int(i)
if i < 15:
return 'blue'
elif i > 15:
return 'yellow' |
import requests
import scrapbox
def make_request(method, url, params):
request_func = getattr(requests, method, None)
if request_func is None:
raise TypeError('Unknown method: %s' % (method,))
kwargs = {
'headers': {
'User-Agent': scrapbox.USER_AGENT
}
}
params ... |
from grainy.core import PermissionSet, Namespace
class GrainyHandler:
"""
The base class to use for the Grainy Meta class
"""
parent = None
namespace_base = None
namespace_instance_template = "{namespace}.{instance}"
@classmethod
def namespace_instance(cls, instance, **kwargs):
... |
# --------------
#Importing header files
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
#Path of the file
path
#Code starts here
data=pd.read_csv(path)
data.rename(columns={'Total':'Total_Medals'},inplace=True)
data.head(10)
# --------------
#Code starts here
condition_1=data['To... |
'''
Using tuple to save numbers and show it later
'''
num = (int(input('Type a number: ')),
int(input('Type other number: ')),
int(input('Type another number: ')),
int(input('Type the last number: ')))
print('The pair numbers were: ',end='')
for n in num:
if n % 2 == 0:
print(... |
import quokka
from load_image import load_image
fb = load_image('NCSS-logo-68x50.qimz')
quokka.display.fill(1)
quokka.display.blit(fb, 30, 7)
quokka.display.show()
c = 1
while True:
quokka.sleep(1500)
quokka.display.invert(c)
quokka.display.show()
c = (c + 1) % 2
|
from captcha.fields import CaptchaField
from django import forms
from django.db.models import fields
from django.db.models.base import Model
from django.db.models.fields import CharField, DateTimeField
from django.forms import ModelForm, widgets
from django.forms.fields import ChoiceField, ImageField
from django.forms.... |
# -*- coding: utf-8 -*-
#
# Copyright (c) 2019~2999 - Cologler <skyoflw@gmail.com>
# ----------
#
# ----------
from utils import assert_example
def test_build_class_empty():
def func():
class A:
pass
assert_example(func)
def test_build_class_with_methods():
def func():
class ... |
from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.contrib.staticfiles.urls import static, staticfiles_urlpatterns
from . import views
urlpatterns = [
path('admin/', admin.site.urls),
path('account/', include('App_Login.urls')),
path('blog/',... |
def intersect(*args):
res = []
for x in args[0]: # Scan first sequence
if x in res: continue # Skip duplicates
for other in args[1:]: # For all other args
if x not in other: break # Item in each one?
else: ... |
"""
*Select*
"""
import jax.numpy as jnp
from ._operator import Manipulation
__all__ = ["Select"]
class Select(
jnp.select,
Manipulation,
):
def __init__(
self,
*args,
**kwargs,
):
super(Select, self).__init__(
*args,
**kwargs,
)
|
# -*- coding: utf-8 -*-
import re
import logging
from distutils.cmd import Command
from cmds.helper import color
from hangulize import hangulize, get_lang, HangulizeError, \
DONE, SPECIAL, BLANK, ZWSP
class REPLHandler(logging.StreamHandler):
color_map = {'hangulize': 'cyan', 'rewrite': 'gr... |
import sys
from warnings import warn
__all__ = [
'warning',
'unique',
]
def warning(message):
"""
Show error using warnings module. Shows function from stack that called this function.
"""
warn(message, stacklevel=3)
if sys.version_info > (3, 5):
from collections import OrderedDict
... |
# This Python file uses the following encoding: utf-8
"""autogenerated by genpy from mavros_msgs/State.msg. Do not edit."""
import codecs
import sys
python3 = True if sys.hexversion > 0x03000000 else False
import genpy
import struct
import std_msgs.msg
class State(genpy.Message):
_md5sum = "65cd0a9fff993b062b91e354... |
"""
For more details, see the class documentation.
"""
class WikiInfoDTO:
"""
This class represents the data transfer object for a Wikipedia article.
"""
def __init__(self):
"""
Constructor to initialize this object.
"""
self.location = None
self.title = ""
... |
import crazyimports
import tests.test_data.config_json as config
def test_json_file_type():
assert config.__file__.split(".")[-1] == "json"
def test_json_integer_type():
assert isinstance(config.number, int)
def test_json_integer_value():
assert config.number == 42
def test_json_string_type():
a... |
from recollection.tests.classes import SetterTestClass
import os
import recollection
import tempfile
import unittest
# ------------------------------------------------------------------------------
class TestClass(object):
# noinspection PyUnusedLocal
def __init__(self):
foo = 1
bar = ''
# ... |
"""
This file contains the filtering functions that are using to process the
'--include' and '--exclude' command line options. The code in this module is
not specific to the netcfgbu inventory column names, can could be re-used for
other CSV related tools and use-cases.
"""
import ipaddress
import operator
import re
f... |
import docker
from console.app import app
from console.widgets.dialogs import MessageBox
def popup_failure(e, self):
self.close_dialog()
e.trap(docker.errors.APIError)
e = e.value
self.show_dialog(
MessageBox(
e.explanation,
title="HTTP Error: " + str(e.response.statu... |
#!/usr/bin/python3
''' In this example, we have two INA233's, at addresses 0x40 and 0x41
for a hypothetical solar battery charging system.
'''
from ina233 import INA233
R_shunt_ohms = 0.020 # shunt resistor value in Ohms
I_max_amps = 10 # max expected current in Amps
bus = 1 # I2C bus
battery_address = 0x40 # addre... |
import numpy as np
from scipy.interpolate import interp1d
from pims import pipeline
from rixs.process2d import apply_curvature, image_to_photon_events
# Eventually we will create this information from the configuration
# attributes in ophyd.
process_dict_low_2theta = {'light_ROI': [slice(175, 1609), slice(1, 1751)],
... |
# Copyright 2018 The dm_control 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 applicable law or agreed to i... |
from ..broker import Broker
class DeviceSupportWorksheetBroker(Broker):
controller = "device_support_worksheets"
def index(self, **kwargs):
"""Lists the available device support worksheets. Any of the inputs listed may be be used to narrow the list; other inputs will be ignored. Of the v... |
import pytest
import xrp.parser
import xrp.views
class TestResources:
def get_file_view(self, file_path):
with open(file_path) as f:
return self.get_string_view(f.read())
@staticmethod
def get_string_view(string):
parser = xrp.parser.XParser()
parser.parse(string)
... |
counter = 0
cx = 0
cy = 0
nx = 0
ny = 0
def setup():
size(500,500)
smooth()
background(0)
strokeWeight(1)
def draw():
global counter, cx, cy, nx, ny
stroke(200,5)
for si in range(0, 6, 1):
for ci in range(0,6, 1):
nx = ci*80 + 50
ny = si*80 +... |
from harvester_manager import HarvesterManger
from harvester import Harvester
# Simple example of using captcha harvester with one Harvester and printing captcha responses to console.
def main():
url = 'https://www.google.com/recaptcha/api2/demo'
# Scraping sitekey from url
sitekey = Harvester.get_siteke... |
def practice_assert(arg):
print(f"is {arg!r} True?", bool(arg))
assert arg, f"arg == {arg!r}"
print("this will pass ".ljust(40, '='))
practice_assert("abc")
print('''I said "This will pass"''')
try:
print("This will raise an exception ".ljust(40, '='))
practice_assert('')
except AssertionError as e:
print... |
import xml.etree.ElementTree as ET
from datetime import timezone
from ..v3_0 import dto, namespaces as ns
from .serialize_element import serialize_text_element
from ois_api_client.xml.get_full_tag import get_full_tag
def serialize_header(data: dto.BasicHeader) -> ET.Element:
result = ET.Element(get_full_tag(ns.C... |
m, n = [int(x) for x in input().split()]
haydict = {}
for i in range(m):
a, b = input().split()
haydict.update({a:int(b)})
count = 0
while(True):
try:
line = input().split()
if len(line)>0:
if line[0] == ".":
print(count)
count = 0
else... |
"""
INSTALLED_APPS = [
"paper_admin",
"paper_admin.patches.logentry_admin",
...
"logentry_admin",
]
PAPER_MENU = [
...
dict(
label=_("Logs"),
icon="fa fa-fw fa-lg fa-history",
perms="admin.view_logentry",
models=[
"admin.LogEntry"
]
),
]
"... |
"""Virtual Sudoku Game Board
=== Module description
This module contains a Sudoku class that keep tracks of various game variables
and keep track of any errors made my the users
@date: 7/17/2018
@author: Larry Shi
"""
from typing import Union, Tuple, List
__all__ = ['Sudoku', 'CELL_IDX']
# Constants
CELL_IDX = [[0,... |
from discord.ext import commands
import discord
#from discord_slash import cog_ext, SlashContext, manage_commands, error
from tabulate import tabulate
import mariadb
import pydest
class Public(commands.Cog):
def __init__(self, bot):
self.bot = bot
g_guilds = []
# for lang in self.bot.lang... |
from typing import Optional, List, Dict
from .easy_access import EasyAccessDict
class AvatarDetail(EasyAccessDict):
user_type: int
identity_level: int
identity_icon_url: str
class Creator(EasyAccessDict):
default_avatar: bool
province: int
auth_status: int
followed: bool
avatar_url:... |
from .base import *
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
DEBUG = True
STATICFILES_DIRS = [
os.path.join(BASE_DIR, 'static', 'local')
]
# WEBPACK_MANIFEST_FILE = os.path.join(BASE_DIR, '../webpack-stats.local.json') |
from __future__ import annotations
from typing import Any, Optional
from datastax.linkedlists.doubly_linked_list import DoublyLinkedList
from datastax.linkedlists.private_lists import doubly_circular_llist
class DoublyCircularList(doubly_circular_llist.DoublyCircularList,
DoublyLinkedList):... |
"""Test module for the plane endpoint"""
import pytest
from django.urls import resolve, reverse
from src.apps.core.utilities.messages import ERRORS
from tests.fixtures.plane import NEW_PLANE, SEATS
from tests.fixtures.user import USER
PLANE_URL = reverse('flight:plane-list')
GET_A_PLANE_URL = 'flight:plane-detail'
... |
import insightconnect_plugin_runtime
from .schema import SearchInput, SearchOutput, Output, Input
# Custom imports below
from typing import Optional
class Search(insightconnect_plugin_runtime.Action):
def __init__(self):
super(self.__class__, self).__init__(
name="search", description="Search... |
from eth_utils import (
ValidationError,
decode_hex,
to_bytes,
)
import pytest
import rlp
from eth.exceptions import UnrecognizedTransactionType
from eth.rlp.receipts import Receipt
from eth.vm.forks import (
BerlinVM,
LondonVM,
)
from eth.vm.forks.berlin.receipts import (
TypedReceipt,
)
# Th... |
import random
# This is a statistical sampling approximation algorithm that simply simulates the game for a fixed number of dice rolls.
# An exact algorithm would involve calculating the eigenvector of the largest eigenvalue of the transition matrix (which is practical),
# but averaging over all possible permutations... |
#!/usr/bin/env python
# fork multiagent-particle-envs from openai and uncomment the following:
# line 7 in multiagent.multi_discrete.py: # from gym.spaces import prng
# line 14 in multiagent.rendering.py: # from gym.utils import reraise
import argparse
from robot.robot_policy import HierPolicy
from robot.robot_environ... |
import os
PROJECT_PATH = os.path.abspath(os.getcwd())
DEFAULT_DATA_PATH = os.path.abspath(os.path.join(PROJECT_PATH, 'gaia_data'))
|
import tensorflow as tf
from model_fn.model_fn_2d.util_2d.graphs_2d import Graph2D
import model_fn.util_model_fn.keras_compatible_layers as layers
from util.flags import update_params
class GraphConv2MultiFF(Graph2D):
def __init__(self, params):
super(GraphConv2MultiFF, self).__init__(params)
# v... |
#!/usr/bin/env python
#
# __COPYRIGHT__
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
... |
import unittest
import sys
import yaml
from beluga import Client
try:
with open('test/expect_state.yaml') as file:
expect_state = yaml.safe_load(file)
except Exception as e:
print('Exception occurred while loading YAML...', file=sys.stderr)
print(e, file=sys.stderr)
sys.exit(1)
class TestBeru... |
#! /usr/bin/env python
import sys
buf = open(sys.argv[1], "r").read().lower()
if buf.find("pgq consumer") >= 0:
print "-a pgq"
|
import sys
import glob
import argparse
import os
import shutil
import datetime
def main(argv):
parser = argparse.ArgumentParser()
parser.add_argument('--name', required=True, type=str, help='Name of new project')
parser.add_argument('--template', type=str, help='Source template directory')
parser.add_a... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.