text
stringlengths
8
6.05M
__author__ = 'chenjensen' from BeautifulSoup import BeautifulSoup from PageGetter import PageGetter class NextCrawer: def __int__(self): herfInfoList = [] nameInfoList = [] describeInfoList = [] getter = PageGetter('http://next.36kr.com/posts') page = getter.getPage() ...
a,b,c=input().split() a=a[int(c):] print(a[int(b)-1])
''' Single neuron with Numpy dot product ''' import numpy as np inputs = [1.0, 2.0, 3.0, 2.5] weights = [0.2, 0.8, -0.5, 1.0] bias = 2.0 output = np.dot(weights, inputs) + bias print(output)
# Generated by Django 2.0.7 on 2018-08-09 09:23 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('twitterapp', '0001_initial'), ] operations = [ migrations.AlterField( model_name='uefa', name='Teams', f...
import os import sys import time from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC def get_path(main_folder = 'files', a = '...
print("Hola") print("Cómo te llamas?") myName=input() print("Qué tal " + myName + "?") print("Tu nombre tiene " + str(len(myName)) + " letras") print('Cuál es tu edad?') #print(int('99.9')) #Not possible to print yourAge=int(input()) #yourAge=int(yourAge) #can't evaluate value as an integer, better try yourAge=int(inpu...
from sdc.crypto.key_store import KeyStore TEST_DO_NOT_USE_SR_PRIVATE_PEM = """-----BEGIN RSA PRIVATE KEY----- MIIEogIBAAKCAQEAt8LZnIhuOdL/BC029GOaJkVUAqgp2PcmbFr2Qwhf/514DUUQ 9sKJ1rvwvbmmW2zE8JRtdY3ey0RXGtMn5UZHs8NReHzMxvsmHN4VuaGEnFmPwO82 1Tkvg0LpKsLkotcw793FD/fut44N2lhpTSW2Sc82uG0p9A+Kud8HCIaWaluosghk 9rbMGYDzZQk8cA...
import pygame pygame.init() canvas = pygame.display.set_mode([500, 250]) # para crear textos es necesario usar el objeto pygame.font # SysFont(name, size, bold=False, italic=False) font = pygame.font.SysFont("Arial", 24) # render(text, antialias, color, background=None) antialias = True text = "Yes" text_surface =...
# -*- coding: utf-8 -*- from django.shortcuts import render <<<<<<< HEAD from contest.models import * from contest.functions import * # Create your views here. def index(request, tag=None): tags = ContestTag.objects.order_by() if tag != None: contests = Contest.objects.filter(tags__tag=tag).order_by('...
import unittest from conans.test.utils.tools import TestClient from conans.util.files import save import os class SettingConstraintTest(unittest.TestCase): def settings_constraint_test(self): conanfile = """from conans import ConanFile class Test(ConanFile): name = "Hello" version = "0.1" set...
import unittest from gita_md_writer import mdcumulate, groupadja class MDChapterTest(unittest.TestCase): def test_adjacent_paras_of_same_style_are_grouped(self): adjacent_paras = [ {"para": "para1.1", "style": "style1"}, {"para": "para1.2", "style": "style1"}, {"para": "para2", "style": "style2...
"""Hermes MQTT server for Rhasspy TTS using Google Wavenet""" import asyncio import hashlib import io import logging import os import shlex import subprocess import typing import wave from pathlib import Path from uuid import uuid4 from google.cloud import texttospeech from rhasspyhermes.audioserver import AudioPlayBy...
from jamesbot.data_loader import DataLoader
import os import re import sys import json import shutil from optparse import OptionParser from subprocess import check_call CONDA_ENV_SH = """#!/bin/bash if [ -z "${CDH_PYTHON}" ]; then export CDH_PYTHON=${PARCELS_ROOT}/${PARCEL_DIRNAME}/bin/python fi if [ -n "${R_HOME}" ]; then export R_HOME="${PARCELS_ROOT}/...
from flask import Blueprint bp = Blueprint("base_routes", __name__) from . import delete, get, patch # noqa: F401, E402
# @Title: 键盘行 (Keyboard Row) # @Author: 2464512446@qq.com # @Date: 2019-10-08 16:59:59 # @Runtime: 24 ms # @Memory: 11.5 MB class Solution(object): def findWords(self, words): set1 = set('qwertyuiop') set2 = set('asdfghjkl') set3 = set('zxcvbnm') res = [] for i in words: ...
from multiprocessing import Manager,Queue,Pool #1.进程之间的通讯 q=Queue(3) #初始化一个Queue队列,最多存储三个put消息 q.put("haha1") #放入任意数据类型消息(具有堵塞属性,如果添加第四个会堵塞) q.qsize() #获取队列里面的消息个数 q.get() #塞先进先出,获取第一个消息内容(具有堵塞属性,如果里面没有消息,调用get会堵) q.empty() #判断是否空消息 q.full() #判断队列的消息是否已满 q.get_nowait() #不会堵塞,但是会抛出异常,所以要放在异常捕获try里面...
import cv2 import numpy as np img = cv2.imread("H:/Github/OpenCv/Research/images/opencv.jpg") # cv2.imshow("Original",img ) grey = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) edges = cv2.Canny(grey,75,127) ret,thresh = cv2.threshold(edges,70,255,0) thresh = cv2.subtract(255, thresh) im2, contours, hierarchy = cv2.findConto...
''' multiple of 3 'Fizz' and 5 'Buzz' and both 'FizzBuzz' NOw this is just a test to push the code ''' import os,sys from flask import Flask app = Flask(__name__) @app.route("/") #class FizzBuzz: def numb(): a=[] for i in range(1,101): if (i%3==0) and (i%5==0): a.append('FizzBuzz') e...
# This file should contain the main codes that controls the whole # behaviour of the package. # # To import modules from different files, just add here: # from <package_name>.module import functions, classes def main(): pass
# -*- coding: utf-8 -*- ############# # # Copyright - Nirlendu Saha # # author - nirlendu@gmail.com # ############# """ Django settings for core project. Generated by 'django-admin startproject' using Django 1.10.1. For more information on this file, see https://docs.djangoproject.com/en/1.10/topics/settings/ For ...
import os, glob import numpy as np import scipy.stats as stats import pandas class _Sampler: def __init__(self, sbml, config): self.sbml = sbml self.config = config def sample(self): raise NotImplementedError def _sample1dist(self): return NotImplementedError class Mon...
from collections import namedtuple from simlammps.bench.util import get_particles from simlammps.testing.md_example_configurator import MDExampleConfigurator from simphony.bench.util import bench from simphony.core.cuba import CUBA from simphony.engine import lammps _Tests = namedtuple( '_Tests', ['method', 'na...
#!/usr/bin/python import matplotlib.pyplot as plt from prep_terrain_data import makeTerrainData from class_vis import prettyPicture features_train, labels_train, features_test, labels_test = makeTerrainData() ### the training data (features_train, labels_train) have both "fast" and "slow" ### points mixed together-...
/Users/karshenglee/anaconda3/lib/python3.6/fnmatch.py
''' задача 1 - сделать скрипт, который - раз в 30 секунд выводит текущее время, - все остальное время ждем ввода. - если передать пробел - скрипт завершается ''' import time from threading import Thread from threading import Event class TimerThread(Thread): def __init__(self, event): Thread.__init__(s...
import os.path import photo import calibrate from os import path import numpy as np def read_cam_paramns(): with np.load('pose/webcam_calibration_params.npz') as X: mtx, dist, _, _ = [X[i] for i in ('mtx','dist','rvecs','tvecs')] return mtx, dist def prepare_env(): if path.exists("...
#import sys #input = sys.stdin.readline from collections import Counter Q = 10**9+7 def main(): N = int(input()) A = list(map(int,input().split())) if A[0] > 0: print(0) return CA = Counter(A) if CA[0] > 1: print(0) return B = list(set(A)) B.sort() for i, ...
# Tencent is pleased to support the open source community by making GNES available. # # Copyright (C) 2019 THL A29 Limited, a Tencent company. 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...
import cv2 import os from scipy import ndimage i = 0 for filename in os.listdir("path\\to\\folder\\of\\images\\"): img = cv2.imread("path\\to\\folder\\of\\images\\"+filename) rotated = ndimage.rotate(img, 270) cv2.imwrite("path\\to\\folder\\for\\saving\\images\\"+filename, rotated) print(i) ...
''' Specified insensitivity to IC phase ''' import warnings warnings.simplefilter("ignore", UserWarning) # Import the necessary python library modules import numpy as np from matplotlib import pyplot as plt from scipy.optimize import minimize import os import sys import pdb # Add my local path to the relevant modul...
import time import sys,os import curses import datetime import math import json from dateutil.parser import * import urllib2 def check_wind(): try: try: f = urllib2.urlopen('http://api.wunderground.com/api/c76852885ada6b8a/conditions/q/Ijsselstein.json') except: print('[NOK...
import vk_api, json from vk_api import VkUpload from vk_api.longpoll import VkLongPoll, VkEventType #from si vk_session = vk_api.VkApi(token="ac4a1efc08aba9faa25bb28e290debf62e3d5c2932430a57020cb07fa37698472f69a06b33bad06bad251") vk = vk_session.get_api() longpoll = VkLongPoll(vk_session) upload = VkUpload(v...
templates_list = dict( photo="photo_message.jinja2", document="document_message.jinja2", voice="voice_message.jinja2", video_note="video_note_message.jinja2", sticker="sticker_message.jinja2", animation="animation_message.jinja2", _="base_message.jinja2", ) def get_template(message, templa...
from pytuning.scales import create_edo_scale edo_12_scale = create_edo_scale(12) print((edo_12_scale[1] * 440).evalf(8))
from django.contrib import admin from user.models import User # Register your models here. class UserAdmin(admin.ModelAdmin): list_display = ('username', 'password') # user list 사용자명과 비밀번호를 확인할 수 있도록 설정 admin.site.register(User, UserAdmin)
import torch import torch.nn as nn class GCAModel(nn.Module): def __init__(self,hparams,vocab): super().__init__() self.cdd_size = (hparams['npratio'] + 1) if hparams['npratio'] > 0 else 1 self.device = torch.device(hparams['device']) self.embedding = vocab.vectors.to(self.device)...
# -*- coding: utf-8 -*- # Generated by Django 1.9 on 2016-03-14 07:24 from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency...
import datetime from haystack import indexes from periodicals.models import Article class ArticleIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.CharField(document=True, use_template=True) pub_date = indexes.DateTimeField(model_attr='issue__pub_date') # pregenerate the search result HTML for...
""" Specification objects and functions for the ``Date`` built-in. """ from __future__ import absolute_import import time import math import operator from .base import ObjectInstance, FunctionInstance from .function import define_native_method from ..exceptions import ESRangeError, ESTypeError from ..literals import Li...
from unittest import TestCase import create_food class TestFieldObjects(TestCase): def test_coordinates(self): s = create_food.save_terrain() # self.assertTrue(isinstance(s, basestring))
# 增加属性类型限制 限制People 中的name 属性只能是str age属性只能是 int # 数据描述符 class Typed(): def __init__(self,key,exceptipnType): self.key = key self.exceptipnType=exceptipnType def __get__(self, instance, owner): print('**get方法***') # print('**instance参数 [%s] ***' %instance) # print('**own...
__author__ = 'Jan Pecinovsky, Roel De Coninck' """ A sensor generates a single data stream. It can have a parent device, but the possibility is also left open for a sensor to stand alone in a site. It is an abstract class definition which has to be overridden (by eg. a Fluksosensor). This class contains all metadata ...
import zeroone_hash from binascii import unhexlify, hexlify import unittest # zeroone block #1 # user@b1:~/zeroone$ zeroone-cli getblockhash 1 # 000005e9eeef7185898754d08dbfd6ecc167cfa83c4e15dcb1dcc0d79cc13fbf # user@b1:~/zeroone$ zeroone-cli getblock 000005e9eeef7185898754d08dbfd6ecc167cfa83c4e15dcb1dcc0d79c...
#!/usr/bin/env python # coding: utf-8 # In[ ]: # Gabriel Santos IS-211 9/12/2020 import urllib.request import re import logging import csv import argparse import datetime import requests hours = {0: 0, 1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0, 8: 0, 9: 0, 10: 0, 11: 0, 12: 0, 13: 0, 14:...
#Array range class Stack: def __init__(self): self.stack = list() def isEmpty(self): return self.stack == [] def peek(self): assert not self.isEmpty() , "Cannot peek from empty stack" return self.stack[-1] def pop(self): ...
import os PROJECT_ROOT = os.path.abspath(os.path.dirname(__file__)) """ Path to media monitoring data (monthly) """ DATA_PATH = os.path.join(PROJECT_ROOT, 'data/') """ Segments """ segment1 = {"label": "Undecided", "value": "UND"} segment2 = {"label": "Abstainer", "value": "ABS"} segment3 = {"label": "PJD", "value":...
"""Advent of Code 2019 Day 20 - Donut Maze.""" from collections import defaultdict, deque def maze_bfs(maze, start, end, portals, recursive=False): """BFS from entrance to exit of maze with portals. Args: maze (dict): {Coords: Value} dictionary representing the maze. entrance (s...
from functools import cached_property from onegov.activity import Activity, PeriodCollection, Occasion from onegov.activity import BookingCollection from onegov.core.elements import Link, Confirm, Intercooler, Block from onegov.core.elements import LinkGroup from onegov.core.utils import linkify, paragraphify from one...
from rest_framework.response import Response from rest_framework.generics import ListAPIView from rest_framework.views import APIView from django.http import JsonResponse from employee_core.api.serializers import EmployeeObjectSerializer from employee_core.models import Employee class EmployeeObjectView(APIView): ...
import time class Solution: def lengthOfLongestSubstring(self, s): """ :type s: str :rtype: int """ n = len(s) nums = [] if s == '': return 0 if len(s) == 1: return 1 for i in range(n): #这里直接用字符...
import socket import random s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect(('127.0.0.1', 4445)) random_number = random.randrange(100) s.send(str(random_number).encode())
#importing necessary libraries import matplotlib.pyplot as plt import torch import numpy as np from torch import nn from torch import optim from torchvision import datasets, models, transforms import torch.nn.functional as F import torch.utils.data import pandas as pd from collections import OrderedDict from PIL import...
from .mplbasewidget import MatplotlibBaseWidget from .mplcurvewidget import MatplotlibCurveWidget from .mplerrorbarwidget import MatplotlibErrorbarWidget from .mplimagewidget import MatplotlibImageWidget from .mplbarwidget import MatplotlibBarWidget __all__ = [ 'MatplotlibBaseWidget', 'MatplotlibCurveWidget', ...
import os, re invertInput_arr = [ { "IMCR" : "28", "Name" : "eMIOS_0_emios_y_in_28" }, { "IMCR" : "29", "Name" : "eMIOS_0_emios_y_in_29" }, { "IMCR" : "30", "Name" : "eMIOS_0_emios_y_in_30" }, { "IMCR" : "31...
# Generated by Django 3.0.7 on 2020-10-09 09:15 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('cl_table', '0021_auto_20201009_0859'), ] operations = [ migrations.CreateModel( name='Employee', fields=[ ...
import random import requests import http.client import numpy as np from flask import Flask from flask import request, escape, render_template app = Flask(__name__) def getData(ID, ID_Data): """ Converts the data sent by the server into the original message Parameters ---------- ID : list(:float) ...
import math N = 1 for n in xrange(N): y = (math.sin(float(n)/float(N)*math.pi*2.0)+1.0)/2.0*(8*16-1) sy = int(round((y % 16)/3)) cy = int(round(int(y / 16))) print "; x = %d y = %f" % (n, y) print "db %d" % cy print "db %d" % sy #print n, y, cy*16+sy*3
###### ITC 106 - Jarryd Keir - Student Number 11516086 #### Variable Section - ensure that variables are correct values before starting to ensure that the main part of the code #### inputMarkAss1 = -1 inputMarkAss2 = -1 inputMarkExam = -1 outputMarkAss1 = 0 outputMarkAss2 = 0 outputMarkExam = 0 AssWeight1 = 20 AssWe...
# Generated by Django 3.2.5 on 2021-08-12 03:52 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('erp', '0004_auto_20210718_1958'), ] operations = [ migrations.AlterField( model_name='category', name='name', ...
from flask import Flask, render_template from random import randrange app = Flask(__name__) @app.route("/") def home(): return render_template("home.html") @app.route("/about") def about(): return render_template("about.html") @app.route("/fun") def fun(): return render_template("fun.html") @app.route(...
# making anagrams from collections import Counter s="abc" s1="cde" a=Counter(s) b=Counter(s1) print(a-b) print(a) print(b)
# -------------------------------------------------------------------- import re import os # *** Matching chars *** """ MetaCharacters: . ^ $ * + ? { } [ ] \ | ( ) Class [] or set of characters [abc] or [a-c] [abc$] $ is not special here! [^5] complement. Any char but 5. [5^] has no meaning [a-zA-Z0-9_] = \w \d Matc...
'''tests ensuring that *the* way of doing things works''' import datetime from icalendar import Calendar, Event import pytest def test_creating_calendar_with_unicode_fields(calendars, utc): ''' create a calendar with events that contain unicode characters in their fields ''' cal = Calendar() cal.add('PR...
#!/usr/bin/env python import pygtk pygtk.require("2.0") import gtk class Base: def combo_text(self,widget): self.win.set_title(widget.get_active_text()) def textchange(self,widget): self.win.set_title(self.textbox.get_text()) def relabel(self,widget): self.label.set_text('xxxxxxxx...
from operator import itemgetter import re import numpy as np def levenshtein_distance(s, t): """ computes the Levenshtein distance between the strings s and t using dynamic programming Returns ---------- dist(int): the Levenshtein distance between s and t """ rows ...
# ------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # -------------------------------------------------------------------------- import nu...
import os class Config(object): SECRET_KEY = os.environ.get("SECRET_KEY") SQLALCHEMY_DATABASE_URI = os.environ.get('DATABASE_URL') SQLALCHEMY_TRACK_MODIFICATIONS = False MAIL_SERVER = os.environ.get('MAIL_SERVER') MAIL_PORT = os.environ.get('MAIL_PORT') MAIL_USE_TLS = os.environ.get('MAIL_USE...
#!/usr/bin/python import os import urllib2 import json import commands import re import boto3 from boto3 import session #Retrieving Instance Details such as Instance ID and Region from EC2 metadata service instance_details = json.loads(urllib2.urlopen('http://169.254.169.254/latest/dynamic/instance-identity/document...
from Pages.ContentPages.BasePage import Page import time from Pages.ServicePages import AuthPage import pytest import config class User(object): URL = 'http://{login}:{pas}@{url}/user/login'. \ format(login=config.http_login, pas=config.http_pass, url = config.domain) login = 'adyaxadmin' password...
Author = 'Liu Lei' import configparser config=configparser.ConfigParser() config['DEFAULT']={'ServerAliveInterval':'45','sex':'girl'} config['f']={'aslkd':'wew'} config['topsecret.server.com']={} topsecret = config['topsecret.server.com'] topsecret['Host Port'] = '50022' # mutates the parser topsecret['ForwardX11'] =...
import socket import os import sys import glob def enviar(nombre): try: f = open(nombre,'rb') stats = os.stat(nombre) tam = stats.st_size #print(tam) s_cliente.send(str(tam).encode()) l = f.read(1024) while (l): s_cliente.send(l) l = f.read(1024) print("Enviado") f.close() except IOError:...
from django import forms from .models import User from django.core.exceptions import * import re USERNAME_PATTERN = re.compile(r'\w{4,20}') class UserForm(forms.ModelForm): def clean_username(self): username = self.cleaned_data['username'] if not USERNAME_PATTERN.fullmatch(username): ...
# -*- coding:utf-8 -*- """ Time : 2020/11/6 11:10 Author : Kexin Guan Decs : """
# ################## # 1. lists of floats # ################## import random from deap import base from deap import creator from deap import tools # negative weights lead to minimization # positive weights are for maximization creator.create("FitnessMin", base.Fitness, weights=(-1.0,)) creator.create("FitnessMax", b...
#coding=utf-8 import re from flask_wtf import FlaskForm from wtforms import StringField, PasswordField, SubmitField, BooleanField, SelectField from wtforms import TextAreaField, IntegerField from wtforms import ValidationError from wtforms.validators import Length, Email, EqualTo, DataRequired, URL, NumberRange, Op...
#symetric difference def symetric_difference(num1,num2): num1 = set(list(map(int, num1))) num2 = set(list(map(int, num2))) num = sorted(num1.symmetric_difference(num2), key=int, reverse=True) for i in num[::-1]: print(i) nums1 = input() nums2 = input().split() nums3 = input() nums4 =...
import tosca.basetypes def f_eq(v, _): return lambda x : x == v def f_gt(v, _): return lambda x : x > v def f_ge(v, _): return lambda x : x >= v def f_lt(v, _): return lambda x : x < v def f_le(v, _): return lambda x : x <= v def f_ir(v, t): if isinstance(t, int) and isinstance(v, list): r = Ra...
import requests p='page2' res=requests.get("https://reqres.in/api/users?",params=p) assert res.status_code==200, "Code dose not match." print(res.json()) print(res.headers) print(res.encoding) print(res.url) json_res=res.json() print(json_res['total']) print(json_res['total_pages']) assert (json_res['total_pages'])==2...
A, B, C, D = map( int, input().split()) if A+B < C+D: print('Right') elif A+B == C+D: print('Balanced') else: print('Left')
# . Copyright (C) 2020 Jhonathan P. Banczek (jpbanczek@gmail.com) # import unittest import os import datetime from utils import ( str2float, namefile2date, date2filename, _format_item, format_file, all_files, ) from models import Arquivo, Folha ############################################...
from django.urls import path from .views import review, PostListView, PostDetailView, PostCreateView, ReviewCreateView, ReviewDetailView, review_comment_create, ReviewListView urlpatterns = [ path('board', PostListView.as_view(), name='board'), path('board/<int:pk>', PostDetailView.as_view(), name='board_deta...
import numpy as np import os,sys import tensorflow as tf import cv2 as cv sys.path.append('../') from models.research.object_detection.utils import label_map_util from models.research.object_detection.utils import visualization_utils as vis_util PATH_TO_CKPT = "data/save/frozen_inference_graph.pb" PATH_TO_LABELS = ...
import json from breeding.models import Source from users.models import UserProfile userprofile_filter = UserProfile.objects.filter(is_signup=True) winner_list = list() for userprofile in userprofile_filter: source_count = Source.objects.filter(userprofile=userprofile, qual...
from keras.preprocessing import text import pandas as pd import pickle import util print('loading data...') df_train = pd.read_csv(util.train_data) df_test = pd.read_csv(util.test_data) df_train['comment_text'] = df_train['comment_text'].fillna('UN') df_test['comment_text'] = df_test['comment_text'].fillna('UN') print...
import pandas as pd # DataFrame() 함수로 데이터 프레임 변환, 변수 df에 저장 exam_data = {'이름':['서준','우현','인아'],'수학':[90,80,70],'영어':[98,89,95],'음악':[85,95,100],'체육':[100,90,90]} df = pd.DataFrame(exam_data) print("# '이름'열을 새로운 인덱스로 지정하고, df객체에 변경사항 반영") df.set_index('이름',inplace=True) print(df) print() print("# 데이터프레임 df의 특정원소 1개 선...
from download_task_center import DownloadTaskCenter from spider_lib import log_print info = ''' 程序说明: 本程序会将 https://alpha.wallhaven.cc/random 上的图片采集到运行目录下 作者:Jerry 网站:www.jerryshell.cn 版本:v0.4 ''' log_print(info) home_page_url = 'https://alpha.wallhaven.cc/random' get_home_page_count = int(input('请求 1 次首页可获得 24 张图片...
from state import State class StateObserver(object): def __init__(self, delegate): assert hasattr(delegate, 'deploy') self._delegate = delegate def update(self, _, payload): if payload['old'] == State.STARTING and payload['new'] == State.RUNNING: self._delegate.deploy()
# Copyright 2017 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...
from collections import math import math def uniqueNumber(A): counter = Counter(A) commons = counter.most_common() return commons[-1][0] def power(x, y, p): res = 1 x = x % p; while (y > 0): if (y & 1): res = (res * x) % p y = y >> 1 x = (x * x) % p ...
import json import tweepy # keep credentials in a seperate folder so it need to be imported. also the file is added to the '.gitignore' file. import credentials from tweepy import OAuthHandler # import Python's Counter Class from collections import Counter # to access the credentials in the file we add 'credentials.' ...
class Solution(object): def reverseVowels(self, s): """ :type s: str :rtype: str """ s_lst = list(s) l = 0 r = len(s) - 1 vowels = 'aeiouAEIOU' while True: while l < r and s[l] not in vowels: l += 1 while...
# https://www.w3schools.com/python/python_ml_scale.asp # Machine Learning - Scale - Escala # Recursos de escala # Quando seus dados têm valores diferentes e até mesmo unidades de medição diferentes, # pode ser difícil compará-los. O que é quilograma comparado com metros? # Ou altitude em comparação com o tempo? # A ...
# # Copyright (C) 2012 - 2019 Satoru SATOH <satoru.satoh@gmail.com> # Copyright (C) 2017 Red Hat, Inc. # License: MIT # # pylint: disable=missing-docstring,invalid-name,too-few-public-methods from __future__ import absolute_import import os import tests.backend.common as TBC try: import anyconfig.backend.yaml.pyya...
import random import config from enums import SideEnum, ActionEnum from feedhandler import FeedHandler def generate_order_message(order_id: int): min_price = int(config.MIN_PRICE_THRESHOLD) max_price = int(config.MAX_PRICE_THRESHOLD) price = random.randint(min_price, max_price) qty = random.randint(1,...
def add(n1, n2): return n1 + n2 def subtract(n1, n2): return n1 - n2 def calculator(n1, n2, func): return func(n1, n2) result_1 = calculator(5, 3, add) print(result_1) result_2 = calculator(5, 3, subtract) print(result_2)
from tkinter import * import math as m import tkinter.messagebox root = Tk() root.title("Advanced scientific calculator") root.configure(background="powder blue") root.resizable(width="false", height="false") root.geometry("480x624+20+20") Cacl = Frame(root) Cacl.grid() txtDisplay = Entry(Cacl, font=('arial', 30, 'b...
from flask import Flask, render_template, session, request, redirect,url_for app = Flask(__name__) @app.route("/") def home(): if 'logged' in session: return redirect(url_for("secret")) else: return render_template("home.html") @app.route("/secret", methods=["GET","POST"]) def secret(): i...
from ED6ScenarioHelper import * def main(): # 格兰赛尔 CreateScenaFile( FileName = 'T4214 ._SN', MapName = 'Grancel', Location = 'T4214.x', MapIndex = 1, MapDefaultBGM = "ed60017", Flags = 0, ...
from sys import platform as os_name from abstract_os import AbstractOS def singleton(cls): _instance = {} def inner(): if cls not in _instance: _instance[cls] = cls() return _instance[cls] return inner() @singleton class NativeOS(AbstractOS): def __init__...