text
stringlengths
38
1.54M
import tensorflowjs as tfjs import pandas as pd from keras.models import load_model from sklearn.model_selection import train_test_split from sklearn.preprocessing import LabelEncoder from keras.preprocessing.text import * from keras.utils import to_categorical from keras.models import Model from keras.layers import I...
from base import * DEBUG = True SITE_URL = 'http://localhost:8000/' MEDIA_URL = 'http://localhost:8000/site_media/' CACHE_BACKEND = 'dummy://'
from bitex import Bittrex k = Bittrex(key_file='bittrex.key') r = k.ticker('BTC-BTS') import pprint print((r.formatted)) print((r.json()))
# ----------module for core solver functions import numpy as np import SWIC_IO_module as IO # input-output module import sys from statistics import mode import scipy.sparse import scipy.sparse.linalg def fill_zeros_with_last(arr): #fills zeros with last non_zero value prev = np.arange(len(arr)) prev[arr == 0]...
# coding: utf-8 import json from datetime import datetime, date from werkzeug.security import generate_password_hash, check_password_hash from ._base import db from ._helpers import pinyin, save_object_to_es, delete_object_from_es, search_objects_from_es class User(db.Model): """用户""" __bind_key__ = 'dc' ...
#Import the necessary data science libraries import numpy as np import pandas as pd import matplotlib.pyplot as plt from tensorflow.keras.models import Sequential from tensorflow.keras.layers import Dense from tensorflow.keras.layers import LSTM from tensorflow.keras.layers import Dropout from sklearn.preprocessing imp...
from multiprocessing import Process, Value, Lock import os import time from multiprocessing.managers import BaseManager class User: def __init__(self, name, salary): self.name = name self.money = Value('f', salary) # 进程共享变量 def increase(self): self.money.value += 1000 time.sl...
from pymongo import MongoClient import datetime client = MongoClient('localhost', 27017) db = client['test-database'] collection = db['test-collection'] post = {"author": "Mike", "text": "My first blog post!", "tags": ["mongodb", "python", "pymongo"], "date": datetime.datetime.utcnow()} posts = db["posts"]
import platform from ..base import Ray, Vector3 from ..macros import create_assembler from .hit import HitPoint from .shape import Shape from .grid_mesh import GridMesh from .ray_triangle import ray_triangle_intersection class BaseMesh(Shape): def ntriangles(self): raise NotImplementedError() def bb...
from tkinter import* def triangle_w(): global triangle_main triangle_main=Tk() triangle_main.title("Triangle") pytago=Button(triangle_main,text="Square",command=pytago_w,fg="green") pytago.pack() Normal_area=Button(triangle_main,text="Normal area",fg="green",command=triangle_normal) Normal_area.pack() N...
from jarvis.io.wannier.outputs import ( WannierHam, Wannier90wout, Wannier90eig, get_projectors_for_formula, get_orbitals, ) import os import tempfile from jarvis.core.kpoints import generate_kgrid from jarvis.io.vasp.inputs import Poscar import matplotlib.pyplot as plt plt.switch_backend("agg") n...
# harshad number : # it is take any number and add this two digit number and check the # addition value is divisible bye this two digit number then it is divisible then its harshad # number then it not divisiblr then it not harshad number # forEx; 43 # 4+3=7 # 7/43 # num=int(input("enter a num...
import Layers import DataSets as ds import numpy as np import tensorflow as tf ############################################################################# # Creates a graph. a = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape=[2, 3], name='a') b = tf.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], shape=[3, 2], name='b')...
from pprint import pprint, pformat import logging from logging.config import dictConfig import colorlog from colorlog import ColoredFormatter # cf : https://stackoverflow.com/questions/17668633/what-is-the-point-of-setlevel-in-a-python-logging-handler ### create a formatter for future logger formatter = ColoredFor...
""" Implementation of Shell sort sorting technique """ def shell_sort(arr): n = len(arr) gap = n // 2 while gap > 0: for i in range(gap, n): temp = arr[i] j = i while j >= gap and arr[j - gap] > arr[j]: arr[j] = arr[j - gap] j -= ...
#!/usr/bin/env python #Author: Tyler Fornes #Filename: switcheroo.py #Function: Clones specified webpage to local copy and replaces a specified word with a given replacement import sys import urllib2 def getter(): response = urllib2.urlopen(sys.argv[1]) html = response.read() return html def reader(): file = ope...
from django.shortcuts import render, render_to_response from versiontools.osutils import AssemblyInfoFinder from django.template.context import RequestContext # Create your views here. def show_assemblyinfo(request): af = AssemblyInfoFinder() directory_to_scan =r'C:\Users\lberrocal\Documents\Visual Studio 2010...
from __future__ import print_function, absolute_import, division #makes KratosMultiphysics backward compatible with python 2.6 and 2.7 from KratosMultiphysics import IsDistributedRun from KratosMultiphysics.FluidDynamicsApplication.adjoint_fluid_analysis import AdjointFluidAnalysis if (IsDistributedRun()): raise...
import os import pandas as pd import numpy as np import pprint import re import tweepy from tweepy import OAuthHandler from textblob import TextBlob import json import sqlalchemy from sqlalchemy.ext.automap import automap_base from sqlalchemy.orm import Session from sqlalchemy import create_engine from flask im...
import os import torch import random import argparse import numpy as np from tqdm import tqdm import matplotlib.pyplot as plt from sklearn.decomposition import PCA from sklearn.preprocessing import StandardScaler from dataset import add_args_to_string from training_VAE import VarAutoencoder from dataset import DoubleM...
# ***corey pandas*** import json with open ('s3.json') as f: new_string = json.load(f) with open('claims2.json') as f2: new_string2 = json.load(f2) # for new_list in new_strig: # print(new_list) # print(new_strig) def sorting(item): if isinstance(item, dict): return sorted((key, sorting(values)...
# Programming Exercise 5-12 # # Program to find the greater of two integers. # This program accepts two integers, # passes them to a function that compares them, # and displays which one is greater. # define the main function def main(): # Define local variables to hold two integers int_1 = 0 ...
#!/usr/bin/env python # coding=utf-8 ''' @author: Zuber @date: 2019/8/8 9:38 ''' import os from selenium import webdriver from selenium.webdriver.chrome.options import Options from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import exp...
# This file contains the stack ADT from collections import deque class Stack: # Create a deque stack = deque() # This function pushes an element onto the stack def pushStack(self, newElement): self.stack.append(newElement) return # This function pops the element from the stack ...
from tkinter import * from PIL import ImageTk, Image from json import * constants = load(open('utils/constants.json')) DEFAULT_COLOR = 'AntiqueWhite1' class Application(): def __init__(self, parent): self.parent = parent self.load_images() self.load_hud() self.label01 = Label(...
"""scanf.py: scanf-style input for Python. Danny Yoo (dyoo@hkn.eecs.berkeley.edu) The initial motivation for this module was based on a posting on Python-tutor: http://mail.python.org/pipermail/tutor/2004-July/030480.html I haven't been able to find a nice module to do scanf-style input. Even the Library Refere...
from binance.client import Client import pandas as pd import os import matplotlib.pyplot as plt import numpy as np from sklearn import preprocessing import talib from pytrends.request import TrendReq class Features(): API, API_SECRET = '', '' FEATURE_LIST = { "price_change" : ['1','2','4','6','12','24'...
while True: quantidade = int(input()) if quantidade == 0: break suspeitos = list(map(int, input().split())) indice_maior = suspeitos.index(max(suspeitos)) suspeitos[indice_maior] = 0 assassino = suspeitos.index(max(suspeitos)) + 1 print(assassino)
import extractText url = "https://cdn.fbsbx.com/v/t59.2708-21/87471654_129388618504729_4629126029485539328_n.pdf/CV-Flipkart.pdf?_nc_cat=110&_nc_sid=0cab14&_nc_oc=AQmqQ1glOGXLTCOlUaMTUHrjtDyFhRlEr_TNHzZlIny6O51sy_pbl-gqEohpXZGLw37PJWaDfb9Td03XJKmPKcNK&_nc_ht=cdn.fbsbx.com&oh=f673186b4a1ad7e03d357c4e2aacde8a&oe=5E6068...
from codecs import open from os import path from setuptools import Extension, find_packages, setup here = path.abspath(path.dirname(__file__)) with open(path.join(here, 'README.rst'), encoding='utf-8') as f: long_description = f.read() setup( name='search_in_files', version='0.0.6', description='A...
import streamlit as st import pandas as pd import seaborn as sns import matplotlib.pyplot as plt def info(): df = pd.read_csv('data/happiness_combined_year copy 2.csv') df = df.drop(columns=['Unnamed: 0'],axis=1) avg = df.groupby(['Country']).mean().sort_values(by='Happiness Score',ascending=False).reset_index() ...
def topla(*sayilar): toplam = 0 for sayi in sayilar: toplam += sayi return toplam print("Sayıların Toplamı :", topla(1, 3, 5, 7, 10, 15, 20, 65, 15))
import pandas as pd import matplotlib.pyplot as plt import statsmodels.graphics.tsaplots as tsplots import statsmodels.tsa.arima.model as arma import numpy as np import helper_functions_4 import statsmodels.formula.api as smf import statsmodels.tsa.stattools as stats def main(): # data is a dataframe, first colum...
import numpy import theano import theano.tensor as T import TP1 rng = numpy.random def escala_gris(img): return numpy.dot(img,[0.3333,0.3333,0.3333]) # Media de los 3 canales def procesar_imagen(img): img = TP1.normalize(img) img = TP1.resize_image(img,28) img = escala_gris(img) return img.flatten...
import turtle turtle.setpos(-400, 0) pen = turtle.Pen() print(" Para criarmos o mosaico desejado, precisamos de O-O-O-O como \ codigo de entrada, e O yo-pO+xO+bOoO-rO-gO+bO como regra. Além de 4 Repetições ") inicio = str(input("Digite o código de entrada: ")) regra = str(input("Digite a regra desejada: ")) re...
def checkio(n): return feed(n, 1, 0) def feed(n, pigeon, last): if n <= last: return last if n <= pigeon: return n return feed(n - pigeon, 2 * pigeon - last + 1, pigeon) if __name__ == '__main__': assert checkio(0) == 0, 0 assert checkio(1) == 1, 1 assert checkio(2) == 1,...
class Solution(object): def permuteUnique(self, nums): """ :type nums: List[int] :rtype: List[List[int]] """ res = self.nonRecursive(nums) return res def recursive(self, nums, i, res): if i >= len(nums): res.append(nums[:]) retur...
from itertools import permutations def lexicographical_combos(word, rank): perm = sorted(''.join(chars) for chars in permutations(word)) return(perm[rank-1]) n = int(input()) while n: word, rank = input().split() print(lexicographical_combos(word, int(rank))) n -= 1
import cv2 import numpy as np from matplotlib import pyplot as plt rgb_min_blue = np.uint8([[[50, 50, 200]]]) rgb_max_blue = np.uint8([[[100,0,255 ]]]) # hsv_min = np.array([110,50,50]) # hsv_max = np.array([130,255,255]) hsv_max = cv2.cvtColor(rgb_max_blue,cv2.COLOR_BGR2HSV) hsv_min = cv2.cvtColor(rgb_min_blue,cv2....
import random import csv import numpy as np from collections import Counter from itertools import chain from .dataloader import Dataloader from ..metric import MetricChain, PerlplexityMetric, BleuCorpusMetric, SingleDialogRecorder from .._utils import trim_before_target class MultiTurnDialog(Dataloader): r"""Base cla...
__author__ = 'larsmaaloee' import os import env_paths as ep import matplotlib import numpy as np from DBN.dbn import generate_output_for_test_data, generate_output_for_train_data, generate_input_data_list from DataPreparation.data_processing import get_all_class_indices, get_all_class_names from heapq import nsmallest...
def trim_suffix(text, suffix): """Strip a suffix from text, if it appears (otherwise return text unchanged)""" if not text.endswith(suffix): return text return text[: len(text) - len(suffix)]
#!/usr/bin/env python3 # Copyright (c) 2018-2020 Bitcoin Association # Distributed under the Open BSV software license, see the accompanying file LICENSE. """ Check that orphan transaction with max allowed size is accepted. """ from test_framework.blocktools import create_transaction, create_coinbase, create_block fro...
# MIT LICENSE # # Copyright 1997 - 2020 by IXIA Keysight # # 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,...
from django.contrib import admin from django.contrib.auth.admin import UserAdmin from .forms import CustomUserChangeForm, CustomUserCreationForm from .models import CustomUser, UsersCount class CustomUserAdmin(UserAdmin): add_form = CustomUserCreationForm form = CustomUserChangeForm model = CustomUser ...
from datetime import timedelta from django.db import models from django.utils import timezone class TelegramUser(models.Model): """ Telegram user """ id = models.BigIntegerField(primary_key=True, unique=True) username = models.CharField(max_length=120, blank=True) first_name = models.CharFiel...
def factorial(n): # return 1 if n == 0 or n == 1 else n * factorial(n-1) if n == 0 or n == 1: return 1 else: a = n * factorial(n - 1) return a # return n*factorial(n-1) n = int(input("enter number")) print("facorial number of {0} is {1} ".format(n, factorial(n)))
from scipy import stats from spux.distributions.tensor import Tensor from units import units from auxiliary import auxiliary from spux.distributions.merge import Merge # define an error model class Error (object): def __init__ (self, scalar = True): self.scalar = scalar # auxiliary dataset loader ...
from __future__ import unicode_literals from django.utils.translation import ugettext_lazy as _ from common import MayanAppConfig from common.classes import Package class AppearanceApp(MayanAppConfig): name = 'appearance' verbose_name = _('Appearance') def ready(self): super(AppearanceApp, self...
#!/usr/bin/env python import os, sys current_dir = os.getcwd() test_suite_path = os.path.dirname(os.path.dirname(current_dir)) sys.path.append(test_suite_path) import testing problem_number = testing.parse_argv() current_dir = os.getcwd() + '/' exec_path = current_dir + str(problem_number) + '.py' testing.check...
from apps.core.models.model_base import ModelBase from django.db import models class Participation(ModelBase): class Status(models.TextChoices): READY = 'ready' PARTICIPATED = 'participated' SUCCESS = 'success' FAILURE = 'failure' mission = models.ForeignKey("Mission", related...
import numpy as np m = int(input('Enter rows')) n = int(input('Enter columns')) l = [] b = [] for i in range(m): l = [] for j in range(n): e = int(input('Enter element: ')) l.append(e) b.append(l) print("Original matrix") print(np.matrix(b)) for i in range(m): for j in range(n): ...
################################### # CS B551 Fall 2020, Assignment #3 # # Your names and user ids: # Alex Fuerst (alfuerst), Andrew Corum (amcorum), Kaitlynne Wilkerson (kwilker) # # (Based on skeleton code by D. Crandall) # import random import math import define import prob import simple import viterbi # We've ...
def init(): fieldID = sm.getFieldID() oldFieldID = sm.getOldFieldID() warp = True if oldFieldID == 0: map = 100000000 portal = 0 sm.chat("(Portal) Cannot find your previous map ID, warping to Henesys.") elif oldFieldID == 910000000: sm.chat("(Portal) Cannot find your ...
## HW5 - Implementing a Greedy Motif Finder ## Due 10am on Wed., 3/8/17 # Unfinished Portions: # - Didn't get to the point generator, or most of the Greedy Algorithm, took an unreasonably long time fixing bugs on the frequency table. ## Nick Egan # Time Estimate: 4 #Notes: # #DB indicates lines used for debugging/...
import csv import django django.setup() import os from sefaria.model import * files = [f for f in os.listdir(".") if f.endswith(".csv")] for f in files: prev_ref = None print(f) with open(f, 'r') as open_f: for row in csv.reader(open_f): ref, comm = row try: ref = Ref(ref) if prev_...
class MyMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): if 'id' in request.session: request.META['end-user'] = request.session.get('id') else: request.META['end-user'] = None if 'Authorization...
from abc import abstractmethod from typing import Dict, List from src.dialog.common.manage_entity.ManageEntityDialogMode import ManageEntityDialogMode from src.property.Property import Property from src.property.PropertyValue import PropertyValue from src.template.property.PropertyTemplate import PropertyTemplate cl...
from enum import Enum class EncodingType(Enum): ADJACENCY_ONE_HOT = "adjacency_one_hot" ADJACENCY_MIX = 'adjacency_mix' PATH = "path" GCN = "gcn" BONAS = "bonas" SEMINAS = "seminas" COMPACT = 'compact'
#!/usr/bin/env python import cv2 import random import os # def check_empty(file): # return os.stat(file).st_size == 0 # def isclose(a, b, rel_tol=.1, abs_tol=0.0): # return abs(a-b) <= max(rel_tol * max(abs(a), abs(b)), abs_tol) # def crop_save_image(image, x_offset, y_offset, width, height): # # image_pa...
import json class questions_store: def __init__(self, file_name): self.data_file = file_name def load_questions(self): self.items = [] try: with open(self.data_file) as f: data = json.loads(f.read()) self.items = data return s...
# print('让我看看你是啥', demo4.func()) from demo3 import demo7 # print(demo7) # def func2(): # return "demo2进入执行"
# Generated by Django 2.2.6 on 2019-10-15 06:27 from django.db import migrations, models import django.utils.timezone class Migration(migrations.Migration): dependencies = [ ('publications', '0001_initial'), ] operations = [ migrations.AddField( model_name='ad', ...
### Unintended solution ### # @giovannichhatta import hashlib, string, requests, sys, argparse parser = argparse.ArgumentParser() parser.add_argument("-t", "--target", help="IP address of the target.") args = parser.parse_args() if not args.target: parser.print_help() sys.exit(0) PROXY = { ...
from django.urls import path from .views import ToolListApiView,ToolDetailApiView, ToolTypesDetailApiView, ToolTypesListApiView, UserRecordView app_name = 'api' urlpatterns = [ path('', ToolListApiView.as_view(), name='tool_list'), path('detail/<tool_code>', ToolDetailApiView.as_view(), name='tool_detail'), ...
#!/usr/bin/python # -*- coding: UTF-8 -*- import xmpp def init(bot): return 50 def description(): return 'set activity status(XEP-0108)' #XEP-0108: User Mood def help(): txt = 'Set activity status bot (XEP-0108) (v0.1)\n\n' txt = txt+ 'Синтаксис: setactivity статус подстатус текст_статуса\n...
n = int(input()) for i in range(n): n1 = int(input()) arr = [int(x) for x in input().split()] arr2 = [] for j in range(n1-1): if arr[j] > max(arr[j+1:]): arr2.append(arr[j]) arr2.append(arr[n1-1]) print(*arr2)
import pytest from selenium import webdriver def pytest_addoption(parser): parser.addoption("--userType", action="store", default="lo302") parser.addoption("--browser", action="store", default="chrome") @pytest.fixture(scope="class") def setup(request): browser = request.config.getoption("browser") ...
# 导入数据集iris from sklearn.datasets import load_iris import numpy as np import matplotlib.pyplot as plt # 导入决策树DTC包 from sklearn.tree import DecisionTreeClassifier # 输出准确率 召回率 F值 from sklearn import metrics # 载入数据集 iris = load_iris() # 训练集 train_data = np.concatenate((iris.data[0:40, :], iris.data[50:90, :], iris.data[...
from django.contrib import admin from .models import Cart, Product, Reviews # Register your models here. admin.site.register(Cart) admin.site.register(Reviews) admin.site.register(Product)
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'ClassificacaoRisco.ui' # # Created by: PyQt5 UI code generator 5.13.2 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtGui, QtWidgets class Ui_FichaAmbulatorialVerso(object): def setup...
from argv.tokens import split_flag_token def parse_tokens(tokens): '''Read tokens strings into (is_flag, value) tuples: For this value of `tokens`: ['-f', 'pets.txt', '-v', 'cut', '-cz', '--lost', '--delete=sam', '--', 'lester', 'jack'] `flatten(tokens)` yields an iterable: [ ...
from inspect import signature class Page: def __init__(self, url, name, builder, auth_needed=None, description=''): self.name = name self.url = url self.auth_needed = auth_needed self.builder = builder def as_list(self, param=''): def call_builder(): if...
import os import sqlite3 import pandas as pd import numpy as np from .pybash import get_file_info def connect_to_db(path): """ Interact with a SQLite database Parameters ---------- path: str Location of the SQLite database Returns ------- conn: Connector The SQLite co...
# Generated by Django 2.0.3 on 2018-04-01 05:28 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Person', fields=[ ('id', models.AutoField(a...
import time import random from random import randint storytime = random.randint(0, 130) storytime2 = random.randint(0, 130) def intro(): print ("Hello....................") time.sleep(2) print("Welcome. You are about to engage in the difficult process of decision making. ") print("Your choices ...
import logging from typing import ( Any, Awaitable, Callable, List, Optional, Tuple, Type, Sequence, ) from guardpost.asynchronous.authentication import AuthenticationStrategy from guardpost.asynchronous.authorization import AuthorizationStrategy from guardpost.authorization import Poli...
import datetime import factory from kawaz.core.personas.tests.factories import PersonaFactory from ..models import Event class EventFactory(factory.DjangoModelFactory): FACTORY_FOR = Event pub_state = 'public' title = '焼肉食べまくる会' period_start = factory.LazyAttribute(lambda o: datetime.datetime.now() ...
from Util.LoggingHelper import log_info_message from datetime import datetime async def get_reaction_wheel_status(rf_controller): try: log_info_message('Sending Get Reaction Wheel Command') await rf_controller.send(7) while True: print('Waiting for response...') rece...
""" 不可逆加密 hashlib模块简介: hashlib模块为不同的安全哈希/安全散列(Secure Hash Algorithm)和 信息摘要算法(Message Digest Algorithm) 实现了一个公共的、通用的接口,也可以说是一个统一的入口。 因为hashlib模块不仅仅是整合了md5和sha模块的功能, 还提供了对更多中算法的函数实现, 如:MD5,SHA1,SHA224,SHA256,SHA384和SHA512。 hashlib模块使用步骤: 1)获取一个哈希算法对应的哈希对象(比如名称为hash): 可以通过 hashlib.new(哈希算法名称, 初始出入信息)函数,来获取这个哈希对象, 如has...
""" The scramblesuit module implements the ScrambleSuit obfuscation protocol. The paper discussing the design and evaluation of the ScrambleSuit pluggable transport protocol is available here: http://www.cs.kau.se/philwint/scramblesuit/ """ from twisted.internet import reactor import obfsproxy.transports.base as bas...
#!/usr/bin/python # -*- coding: utf-8 -*- import datetime import time def print_time(func): # function def function_1(x, y): # parameters print datetime.datetime.now() res = func(x, y) print datetime.datetime.now() return res return function_1 @print_time def ...
def palindromeRearranging(inputString): w=''.join(sorted(inputString)) if w==inputString and len(w)%2==1: #edge case:string consists of only one unique character return True if len(w)%2==0: for char in w: if w.count(char)%2!=0: return False return T...
import starkbank from unittest import TestCase, main from starkcore.error import InputErrors from tests.utils.user import exampleProject starkbank.user = exampleProject class TestDarfPaymentLogGet(TestCase): def test_success(self): logs = list(starkbank.darfpayment.log.query(limit=10)) logs = l...
def is_sequence(arg): """ Check whether an argument is iterable, but not a string.\n :param arg: argument to check :return: True if the argument is a non-string, iterable. """ return not(hasattr(arg, "strip") and (hasattr(arg, "__getitem__") or hasattr(arg, "__iter...
""" Well Registry ORM object. """ from django.conf import settings from django.core.exceptions import ValidationError from django.core.validators import RegexValidator from django.db import models from smart_selects.db_fields import ChainedForeignKey class ArbitraryDecimalFields(models.DecimalField): """ Su...
#!/usr/bin/python3 from pprint import pprint from subprocess import Popen, PIPE import sys from flask import Flask, url_for, jsonify, request, send_from_directory, abort app = Flask(__name__) @app.route("/",methods=['POST']) def echo(): json = request.get_json() repo_name = json['repository']['name'] rep...
from scrapy import Spider from bcp.items import NewsItemLoader class LaRepublicaSpider(Spider): name = 'la_republica' start_urls = [ 'https://larepublica.pe/politica/1421312-pedro-chavarry-fiscal-pedir-prision-preventiva-extitular-ministerio-publico-yvan-montoya', ] def parse(self, response):...
# 거스름돈 coins = [500, 100, 50, 10, 5, 1] n = 1000 - int(input()) cnt = 0 for coin in coins: cnt += n // coin n %= coin print(cnt)
from django.shortcuts import get_object_or_404, render from django.views import View from django.utils import timezone from utilities.views import GetReturnURLMixin from netbox_plugin_gpon.netbox_plugin_gpon.views.generic import * from . import forms from .models import * from . import tables from . import filters ...
# https://leetcode.com/problems/implement-strstr/description/ class Solution(object): def strStr(self, haystack, needle): """ :type haystack: str :type needle: str :rtype: int """ if not needle: return 0 haystack_len = len(haystack) needl...
#!/usr/bin/env from __future__ import print_function import argparse def bin(s): return str(s) if s<=1 else bin(s>>1) + str(s&1) def get_muggle_expr(number): result = "" bin_number = bin(number) for i in xrange(0, len(bin_number)): if bin_number[i] == "1": order = len(bin_number) ...
from core.object import Object from physics.rect import Rect from graphics.prims3d.cube import Cube from core.vec2 import Vec2 from core.vec3 import Vec3 class Block(Rect): def onAttach(self): self.defaultVar("material",{}) self.defaultVar("stretchMaterial",True) self.defaultVar("...
# -*- coding: utf-8 -*- from odoo import api, fields, models, _ from odoo.exceptions import UserError from company import WEEK_DAYS class SubActivityStartingTime(models.Model): _name = 'op.subactivity.starting.time' _description = 'A set of subactivity has a set of preferred starting Time.' _rec_name = 'f...
#-*- coding: UTF-8 -*- import json import math import re import sys import time import pandas import pp import scrapy # sys reload(sys) sys.setdefaultencoding('utf8') #load funcs from Parse_Init import * from SaveData import * from PP_Init import * #basesetting def Init(): #params website...
import inspect try: from typing import GenericMeta # python 3.6 except ImportError: # in 3.7, GenericMeta doesn't exist but we don't need it class GenericMeta(type): pass def annotation_to_string(annotation): if annotation is inspect.Signature.empty: return "" if inspect.isclass(...
# Recurrent Neural Network # Part 1 - Data Preprocessing # Importing the libraries import numpy as np import matplotlib.pyplot as plt import pandas as pd # Importing the training set fore_step = 3 time_step = 60 train_samples = 1144 test_samples = 20 feature_size = 2 volume_downsize = 10000 dataset_train = pd.read...
# relative from .abstract_node_msg_registry import AbstractNodeMessageRegistry class DomainMessageRegistry(AbstractNodeMessageRegistry): """A class for registering messages that can be used by the domain service."""
from txt_game.tic_tac_toe.statistics import read_statistics, save_statistics, gen_game_stats from txt_game.tic_tac_toe.comp import make_move as comp_move from txt_game.tic_tac_toe.settings import modes from txt_game.rendering import rend_board, clr import random as rnd def run_game(settings, mode): """ Start ...
from flask_wtf import FlaskForm from wtforms import StringField, PasswordField from wtforms.validators import DataRequired class ClientForm(FlaskForm): first_name = StringField('imie', validators=[DataRequired()]) last_name = StringField('nazwisko', validators=[DataRequired()]) class LoginForm(FlaskForm): ...