content stringlengths 0 894k | type stringclasses 2
values |
|---|---|
import io
import nextcord
async def send_code_block_maybe_as_file(ctx, text):
"""
Sends a code block to the current context.
If it's too long to fit in a single message, it will
instead be sent as a file.
"""
if len(text) > 2000:
file = io.StringIO()
file.writelines(text)
... | python |
import itertools
import binascii
def detect_ecb(s,klen):
blocks = [s[i:i+klen] for i in range(0,len(s),klen)]
pairs = itertools.combinations(blocks,2)
score = 0
for p in pairs:
if p[0] == p[1]:
score += 1
return score > 0
def main():
f = open('8.txt', 'r')
data = f.read()
lines = data.split('\n')... | python |
# Copyright 2017 The Sonnet Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable l... | python |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from collections import Counter, defaultdict
def load_fish(file):
with open(file) as f:
fish = f.read().strip()
fish = fish.split(",")
fish = [int(i) for i in fish]
return fish
def get_num_fish(fish, days):
counts = Counter(fish)
while ... | python |
import chainer
import chainer.functions as F
import chainer.links as L
import inspect
import ast, gast
import itertools
from contextlib import ExitStack
from chainer_compiler.elichika.parser import config
from chainer_compiler.elichika.parser import nodes
from chainer_compiler.elichika.parser import values
from chaine... | python |
import insightconnect_plugin_runtime
from .schema import GetAlertsInput, GetAlertsOutput, Input, Output, Component
# Custom imports below
class GetAlerts(insightconnect_plugin_runtime.Action):
def __init__(self):
super(self.__class__, self).__init__(
name='get_alerts',
des... | python |
from pydantic import BaseModel
from typing import Optional
import typing as T
class Member(BaseModel):
user_id: int
nickname: str
card: T.Optional[str]
sex: str
age: int
area: str
level: str
role: T.Optional[str]
title: T.Optional[str]
# 以下是 getGroupMemberInfo 返回的更多结果
group_... | python |
import config as config
import utils.log as log
# import tests cases
import test_api_config
import test_api_crush_map
import test_api_crush_node
import test_api_crush_rule_set
import test_api_crush_rule
import test_api_crush_type
import test_api_logs
import test_api_mon
import test_api_pool
import test_api_request
imp... | python |
# -*- coding: utf-8 -*-
#
# Copyright (c) 2016 - 2022 -- Lars Heuer
# All rights reserved.
#
# License: BSD License
#
"""\
EPC QR Codes.
Test against issue <https://github.com/heuer/segno/issues/55>.
"""
from __future__ import absolute_import, unicode_literals
import decimal
import pytest
from segno.helpers import mak... | python |
import rope.base.builtins
import rope.base.codeanalyze
import rope.base.pynames
from rope.base import ast, exceptions, utils
from rope.refactor import patchedast
class Scope(object):
def __init__(self, pycore, pyobject, parent_scope):
self.pycore = pycore
self.pyobject = pyobject
self.pare... | python |
import websocket
import json
import RPi.GPIO as GPIO
GPIO.setmode(GPIO.BCM) # set board mode to Broadcom
GPIO.setup(17, GPIO.OUT) # set up pin 17 TV
GPIO.setup(18, GPIO.OUT) # set up pin 18 Lights
GPIO.setup(22, GPIO.OUT) # set up pin 12 A/C
GPIO.setup(27, GPIO.OUT) # set up pin 27 Alarm
GPIO.output(17, 0) # ... | python |
from replays_fetching.replay_fetcher import ReplayFetcher
replay_fetcher = ReplayFetcher()
replays = replay_fetcher.get_replays()
for index in range(len(replays)):
print('Replay #{0}: '.format(index) + str(replays[index]))
| python |
# 2.3.5 Example: Range Class
class Range:
"""A class that mimic's the built-in range class."""
def __init__(self,start,stop=None,step=1):
"""Initialize a Range instance.
Semantics is similar to built-in range class.
"""
if step == 0:
raise ValueError('step cannot b... | python |
# Copyright 2018 Alibaba Group Holding Limited. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by ... | python |
#
# Generated with RIFLEXDynamicCalculationParametersBlueprint
from dmt.blueprint import Blueprint
from dmt.dimension import Dimension
from dmt.attribute import Attribute
from dmt.enum_attribute import EnumAttribute
from dmt.blueprint_attribute import BlueprintAttribute
from sima.sima.blueprints.moao import MOAOBluepr... | python |
# -*- coding: utf-8 -*-
from permutive.exceptions import PermutiveApiException
from .util import none_default_namedtuple
from .base import Resource
User = none_default_namedtuple('User', 'id, custom_id, properties, updated')
class UserResource(Resource):
def create(self):
"""
Creates a new user ... | python |
# control.applications - Controller for comodit Applications entities.
# coding: utf-8
#
# Copyright 2010 Guardis SPRL, Liège, Belgium.
# Authors: Laurent Eschenauer <laurent.eschenauer@guardis.com>
#
# This software cannot be used and/or distributed without prior
# authorization from Guardis.
from __future__ import a... | python |
foods = ('yu','wa','fan','cai','tang')
for foods2 in foods:
print(foods2)
foods = ('yu','wa','fan','cai','tang')
print(foods)
foods = ('yu','wa','fan','cai','tang','xia')
print(foods)
# 4 | python |
import dojo.dojo as d
def test():
print(dir(d))
assert(d.test_function() is True)
| python |
"""
Unittests for staros plugin
Uses the mock_device.py script to test the plugin.
"""
__author__ = "dwapstra"
import unittest
from unicon import Connection
from unicon.core.errors import SubCommandFailure
class TestStarosPluginConnect(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.c... | python |
# -------------------------------------------------------------------------------
# Copyright (c) 2017, Battelle Memorial Institute All rights reserved.
# Battelle Memorial Institute (hereinafter Battelle) hereby grants permission to any person or entity
# lawfully obtaining a copy of this software and associated docum... | python |
import binascii
from web3.auto import w3
with open("/home/koshik/.ethereum/rinkeby/keystore/UTC--2018-06-10T05-43-22.134895238Z--9e63c0d223d9232a4f3076947ad7cff353cc1a28") as keyfile:
encrypted_key = keyfile.read()
private_key = w3.eth.account.decrypt(encrypted_key, 'koshik93')
print(binascii.b2a_hex(private_k... | python |
# Copyright 2021 Ian Eborn
# A sub-class of the "SimpleThirdPersonCamera" class, providing one implementaton of
# the collision-related elements of the camera-system.
#
# Specifically, this class primarily implements the "setupCollision" and "getNearestCollision" methods,
# using Panda3D's built-in collision system.
#... | python |
from hms_workflow_platform.core.queries.base.base_query import *
class EncounterQuery(BaseQuery):
def __init__(self, site):
super().__init__()
self.adapter = self.get_adapter(site)
self.query = self.adapter.query
self._site = site
def encounter_create(self, date_obj):
... | python |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Email: chenwx716@163.com
# DateTime: 2019-08-06 22:08:14
__author__ = 'chenwx'
import json
import requests
app_url = "http://127.0.0.1:9002"
req_url = app_url + "/api/v2/local"
json_headers = {"content-type": "application/json"}
class ShowLocal(object):
"""docstr... | python |
#42) Coded triangle numbers
#The nth term of the sequence of triangle numbers is given by, tn = (1/2)*n*(n+1); so the first ten triangle numbers are:
#1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ...
#By converting each letter in a word to a number corresponding to its alphabetical position and adding these values we form a wo... | python |
# Authors: Jose C. Garcia Alanis <alanis.jcg@gmail.com>
#
# License: BSD-3-Clause
# -- WIP -- {
fig, ax = plt.subplots()
im = ax.imshow(np.median(channel_corrs, axis=0), cmap="YlGn", )
# Create colorbar
cbar = ax.figure.colorbar(im, ax=ax)
cbar.ax.set_ylabel('Channels correlation', rotation=-90, va="bottom")
# Show al... | python |
class Aws_Utils:
@staticmethod
def run_code_in_lambda(code):
file_Path = 'temp_code/code.py'
temp_Dir = 'temp_code'
zip_file = 'temp_code.zip'
def create_temp_files():
if not os.path.exists(temp_Dir):
os.mkdir(temp_Dir)
with open(file_P... | python |
#
# resolution(KB, q): Given a propositional knowledge base and query, return
# whether the query can be inferred from the knowledgebase using resolution.
# The implementation is more efficient than pl_resolution in the AIMA code.
# KnowledgeBasedAgent: An abstract class that makes decisions to navigate
# through a w... | python |
from django.db import models
from ...apps import UFDLCoreAppConfig
class LicenceQuerySet(models.QuerySet):
"""
A query-set of data-set licences.
"""
pass
class Licence(models.Model):
"""
The licence for a data-set.
"""
# The name for the licence
name = models.CharField(max_lengt... | python |
"""
This script contains all the functions related to the model
"""
import tensorflow as tf
import numpy as np
import random
from math import ceil
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Flatten, Conv2D, LeakyReLU, Dropout
from game import MOVES_POSSIBLE, ALL_BLOCK_PO... | python |
from Templates.make_excel import make2exel
import Main.Tenderplan.participants2excel as p2ex
import openpyxl
excel_name = r'E:\Лиды_экспорт.xlsx'
make2exel(
['Название компании', 'ИНН', 'Список выигранных тендеров', 'Список остальных тендеров c участием'], excel_name)
wb = openpyxl.load_workbook(excel_name)
she... | python |
#!/usr/bin/env python
from HTMLParser import HTMLParser
import re
import os
import sys
import string
class Html2MarkdownParser(HTMLParser):
def __init__(self):
self._markdown = ''
self._tag_stack = []
self._tag_attr_data = {}
self._handled_tag_body_data = ''
self._converti... | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import division, print_function
def pe5(n=20):
"""
What is the smallest number divisible by each of the numbers 1 to 20?
>>> pe5()
232792560
"""
if n < 2:
return 1
p = 2
m = [2]
for x in range(3, n + 1):
... | python |
import aiohttp
import argparse
import asyncio
import ssl
from urllib.parse import urlsplit
from bs4 import BeautifulSoup
from sitemap.utils import write_text_sitemap, clean_link
# Have these at global scope so they remain shared.
urls = []
results = []
def sitemap(url, verbose=False):
""" Main mapping functio... | python |
import list_wifi_distances
import requests
def report(rogue_mac):
pi_id = 8
distance = list_wifi_distances.get_network(rogue_mac.upper())
print(distance)
requests.post("http://10.10.10.93:8000/report", data={'id':pi_id, 'dist': distance})
| python |
import logging
from cellfinder.figures import heatmap
def run(args, atlas, downsampled_shape):
logging.info("Generating heatmap")
heatmap.run(
args.paths.downsampled_points,
atlas,
downsampled_shape,
args.brainreg_paths.registered_atlas,
args.paths.heatmap,
smo... | python |
# Generated by Django 3.1.2 on 2021-04-08 02:58
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('bpmn', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Diagram',
fi... | python |
"""Aramaic Bible Module tool"""
from pathlib import Path
import click
from abm_tools.sedra.bible import parse_sedra3_bible_db_file
from abm_tools.sedra.db import from_transliteration, parse_sedra3_words_db_file, sedra4_db_word_json
@click.group()
def tool():
"""Tools for generating Aramaic bible software module... | python |
#!/usr/bin/env python
>>> import snmp_helper
c. Create a script that connects to both routers (pynet-rtr1 and pynet-rtr2) and prints out both the MIB2 sysName and sysDescr.
| python |
##
##
##
import queue
class BundGrammarQueue:
def __init__(self):
self.q = {}
self.default_queue_name = "__root__"
self.createLIFO("__root__")
def queue(self, name, auto_create=True):
if name not in self.q:
if auto_create:
self.default_queue_name = na... | python |
import vcr
from umm.cli.client import umm_request
from umm.server.utils import setup_folder
@vcr.use_cassette()
def test_umm_request():
setup_folder()
resp = umm_request([])
assert resp == {"commands": []}
| python |
"""
Copyright (c) 2016-present, Facebook, Inc.
All rights reserved.
This source code is licensed under the BSD-style license found in the
LICENSE file in the root directory of this source tree. An additional grant
of patent rights can be found in the PATENTS file in the same directory.
"""
"""Fabric commands for pack... | python |
def fun(x: int) -> str:
return str(x)
class SomeClass:
def meth(self, x: int) -> str:
return str(x)
| python |
from typing import (
Any,
Callable,
Dict,
Iterable,
Iterator,
NamedTuple,
Optional,
Set,
)
from contextlib import contextmanager
import pendulum
import prefect
from prefect.core import Edge, Flow, Task
from prefect.engine.result import Result
from prefect.engine.results import ConstantR... | python |
''' Menu Module
Module to deal with menus and buttons. Used initially for start menu.
Can be extended if required to create pause and other menues throughout
the game.
@author: Robert (unless stated otherwise)
'''
import pygame
from classes.text import Text
from classes.sfxbox import SFXBox
button_... | python |
from loguru import logger
import cv2
import os
import pickle
import typing
import numpy as np
from sklearn.svm import LinearSVC
from stagesepx.classifier.base import BaseModelClassifier
from stagesepx import toolbox
from stagesepx.video import VideoFrame
from stagesepx import constants
class SVMClassifier(BaseModelC... | python |
from fastapi import APIRouter
from client.api.api_v1.endpoints import twitter, disk_space
router = APIRouter()
router.include_router(disk_space.router, prefix="/diskspace", tags=["diskspace"])
router.include_router(twitter.router, prefix="/twitter", tags=["twitter"])
| python |
import socket
import imagezmq
import cv2
import time
sender = imagezmq.ImageSender(connect_to='tcp://localhost:5555')
sender_name = socket.gethostname() # send your hostname with each image
# image = open("C:/Users/H S/PycharmProjects/Kivy/Untitled.png", 'rb')
image = cv2.imread("C:/Users/H S/PycharmProjects/Kivy/Unt... | python |
import zerorpc
client = zerorpc.Client()
client.connect("tcp://127.0.0.1:4242")
num = 7
result = client.double(num)
print("Double", num, "is", result)
| python |
from Components.Converter.Converter import Converter
from Components.config import config
from Components.Element import cached
from Poll import Poll
from enigma import eDVBVolumecontrol
class ArcticVolume(Poll, Converter):
def __init__(self, val):
Converter.__init__(self, val)
Poll.__... | python |
###############################################################################
# WaterTAP Copyright (c) 2021, The Regents of the University of California,
# through Lawrence Berkeley National Laboratory, Oak Ridge National
# Laboratory, National Renewable Energy Laboratory, and National Energy
# Technology Laboratory ... | python |
import os
import csv
import timeit
from datetime import datetime
import numpy
import logging
import coloredlogs
import numpy as np
import argparse
import copy
import json
import re
import sys
import onnxruntime
from onnx import numpy_helper
from perf_utils import *
import pprint
import time
from float16 import *
# impo... | python |
from django.db import models
# Create your models here.
class Person(models.Model):
name = models.CharField(max_length=255)
surname = models.CharField(max_length=255)
image = models.ImageField(upload_to='person_images')
| python |
import os
import click
from flask import current_app
from sqlalchemy import text
from app import db
def register(app):
@app.cli.group()
def translate():
"""Translation and localization commands."""
pass
@translate.command()
@click.argument('lang')
def init(lang):
"""In... | python |
from __future__ import annotations
import attr
__all__ = ("AllowedMentions",)
@attr.s(kw_only=True)
class AllowedMentions:
"""Represents an allowed mentions object.
This is used to determine the allowed mentions of any messages being sent from the client's user.
Parameters
----------
everyone:... | python |
import csv
class PlayerThumbnails:
def getThumbnailsID():
ThumbnailsID = []
with open('Logic/Files/assets/csv_logic/player_thumbnails.csv') as csv_file:
csv_reader = csv.reader(csv_file, delimiter=',')
line_count = 0
for row in csv_reader:
if lin... | python |
"""
This file contains all the HTTP routes for basic pages (usually HTML)
"""
from flask import Blueprint, render_template, request
import _config as config
pages = Blueprint('controller', __name__)
@pages.route('/')
def index():
"""
A basic landing page for this web service
:return: HTTP Response (HTM... | python |
"""The Snooty documentation writer's tool."""
__version__ = "0.9.6.dev"
| python |
#!/usr/bin/env python
from subprocess import Popen
from subprocess import PIPE
class ChromeHtmlToPdf():
def __init__(self, url, output_path=None, verbose=False):
'''
Initialize class with google chrome parameters
Params:
Return:
'''
... | python |
from streaming.app import app
from streaming.config import config
from streaming.phishtank.api import Reported
# Topics
reports_topic = app.topic('phishtank-reports')
# Tables
states_table = app.Table('phishtank-state', default=str)
@app.agent(reports_topic)
async def get_phishtank_reports(states):
async for sta... | python |
#!/usr/bin/python
# -*- coding: UTF-8 -*
from common.common_time import get_system_datetime
from db.base import DbBase
from db.connection_pool import MysqlConn
import copy
import datetime
from utils.status_code import response_code
from config import configuration
import traceback
import json
import os
from config impo... | python |
from .api import process_large_corpus, process_small_corpus, \
process_belscript, process_pybel_graph, process_json_file, \
process_pybel_neighborhood, process_cbn_jgif_file, \
process_bel_stmt
| python |
from distutils.core import setup
version = "1.2"
setup(
name='chainee',
packages=['chainee'],
version=version,
license='MIT',
description='Chain your predicates, easy way.',
author='Yaroslav Pankovych',
author_email='flower.moor@gmail.com',
url='https://github.com/ypankovych/chainee',
... | python |
# The idea here is to store all the different things you need for Code in one module
# Code can then import the module and call whatever functions are needed
# R. Sheehan 27 - 10 - 2020
MOD_NAME_STR = "Measurement"
# import the necessary modules
import board
import time
import digitalio
from analogio import AnalogOut... | python |
import pytest
import main
from time import time
import hmac
import hashlib
from unittest.mock import Mock
from unittest.mock import MagicMock
def test_valid_signature():
timestamp = int(time())
slack_signing_secret = 'abcdefg'
main.slack_signing_secret = slack_signing_secret
req_body = 'abcdefgabcdefg... | python |
from matchbook.apiclient import APIClient
from matchbook.exceptions import MBError
__title__ = 'matchbook'
__version__ = '0.0.9'
| python |
# -*- coding: utf-8 -*-
"""
Test Generic Map
"""
import os
import pytest
import numpy as np
import astropy.units as u
from astropy.coordinates import SkyCoord
import matplotlib.pyplot as plt
import sunpy
import sunpy.map
import sunpy.coordinates
import sunpy.data.test
from sunpy.tests.helpers import figure_test
tes... | python |
# -*- Mode: Python -*-
# vi:si:et:sw=4:sts=4:ts=4
# this should be fine, but failed with pychecker 0.8.18 on python 2.6
def func():
d = { 'a': 1, 'b': 2}
print d.keys()
| python |
import torch
import torch.nn as nn
import torch.nn.init as init
import numpy as np
import math
import torchvision.utils as tvu
from torch.autograd import Variable
import matplotlib.pyplot as plt
def generate_images(generator, centers, num_clusters, alpha, z_dim, device):
idx_centers = torch.from_numpy(np.random.c... | python |
import os
import numpy as np
def _download_and_extract(url, path, filename):
import shutil, zipfile
import requests
fn = os.path.join(path, filename)
while True:
try:
with zipfile.ZipFile(fn) as zf:
zf.extractall(path)
print('Unzip finished.')
... | python |
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
__author__ = 'Chao Wu'
r'''
python C:\Users\cwu\Desktop\Software\Papers\pH_effect\plot_ph_effect_contour\plot_contour.py
'''
import os
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
EPCS_FILE = 'path\to\epcs.xlsx'
DGPS_FILE = 'path\to\dgps.xl... | python |
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
from matplotlib.patches import Polygon
import numpy as np
import stader
d = stader.load_aircraft('b747_flight_condition2')
ac = stader.Aircraft(d)
msec = 15
dt = msec/1000
show_state = False
if show_state:
fig = plt.figure(figsize=(1... | python |
import os.path
from lsst.meas.base import CircularApertureFluxAlgorithm
config.measurement.load(os.path.join(os.path.dirname(__file__), "apertures.py"))
config.measurement.load(os.path.join(os.path.dirname(__file__), "kron.py"))
config.measurement.load(os.path.join(os.path.dirname(__file__), "convolvedFluxes.py"))
co... | python |
import pyglet
from pyglet.gl import *
blueDot = pyglet.resource.image('blue-dot.png')
redDot = pyglet.resource.image('red-dot.png')
class Window(pyglet.window.Window):
"""docstring for Window"""
def __init__(self):
print("Init Window")
super(Window, self).__init__(500, 400, vsync=False)
... | python |
# -*- coding:utf-8 -*-
import logging
from flask import request
from flask_restx import Namespace
from app.spider.csdn.csdn import CSDN
from app.spider.toutiao.toutiao_hotnews import ToutiaoNews
from app.api.util.base_resource import BaseResource
from app.api.util.web_response import WebResponse
from app.api.util.web... | python |
"""Singleton Class"""
# standard library
import threading
class Singleton(type):
"""A singleton Metaclass"""
_instances = {}
_lock = threading.Lock()
def __call__(cls, *args, **kwargs):
"""Evoke call method."""
with cls._lock:
if cls not in cls._instances:
... | python |
def print_two(*args): # :TODO *args are for funcs and argv for inputs
arg1, arg2 = args
print('arg1: %r, arg2: %r' % (arg1, arg2))
def print_two_again(arg1, arg2):
print('arg1: %r, arg2: %r' % (arg1, arg2))
print_two("zdr", "zdr")
print_two_again("zdr", "zdr")
| python |
import os
import sys
import time
import requests
from py2neo import Graph, Node, Relationship
graph = Graph()
graph.run("CREATE CONSTRAINT ON (u:User) ASSERT u.username IS UNIQUE")
graph.run("CREATE CONSTRAINT ON (t:Tweet) ASSERT t.id IS UNIQUE")
graph.run("CREATE CONSTRAINT ON (h:Hashtag) ASSERT h.name IS UNIQUE")
... | python |
import os
import shutil
def create_analysis_folder(folder_name):
if not os.path.exists(folder_name):
os.makedirs(folder_name)
shutil.copy('ffield', folder_name)
shutil.copy('parameters', folder_name)
| python |
from collections import defaultdict
import boto3
import click
from halo import Halo
from termcolor import colored, cprint
from ..app import app
from ..utils import formatted_time_ago
def task_id(task_detail: dict) -> str:
tags = {t["key"]: t["value"] for t in task_detail["tags"]}
try:
return tags["p... | python |
from setuptools import setup
with open("README.md", "r", encoding="utf-8") as f:
long_description = f.read()
setup(
name="sku",
version="0.2",
description="scikit-learn Utilities",
long_description=long_description,
long_description_content_type="text/markdown",
url="https://github.com/myt... | python |
# sim_core/views.py
#################
#### imports ####
#################
from app import app
from flask import render_template, Blueprint
from logger import logger
from flask import current_app
################
#### config ####
################
sim_core_blueprint = Blueprint('sim_core', __name__, static_folder=... | python |
from unittest import TestCase
from demands.pagination import PaginatedResults, PaginationType
class PaginationTestsMixin(object):
args = (1, 2, 3)
kwargs = {'one': 1, 'two': 2}
def get(self, start, end, *args, **kwargs):
self.assertEqual(args, self.args)
self.assertEqual(kwargs, self.kwa... | python |
N, arr = int(input()), input().split()
print(all([int(i) > 0 for i in arr]) and any([i == i[::-1] for i in arr])) | python |
import tkinter as tk
import tkinter.filedialog as fd
import src.helper.gui as hg
from src.image.extractor import Extractor
from src.helper.file import File
class ImageExtractForm(tk.Frame):
def __init__(self, parent, controller):
tk.Frame.__init__(self, parent)
self.controller = controller
... | python |
import copy
import operator
from functools import cached_property, reduce
from typing import Dict, List, Optional
import torch
import torch.nn as nn
from torch import Tensor
from torch.nn.functional import mse_loss
from torch.optim import Adam
from ai_traineree import DEVICE
from ai_traineree.agents import AgentBase
... | python |
# -*- coding: utf-8 -*-
"""
flask_jsonschema
~~~~~~~~~~~~~~~~
flask_jsonschema
"""
import os
from functools import wraps
try:
import simplejson as json
except ImportError:
import json
from flask import current_app, request
from jsonschema import ValidationError, validate
class _JsonSchema(obj... | python |
from tortoise.contrib.pydantic import pydantic_model_creator
from typing import Optional
from pydantic import BaseModel
from db.models import Meals
MealsInSchema = pydantic_model_creator(
Meals, name="MealIn", exclude_readonly=True
)
MealsOutSchema = pydantic_model_creator(
Meals, name="MealOut", exclude=["c... | python |
"""
Host Guest Complex
==================
"""
from __future__ import annotations
import typing
from collections import abc
from ...molecules import BuildingBlock
from ...reactions import GenericReactionFactory
from ..topology_graph import (
ConstructionState,
NullOptimizer,
Optimizer,
TopologyGraph,... | python |
import bs4
import json
import requests
import time
from utils import (get_content, get_soup, save_json, load_json)
MANGA_SEARCH_URL = 'https://myanimelist.net/manga.php?type=1&q='
# load series information
all_series = load_json("data.json")
for series in all_series:
# search on MyAnimeList
query_soup = get... | python |
from random import randint
from game_map.direction import Direction
from game_map.rect import Rect
class Room(Rect):
"""
A Room is just a Rect that can tell you where its walls are
"""
def __init__(self, x, y, width, height):
super(Room, self).__init__(x, y, width, height)
def get_wall(se... | python |
"""
# Sample code to perform I/O:
name = input() # Reading input from STDIN
print('Hi, %s.' % name) # Writing output to STDOUT
# Warning: Printing unwanted or ill-formatted data to output will cause the test cases to fail
"""
# Write your code here
from collections import deque, defaultdict
... | python |
import unittest
from mock import Mock
from foundations_events.producers.jobs.run_job import RunJob
class TestProducerRunJob(unittest.TestCase):
def setUp(self):
from foundations_internal.foundations_job import FoundationsJob
self.route_name = None
self.message = None
self._fou... | python |
import os
TEST_DIR = os.path.realpath(os.path.dirname(__file__))
| python |
# Copyright (c) 2017-2019 Intel Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed... | python |
import logging
from logger_config import configure_logging
logger_name = 'root_logger'
configure_logging(logger_name, log_dir='logs')
logger = logging.getLogger(logger_name)
logger.warning('This is warning')
logger.error('This is exception')
logger.info('This is info message')
logger.debug('This is debug message')
| python |
# All edits to original document Copyright 2016 Vincent Berthiaume.
#
# Copyright 2015 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# ht... | python |
__version__ = '3.0.8'
__buildinfo__ = {'branch': 'BRANCH_NOT_SET', 'last_commit': 'COMMIT_NOT_SET'} | python |
from dash import dcc
import dash_bootstrap_components as dbc # pip install dash-bootstrap-components
from dash import Input, Output, State, html
from app import app
# Lotties: Emil at https://github.com/thedirtyfew/dash-extensions
url_sunlight = "https://assets8.lottiefiles.com/packages/lf20_bknKi1.json"
url_earth = ... | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.