content
stringlengths
5
1.05M
import os from contextlib import contextmanager from tempfile import TemporaryDirectory from tests import Mocks @contextmanager def temporary_test_dir(): oldpwd = os.getcwd() with TemporaryDirectory('test/') as td: try: os.chdir(td) yield finally: os.chdir(...
import logging import re import time import global_vars from utils import DBAgent, extract_table_from_sql, input_sql_processing class WDR: __tablename__ = 'wdr' def __init__(self, db_port, db_type): self.port = db_port self.db_type = db_type def extract_index(self, databa...
import pandas as pd import os from util.file import create_if_not_exist pd.set_option('display.max_rows', 500) pd.set_option('display.max_columns', 500) pd.set_option('display.width', 1000) import numpy as np class Result: default_column_names = ['dataset', 'task', 'method', 'acc', 'time'] def __init__(self, ...
import sys from .modules.api_support import ApiSupport from .modules.output.output import MinimalOut from .lib.gravity import Module, Dependency from .lib.module_arguments import ModuleArgumentParser __all__ = ["Api"] class Api(Module): description: str = "Universum API" api_support_factory = Dependency(Api...
from flask import Flask from flask_sqlalchemy import SQLAlchemy from config import ProductionConfig app = Flask(__name__) app.config.from_object(ProductionConfig) db = SQLAlchemy(app) from app import views
from typing import Tuple, List import numpy as np import tensorflow as tf from webdnn.frontend.tensorflow.converter import TensorFlowConverter from webdnn.frontend.tensorflow.util import unary_op_handler, check_data_format, convert_odd_padding_to_concat, parse_padding from webdnn.graph.axis import Axis from webdnn.gr...
from django.apps import AppConfig class OpsdocsConfig(AppConfig): name = 'opsdocs'
#py_regex_5.py import re re.sub regex = 'cubs' change_to = "CUBS" target = 'If the cubs actually win, will they still be the cubs?' result = re.sub(regex, change_to, target) if result: print(result)
""" LINK: https://leetcode.com/problems/longest-common-prefix/ Write a function to find the longest common prefix string amongst an array of strings. If there is no common prefix, return an empty string "". Example 1: Input: strs = ["flower","flow","flight"] Output: "fl" Example 2: Input: strs = ["dog","racecar","...
import queue as Q ## ##def A_Star(g, s_node, g_node, priority = 0, path = []): ## pq = queue.PriorityQueue(); ## pq.put((priority, (s_node, 0))); ## while(not pq.empty()): ## u = pq.get(); ## pq = queue.PriorityQueue(); ## if u[1][0] == g_node: ## path.append(g_node); ## ...
#!/usr/bin/env python from distutils.core import setup setup(name='conohactl', version='0.1', description='Interface for manage VPS on ConoHa', author='Yuuki Enomoto', author_email='uki@e-yuuki.org', license='public domain', url='https://github.com/user340/tools/www/conoha', ...
import nltk nltk.download('vader_lexicon')
import base64 import json import pytest import main def event(func): def wrapper(): data = func() encoded = base64.b64encode(json.dumps(data).encode()) return {'data': encoded} return wrapper @pytest.fixture @event def cloud_source_repo(): return { "status": "WORKING", ...
import unittest from paddle.vision.models import mobilenet_v2 import numpy as np from paddle.vision.models.resnet import resnet50 import interpretdl as it from tests.utils import assert_arrays_almost_equal class TestGradCAM(unittest.TestCase): def test_cv(self): paddle_model = mobilenet_v2(pretrained=Tr...
import unittest from pterradactyl.commands.state import StateCommand from mock import patch class TestEnvCommands(unittest.TestCase): def test_env_commands(self): with patch('pterradactyl.commands.manifest.ManifestCommand.__init__') as base_mock: with patch('pterradactyl.commands.state.Manife...
# # @lc app=leetcode id=164 lang=python3 # # [164] Maximum Gap # # @lc code=start import collections class Solution: def maximumGap(self, nums): if len(nums) < 2: return 0 if len(nums) == 2: return abs(nums[1] - nums[0]) mx = max(nums) mi = min(nums) ...
import numpy import pyopencl as cl from simple_gene import SimpleGene class SimpleChromosome: # SimpleChromosome - a chromosome contains a list of Genes. # __genes - a list of Genes # __name - name of the chromosome # dna - an listed of Gene's dna # dna_total_length - sum of the lenght of all gene...
class EnvInit: """ Env Init constants """ CMD_DETACHED_STREAMS = "./streams"
""" kml_templates various templates for writting GNOME KML files """ LeStyles = """ <Style id="RedDotIcon"> <IconStyle> <scale>0.2</scale> <color>ff0000ff</color> <Icon> <href>dot.png</href> </Icon> <hotSpot x="0.5" y="0.5" xunits="fraction" yunits...
#!/usr/bin/python3 # -*- coding: utf-8 -*- import unittest import numpy as _np from apollon.audio import loadwav class Test_ModulAudio(unittest.TestCase): def setUp(self): self.x = loadwav('/Users/michael/audio/beat.wav') def test_AudioDataAttributes(self): c = isinstance(self.x.fs, int) ...
import time BRANCH_NAME = "025-trackedbranch" with repository.workcopy() as work, frontend.signin(): REMOTE_URL = instance.repository_url("alice") def wait_for_branch(branch_name, value): instance.synchronize_service("branchtracker") try: output = work.run(["ls-remote", "--exit-c...
from preprocess.MySentenceStemmer import MySentenceStemmer from unittest import TestCase class TestSentenceStemmer(TestCase): def setUp(self): self.st = {} self.stemmer = MySentenceStemmer(self.st) def test_stem(self): str = " Hello, how are you?" result = ['Hello', ',', 'how', ...
import pytest import os.path from numpy.testing import assert_allclose from astropy.io.fits import Header from ..ds9_region_parser import ds9_shape_defs from ..region_numbers import CoordOdd, CoordEven from .. import wcs_converter from ..wcs_helper import _calculate_rotation_angle rootdir = os.path.join(os.path.dirnam...
import asyncio import discord import uvloop from discord.commands import slash_command from discord.ext import commands class InviteV1(commands.Cog): def __init__(self, bot): self.bot = bot @slash_command(name="rininvite", description="Invite links for Rin") async def invite(self, ctx): ...
#!/usr/bin/python3 from numpy.random import random from numpy.random import randint from numpy import array from numpy import column_stack from numpy import row_stack from numpy import cos from numpy import sin from numpy import sort from numpy import pi from modules.utils import random_points_in_circle from modules...
""" More about Pytest Fixtures: https://docs.pytest.org/en/latest/fixture.html """ from RTP_python_template.list_util import mean, split import pytest import numpy as np mean_list = [ ([1, 2, 3, 4, 5], 3), ([0, 2, 4, 6], 3), ([1, 2, 3, 4], 2.5), (range(1, 1000000), 1000000/2.0) ] @pytest.mark.sk...
import torch import torch.nn as nn from network.architecture import * class Decom(nn.Module): def __init__(self): super().__init__() self.decom = nn.Sequential( get_conv2d_layer(in_c=3, out_c=32, k=3, s=1, p=1), nn.LeakyReLU(0.2, inplace=True), get_conv...
#!/usr/bin/env python3 # encoding: utf-8 import threading import queue import os import json import proxy from initscrapy import Ingscrapy # import gbrarscrapy # import doubanscrapy '''写一个或多个全局列表(字典),保存数据,并将内容写入文件''' # temp_dict = dict() temp_list = list() score_dict = dict() class Scrapy_thread(threading.Thread, ...
#credits tanaywhocodes from turtle import * speed(1) shape("turtle") bgcolor("grey") def belt(): rt(10) for i in range(6,17): pensize(i) fd(3) pensize(12) lt(15) fd(18)#25 lt(12) fd(22)#25 def legs(): setheading(270) fd(45) circle(30,180,7) fd(45)...
import setuptools with open("README.md", "r") as fh: long_description = fh.read() setuptools.setup( name="c4sfcensusgeocoder", version="0.0.12", author="Data Science Working Group - Code for San Francisco", author_email="datascience@codeforsanfrancisco.org", description="Censusgeocoder", l...
from django.shortcuts import render from pagination import models from utils import page2 def index(request): # page 的使用 # data = models.Book.objects.all() # page_current = request.GET.get('page') # page_obj = page.Pagination(page_current, data.count(), '/book_list/') # data_list = data[page_obj....
""" Copyright (c) 2021 Philipp Scheer """ import ssl import time import random import hashlib import hashlib, binascii, os from jarvis import Config class Security: """ A Security class that provides hashing and id functions """ @staticmethod def password_hash(pwd: str): """ Hash...
# Create your tests here. from django.test import TestCase from .models import Profile,Project from django.contrib.auth.models import User # Create your tests here. class ProfileTest(TestCase): def setUp(self): ''' run before test ''' user1=User(username='msyoki') user1.sav...
#!/usr/bin/env python -O # -*- coding: utf-8 -*- # # tests.unit._dao.TestRTKSurvival.py is part of The RTK Project # # All rights reserved. """ This is the test class for testing the RTKSurvival module algorithms and models. """ import sys from os.path import dirname sys.path.insert(0, dirname(dirname(dirname...
#!/usr/bin/env python3 import mdmdrupalutil as mdu import os import shutil import textwrap from pyprojroot import here from mdmdrupaldb import STAFF AUTHOR_TEMPLATE=textwrap.dedent('''\ --- # Display name title: {staff_name} {staff_surname} # Custom keyword (e.g. to be used by md2bib.py) short_name: {sho...
import unittest from block import * class TestBlock(unittest.TestCase): def setUp(self): pass def tearDown(self): pass def testRepresentation(self): # Test repr b = Block(2,8) expectedString = "Block(%d, %d)"%(b.id,b.data) rep = repr(b) self.assert...
from numpy.testing import assert_ import os import uuid from pylearn2.utils.string_utils import find_number from pylearn2.utils.string_utils import preprocess from pylearn2.utils.string_utils import tokenize_by_number from pylearn2.utils.string_utils import number_aware_alphabetical_key def test_preprocess(): try...
import mysql.connector as mysql from binance import Client, ThreadedWebsocketManager, ThreadedDepthCacheManager import pandas as pd import sqlalchemy as sq from get_data_api_b import get_pd_daily_histo import mplfinance as mpf import MySQLdb as mysql2 # enter your server IP address/domain name HOST = "82.66.6...
from main import * def get_all_users(id): vals = ref.child(id).get() users = [] for name, info in vals.items(): users.append(str({"Name": name, "PIN": str(info["PIN"]), "is_admin": info["is_admin"]})) return " / ".join(x for x in users) def remove_user(id, name): try: ref = db.reference("/" + id) ...
import nanome from nanome._internal._ui import _TextInput from . import UIBase class TextInput(_TextInput, UIBase): """ | Represents a text input, where the user can input text """ HorizAlignOptions = nanome.util.enums.HorizAlignOptions def __init__(self): _TextInput.__init__(self) ...
# Generated by Django 2.1.8 on 2019-10-04 22:54 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ('teams', '0001_initial'), migrations.swappable_dependency(settin...
# Author: Dhaval Harish Sharma # RED ID: 824654344 # Currently enrolled in the class """Assignment 4: Implement a flyweight pattern for characters. There is a character class that stores only the unicode code point of the character. There is a single point of access to the same flyweight factory. The flyweight factory ...
# Generated by Django 2.2.9 on 2020-08-13 14:05 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] ope...
class Tile: def __init__(self, y, x, grid): self.y = y self.x = x self.grid = grid self.isSnake = False self.isApple = False def setState(self, s): if(s == None): s = "" self.isSnake = s.lower() == "s" self.isApple = s.lower() == "a" def get...
# -*- coding: utf-8 -*- # # (c) 2020, SCC France, Eric Belhomme <ebelhomme@fr.scc.com> # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import (absolute_import, division, print_function) __metaclass__ = type import pytest from ansible_collections.community....
# -*- coding: utf-8 -*- import time import numpy as np from datetime import datetime, timedelta import simplejson as json import itertools import scrapy from exchange_rate_scraper.items import XeItem from exchange_rate_scraper import currency from twisted.enterprise import adbapi import MySQLdb import MySQLdb.cursor...
# BSD 3-Clause License # # Copyright (c) 2019, Elasticsearch BV # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # * Redistributions of source code must retain the above copyright notice, t...
import os import time from datetime import datetime import numpy as np import numpy.random as npr import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt import tensorflow as tf print(tf.__version__) from tensorflow.python.client import device_lib device_lib.list_local_devices() from tensorflow.contr...
# System libraries from __future__ import absolute_import, division, print_function import argparse import logging import os import random import sys import time # Enable logging logging.basicConfig( format='%(asctime)s [%(levelname)s] %(message)s', level=logging.INFO, stream=sys.stdout) log = logging....
#! /usr/bin/python import argparse import shutil from os.path import join, realpath, split, exists, getmtime, relpath from re import match as re_match import os if __name__ == '__main__': parser = argparse.ArgumentParser(prog='copy_create_proto_files',description='Helper script for google protobuf files') par...
#!/usr/bin/env python from datetime import datetime from ndbc import Station import matplotlib.pyplot as plt import matplotlib matplotlib.use('Agg') buoyid = 42002 starttime = datetime(2017, 1, 1) endtime = datetime(2017, 2, 1) s = Station(buoyid, starttime, endtime) fig = plt.figure(figsize=(12, 6)) ax = fig.add...
titles = ['Creature if Habit','Crewel Fate'] plots = ['A num turns into a monster', 'A haunted yarn shop'] movies = dict( zip(titles, plots) ) # expected output: ''' {'Creature if Habit': 'A num turns into a monster', 'Crewel Fate': 'A haunted yarn shop'} ''' print( movies)
class Restaurant(): def __init__(self, restaurant_name, cuisine_type): self.restaurant_name = restaurant_name self.cuisine_type = cuisine_type def describe_restaurant(self): print('Nombre del restaurante: ', self.restaurant_name) print('Tipo de cocina: ', self.cuisine_type) ...
from __future__ import absolute_import from . import _minstcut as __minstcut from ._minstcut import * from .... import Configuration from functools import partial __all__ = [] for key in __minstcut.__dict__.keys(): __all__.append(key) try: __minstcut.__dict__[key].__module__='nifty.graph.opt.minstcut...
"""A command line tool to view detailed information about a character.""" __name__ = "charinfo" __title__ = __name__ __license__ = "MIT" __version__ = "0.2.0" __author__ = "Arian Mollik Wasi" __github__ = "https://github.com/wasi-master/charinfo"
# Copyright 2020 DeepMind Technologies Limited. # # 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 ag...
from.import school from.import funds from.import invo
import json import re from django.forms import widgets from rest_framework import serializers from accounts.serializers import AttachCanEditSerializer, UserSerializer from notifications.models import Notification, NotificationTemplate, NotificationAuthority from reports.models import ReportType from reports.serializ...
#GitHub Username and Password username = "FOO" password = "BAR"
# Copyright 2013 OpenStack Foundation # All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless requ...
# PlacesCNN for scene classification # # by Bolei Zhou # last modified by Bolei Zhou, Dec.27, 2017 with latest pytorch and torchvision (upgrade your torchvision please if there is trn.Resize error) import torch from torch.autograd import Variable as V import torchvision.models as models from torchvision import transfo...
class PixivError(Exception): pass class RetryExhaustedError(PixivError): def __init__(self, name=None, args=None, kwargs=None): self.name = name self.reason = '{}, {}'.format(args, kwargs) super(PixivError, self).__init__(self, self.reason) def __str__(self): return self.r...
from direct.gui.DirectGui import * from pandac.PandaModules import * from pirates.piratesgui import GuiPanel, PiratesGuiGlobals from pirates.piratesbase import PiratesGlobals from pirates.piratesbase import PLocalizer from otp.otpbase import OTPLocalizer from pirates.inventory.InventoryUIGlobals import * from pirates.e...
import time # https://web-dev01.interneturok.ru/algebra/11-klass/bpovtorenie-kursa-algebry-10-klassab/kasatelnaya?seconds=0&chapter_id=51 class PagePaidLessonComment(object): def __init__(self, driver): self.driver = driver def click_link_comments(self): self.driver.find_element_by_id("comme...
import uqbar.strings import supriya.assets.synthdefs import supriya.realtime def test_01(server): group = supriya.realtime.Group() synth_a = supriya.realtime.Synth(supriya.assets.synthdefs.test) synth_b = supriya.realtime.Synth(supriya.assets.synthdefs.test, amplitude=0.0) group.extend([synth_a, synt...
from models.protonet import ProtoNet from backbones.layers import init_layer import torch.nn as nn import torch import torch.nn.functional as F import pprint from torch.autograd import Variable import utils.utils as uu import numpy as np import argparse class RelationNet(ProtoNet): @staticmethod def get...
# built-in from argparse import ArgumentParser # app from ..actions import get_python_env, make_json from ..config import builders from ..converters import InstalledConverter from ..models import Requirement from .base import BaseCommand class DepsCheckCommand(BaseCommand): """Show difference between venv and pr...
import sys reload(sys) sys.setdefaultencoding("latin-1") fname = 'n18811799744.sql' with open(fname) as f: content = f.readlines() content = filter(lambda x: len(x) > 100, content) content = map(lambda x: x.strip().split(","), content) content = map(lambda x: "Hourlys.insert({deviceId: '" + x[0][14:25] + "',upload...
from mathematics.vector import Vector2 class BaseRect: location1: Vector2 size: Vector2 def __init__(self, init_location1: Vector2, init_size: Vector2) -> None: """ 矩形の座標と大きさを出力するクラス :param init_location1: :param init_size: """ self.location1 = init_locatio...
"""Command 4.""" import sys import click from loguru import logger def filter_stdout_logging(record): return record['level'].name in ['INFO', 'SUCCESS', 'WARNING'] def filter_stdout_verbose(record): return record['level'].name in ['DEBUG', 'INFO', 'SUCCESS', 'WARNING'] @click.group() @click.option('--ver...
from formatting import * def analyzer(url="https://www.imdb.com/"): from requests import head try: head(url) except: print(colors('OPS: parece que o programa não pode ser usado nesse momento...', color='vermelho', ngr=True), end=" ") print(colors('Mas tente novamente mais tarde.',...
from typing import NamedTuple, List class Cell(NamedTuple): row: int column: int class Placement(NamedTuple): cell: Cell digit: int class Candidate(NamedTuple): cell: Cell digit: int class Elimination(NamedTuple): candidates: List[Candidate]
from django.contrib import admin from .models import * # Register your models here. @admin.register(ItemType) class ItemTypeAdmin(admin.ModelAdmin): list_display = ("name","about","item_type_keywords","created_at","updated_at") @admin.register(Item) class ItemAdmin(admin.ModelAdmin): list_display = ("name","...
"""Module containing prometheus plugin used to add metrics route to an API""" import logging import pydantic import os import typing import bottle import Octopus.bottle.prometheus.prometheus_config as config LOGGER = logging.getLogger('octopus.bottle.prometheus') # import prometheus metrics module if enabled. N...
""" Copyright 2015, Institute e-Austria, Timisoara, Romania http://www.ieat.ro/ Developers: * Gabriel Iuhasz, iuhasz.gabriel@info.uvt.ro 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...
from django.urls import reverse from django.db import models from core.models import AbstractItem class Book(AbstractItem): cover_image = models.ImageField(null=True, blank=True) category = models.ForeignKey( "categories.Category", on_delete=models.CASCADE, related_name="books" ) wri...
import copy import random from threading import Thread from couchbase_helper.documentgenerator import JsonDocGenerator from gsi_replica_indexes import GSIReplicaIndexesTests from lib.couchbase_helper.tuq_generators import TuqGenerators from lib.membase.helper.cluster_helper import ClusterOperationHelper from lib.memca...
"""empty message Revision ID: c003c56cd46a Revises: Create Date: 2021-12-09 12:34:23.457361 """ from alembic import op import sqlalchemy as sa from sqlalchemy.dialects import mysql # revision identifiers, used by Alembic. revision = 'c003c56cd46a' down_revision = None branch_labels = None depends_on = None def up...
# Copyright (c) 2015, VMRaid Technologies Pvt. Ltd. and Contributors # MIT License. See license.txt from __future__ import unicode_literals import vmraid import vmraid.permissions def execute(): vmraid.reload_doc("core", "doctype", "docperm") table_columns = vmraid.db.get_table_columns("DocPerm") if "restricted" ...
# Copyright 2019 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 # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
# -*- coding: utf-8 -*- # Copyright (c) Facebook, Inc. and its affiliates. # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. from __future__ import absolute_import, division, print_function from abc import abstractmethod, ABC from typing import...
""" Interactions for user feedback """ import logging import requests from settings import PATH, LOG_NAME, API_TOKEN from settings import FEEDBACK from telegram.ext import ConversationHandler logger = logging.getLogger(LOG_NAME) class Feedback: """ Save feedback from the user """ def index(update, ...
from .menu import Views as v from .messages import Messages as msg from .buttons import Buttons as b from .settings import bot from .routes import start_view, country_view, male_view, see_product_view, \ add_product_to_basket, see_product_basket, get_all_product_in_basket, get_product, to_share, order, reviews de...
''' Created on Aug 6, 2015 @author: theo ''' from django.core.management.base import BaseCommand from django.contrib.auth.models import User from iom.models import Meetpunt from acacia.data.models import DataPoint import logging from iom import util logger = logging.getLogger('akvo') class Command(BaseCommand): ...
from .setup import load_django def on_server_loaded(server_context): load_django()
'''5. Пользователь вводит две буквы. Определить, на каких местах алфавита они стоят и сколько между ними находится букв.''' letter1, letter2 = [ x.upper() for x in input('Введите две буквы, через пробел (A - Z): ').split() ] # Генерация списка букв abc_list = [chr(i) for i in range(ord('A'), ord('Z') + 1)] index_l...
#!/usr/bin/env python # units in meters, seconds and kilograms # internal distance unit = Earth radius import os, pyglet, pyglet.clock from pyglet.gl import * from pyglet import window, event from math import sqrt G_Newton = 6.674E-11 def distance_scale(metric, invert=False): earth_radius = 6.371E+...
import asyncio import configparser import datetime import json import math import os import os.path import random import re import shlex import sys import time import urllib.request from datetime import date, datetime from io import BytesIO from operator import add, mul, pow, sub, truediv import aioht...
# # Copyright (c) 2020 Lucas Lehnert <lucas_lehnert@brown.edu> # # This source code is licensed under an MIT license found in the LICENSE file in the root directory of this project. # from unittest import TestCase class TestBeliefAgentTabular(TestCase): def _get_data(self, num_mpds=5): import rewardpredic...
import wx import time import threading import cv2 import numpy as np import time from sakuvid import SakuVid, VidFile import utils class RenderThread(threading.Thread): def __init__(self, func, fps=24.): threading.Thread.__init__(self) self.func = func self._fps = fps self._flag_st...
# Copyright 2018 The Kubeflow 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 in...
# -*- coding: utf-8 -*- class Dog: pass if __name__ == '__main__': # 두 개의 인스턴스 생성 sam = Dog() ruby = Dog() # 각각의 인스턴스를 위한 메모리주소가 할당된다. print(sam) print(ruby)
# -*- coding: utf-8 -*- # tk18.pyw import tkinter as tk def print_txtval(): val_en=en.get() print(val_en) root = tk.Tk() en = tk.Entry() bt = tk.Button(text="ボタン",command=print_txtval) [widget.pack() for widget in (en,bt)] en.focus_set() root.mainloop()
def calc(m, n): mul = m * n div = mul // 2 return div % 7 def calc_sum_and_count_all_numbers_div_by_2_or_7(max_exclusive): div_2 = [] div_7 = [] count = 0 sum = 0 for i in range(1, max_exclusive): if i % 2 == 0 or i % 7 == 0: sum += i count += 1 ...
from django.urls import path from . import views from .views import adminCheck urlpatterns = [ path('register/', views.register, name='users-register'), path('profile/', views.profile, name='users-profile'), path('checkforadmin/', adminCheck, name='admin-check'), ]
# -*- coding: utf-8 -*- # Copyright 2018, IBM. # # This source code is licensed under the Apache License, Version 2.0 found in # the LICENSE.txt file in the root directory of this source tree. import sys sys.path.append('./demos/AI/') from run_classify_local import classify from presentation_helpers import * mode = ...
'''Metalk8s network related utilities.''' import itertools import logging from salt._compat import ipaddress from salt.exceptions import CommandExecutionError K8S_CLUSTER_ADDRESS_NUMBER = 0 OIDC_ADDRESS_NUMBER = 6 COREDNS_ADDRESS_NUMBER = 9 log = logging.getLogger(__name__) __virtualname__ = 'metalk8s_network' ...
from . import * class SubscribeNewEpisodeController(AppDevController): def get_path(self): return '/notifications/episodes/<series_id>/' def get_methods(self): return ['POST', 'DELETE'] @authorize def content(self, **kwargs): user = kwargs.get('user') series_id = request.view_args['series_id...
from decimal import Decimal, DecimalException import statistics from django.db import models from django.utils.translation import ugettext_lazy as _ from django.conf import settings from django.utils import timezone from django.core.validators import MinValueValidator, MaxValueValidator from django.urls import reverse...
# # Lockstep Platform SDK for Python # # (c) 2021-2022 Lockstep, Inc. # # For the full copyright and license information, please view the LICENSE # file that was distributed with this source code. # # @author Lockstep Network <support@lockstep.io> # @copyright 2021-2022 Lockstep, Inc. # @link https://github....