text
stringlengths
8
6.05M
import re import numpy as np import pandas as pd from sklearn.model_selection import train_test_split import torch from torch.utils.data import Dataset, DataLoader from torch._six import container_abcs, int_classes, string_classes from torchvision import transforms from utils.transforms import DropInfo, Cutout, GridM...
import sys if len(sys.argv)!=2: print("Must call program: PROGRAM_NAME FILENAME") exit() print("Opening " + sys.argv[1] + "...\n") export = "new-" + sys.argv[1] f = open(export, "w+") print("Converting and exporting to " + export + "...\n") with open(sys.argv[1]) as inputFile: del_space = False for line...
import pandas as pd import torch from torch.utils.data import DataLoader from tqdm import tqdm from utils.data import data_frames, ForecastDataset from nn import Model def infer(model, loader): """Infer unit sales of next days with a trained model. Args: model = [nn.Module] trained model lo...
from pcc_stats import diehard_pybites, Stats def test_diehard_pybites(): res = diehard_pybites() assert res == Stats(user='clamytoe', challenge=('01', 7))
import urllib3 from urllib.parse import urlparse from bs4 import BeautifulSoup PAGE_NOT_FOUND = "Page not found" MEDIA_NOT_FOUND = "Media not found" class HeadlineCrawler(object): def __init__(self): self.http = urllib3.PoolManager() def crawl_url_title(self, url): soup = BeautifulSoup(self...
from code import Dog class PetDog(Dog): def __init__ (self, ) pass
#!/usr/bin/env python # -*- coding: utf-8 -*- import urllib2 from bs4 import BeautifulSoup import ast webpage = "http://www.dwd.de/DE/wetter/wetter_weltweit/europa/wetterwerte/_node.html" try: web_page = urllib2.urlopen(webpage) except urllib2.HTTPError: print("HTTPERROR!") except urllib2.URLError: prin...
def share_price(invested, changes): return '{:.2f}'.format( reduce(lambda a, b: a + (a * (b / 100.0)), changes, invested))
import codecs import csv from datetime import timedelta import io import subprocess from time import sleep import localSettings import requests from selenium.webdriver.common.action_chains import ActionChains from logger import * # Read from testPartners csv the test details(base URL, credentials, Practitest ID ...
''' Created on Jul 14, 2013 @author: Justin ''' import os from webapp2 import WSGIApplication, Route from google.appengine.ext import db root_dir = os.path.dirname(__file__) template_dir = os.path.join(root_dir, 'templates') class Users(db.Model): u_name = db.StringProperty(required = True) p_hash = db.Stri...
#!/usr/bin/python3 """ Making use of HTTP non-200 type responses. https://tools.ietf.org/html/rfc2616 # rfc spec describing HTTP 1xx - informational 2xx - success / ok 3xx - redirection 4xx - errors 5xx - server errors """ from flask import Flask from flask import redirect from flask import url_for from flask import r...
import mxnet as mx def fire_module(data, squeeze_depth, expand_depth, prefix): fire_squeeze1x1 = mx.symbol.Convolution(name='{}_squeeze1x1'.format(prefix), data=data, num_filter=squeeze_depth, pad=(0,0), kernel=(1,1), stride=(1,1), no_bias=False) fire_relu_squeeze1x1 = mx.symbol.Activation(name='{}_relu_squeez...
from PyQt5 import QtWidgets from Graphics import Ui_MainWindow from ConnectionPackage.ConnectionModule import ConnectionModule from SignalGenerationPackage.SignalGenerationModule import SignalGenerationModule from FrequencySettingPackage.FrequencySettingModule import FrequencySettingModule from LogVisualizationPackage....
# -*- coding: utf-8 -*- # Generated by Django 1.11.2 on 2018-05-08 10:39 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_depende...
# import threading # from peewee import _atomic # from peewee import SqliteDatabase # from peewee import transaction # from playhouse.tests.base import database_class # from playhouse.tests.base import mock # from playhouse.tests.base import ModelTestCase # from playhouse.tests.base import skip_if # from playhouse.tes...
def paul(arr): scores = {'kata': 5, 'Petes kata': 10, 'eating': 1} result = sum(scores.get(a, 0) for a in arr) if result < 40: return 'Super happy!' elif result < 70: return 'Happy!' elif result < 100: return 'Sad!' return 'Miserable!'
from __future__ import print_function #输出格式兼容 import os from PIL import Image path = 'D:/Downloads/Cache/Desktop/Baselines/DualGAN-master/test/50000/cityscapes/leftImg8bit/frankfurt/' names = os.listdir(path) for name in names: img =Image.open(path+name) print(img.format, img.size, img.mode)
#Taking input from users print "How old are you?", age=raw_input() print "How tall are you?", height=raw_input() print "How much do you weigh?", weight=raw_input() print "So you're %r years old, %r feet in height and %r kgs heavy." %(age,height,weight)
import csv from default_clf import DefaultNSL from itertools import chain from time import process_time import numpy as np import pandas as pd NUM_PASSES = 100 NUM_ACC_PASSES = 50 TRAIN_PATH = 'data/KDDTrain+.csv' TEST_PATH = 'data/KDDTest+.csv' ATTACKS = { 'normal': 'normal', 'back': 'DoS', 'land': 'Do...
# Use the file name mbox-short.txt as the file name fname = input("Enter file name: ") fh = open(fname) average = 0.0 N = 0 # Total number for line in fh: if not line.startswith("X-DSPAM-Confidence:") : continue stripped_line = float(line[20:27]) average = average + stripped_line N += 1 average = averag...
import numpy as np import pandas as pd import matplotlib.pyplot as plt df = pd.read_csv('https://s3.amazonaws.com/content.udacity-data.com/courses/ud359/titanic_data.csv') total_males = 0 total_females = 0 survivor_males = 0 survivor_females = 0 for passenger_index, passenger in df.iterrows(): passenger_id = pas...
from __future__ import division import math class Vector(object): def __init__(self, x, y): self.x=x self.y=y def magnitude(self): return math.sqrt(self.x**2+self.y**2) def normalize(self): newx=self.x/self.magnitude() newy=self.y/self.magnitude() return Vecto...
import cv2 import os import numpy as np import random import shutil from tqdm import tqdm def get_filelist(path, ext=[]): file_list = [] files = os.listdir(path) for f in files: if f.split('.')[-1] in ext: file_list.append(f) return file_list def load_img(path, grayscale=False): ...
''' Owner: Luis Eduardo Hernandez Ayala Email: luis.hdez97@hotmail.com Python Version: 3.7.x, but shouldn't have problems with 2.7.x ''' from math import sqrt, cos, sin from FussyNetwork import GaussyModel import numpy as np import random try: import matplotlib.pyplot as plt import ma...
#!/bin/env python #_*_coding:utf-8_*_ #Author:swht #E-mail:qingbo.song@gmail.com #Date:2015.11.24 #Version:V0.0.1 import centerclass import bankmanage import main import time bankdict = {'ID':1018584989,'Pass':123456,'Yue':15000} def bank_login(): centerclass.bank.Print() flag = 0 while flag <= 3: creditId = raw_...
from itertools import combinations def solution(numbers): return sorted(set([sum(i) for i in combinations(numbers, 2)]))
# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use ...
from django.contrib import admin from .models import * # Register your models here. admin.site.register(Machine) admin.site.register(Maker) admin.site.register(Raw) admin.site.register(Model)
# 상근이는 매일 아침 알람을 듣고 일어난다. # 알람을 듣고 바로 일어나면 다행이겠지만, # 항상 조금만 더 자려는 마음 때문에 매일 학교를 지각하고 있다. # 상근이는 모든 방법을 동원해보았지만, # 조금만 더 자려는 마음은 그 어떤 것도 없앨 수가 없었다. # 이런 상근이를 불쌍하게 보던 창영이는 자신이 사용하는 방법을 추천해 주었다. # 바로 "45분 일찍 알람 설정하기"이다. # 이 방법은 단순하다. # 원래 설정되어 있는 알람을 45분 앞서는 시간으로 바꾸는 것이다. # 어차피 알람 소리를 들으면, 알람을 끄고 조금 더 잘 것이기 때문이다. # 이 방법...
print('hola') print('Hola Universo... ¿cómo estás?') print('Hola Universo hehe')
# coding: utf-8 # # PyCity Schools Analysis # # * As a whole, schools with higher budgets, did not yield better test results. By contrast, schools with higher spending per student actually (\$645-675) underperformed compared to schools with smaller budgets (<\$585 per student). # # * As a whole, smaller and medium ...
# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use ...
# coding: utf-8 from requests_html import AsyncHTMLSession, HTMLSession, requests def retry_session(retries=5, session=HTMLSession()): retry = requests.urllib3.util.retry.Retry( total=retries, read=retries, connect=retries, status_forcelist=(500, 502, 503, 504), ) adapter =...
from django.shortcuts import render, redirect from apps.ninja_gold.models import Wallet, Form # Create your views here. def index(request): # del request.session["activites"] wallet = Wallet(request) context = { 'total': wallet.total_gold, 'activites': wallet.activites } return re...
from pyasn1.type.univ import SequenceOf, noValue from asn1PERser.codec.per.encoder import encode_sequence_of from asn1PERser.codec.per.decoder import decode_sequence_of from asn1PERser.classes.types.constraint import SequenceOfValueSize, MAX class SequenceOfType(SequenceOf): subtypeSpec = SequenceOfValueSize(0, M...
def f(string): length = len(string) for a in xrange(1, length + 1): current = string[:a] number = length / a if current * number == string: return current, number
""" Time complexity: O(N) Space complexity: O(1) Compiled on leetcode: Yes Difficulties faced: None """ class Solution: def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode: headASize = 0 headBSize = 0 currentNode = headA while currentNode is not None:...
import json from datetime import date, timedelta from django.views.generic import TemplateView from djofx import models from djofx.utils import qs_to_monthly_report from djofx.views.base import PageTitleMixin, UserRequiredMixin class MonthlyTransactionsView(PageTitleMixin, UserRequiredMixin, TemplateView): templ...
# Generated by Django 3.2 on 2021-05-07 17:15 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('myapp', '0004_auto_20210505_1940'), ] operations = [ migrations.RenameField( model_name='equipo', old_name='fecha_puestaenmarc...
#bubble sort import random import math # 1. an outer loop decreases in size each time # 2. the goal is to have the largest no. at the end of the list when outer loop completes 1 cycle # 3. the inner loop starts comparing indexes at the begining of the loop # 4. check if list[Index] > list[Index + 1] # 5. if so s...
# -*- coding: utf-8 -*- """ Query data download (export) functionality. """ import os import datetime import base64 import logging import json from sys import stderr from django.conf import settings from django.utils.text import get_valid_filename from .tasks import zipquerydata logger = logging.getLogger(__name__)...
A=int(input("A= ")) B=int(input("B= ")) C=int(input("C= ")) print((A>0) or (B>0) or (C>0))
import torch from torch import nn from torch.nn import functional as F class DiceCELoss(nn.Module): def __init__(self): super(DiceCELoss, self).__init__() def forward(self, inputs, targets, smooth=1e-7): ce_loss = F.cross_entropy(inputs, targets) inputs = inputs.log_softmax(dim=1).ex...
# Generated by Django 2.0.2 on 2018-02-25 00:40 from django.conf import settings from django.db import migrations class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('articles', '0002_auto_20180224_1438'), ] operations = [ ...
#!/usr/bin/python3.4 # -*-coding:Utf-8 from random import randrange from math import ceil def couleur(cagnotte, mise) : """Fonction permettant de calculer le gain en cas de couleur ok""" cagnotte = ceil(cagnotte - mise + (mise * 1.5)) print("Not bad x1.5") return (cagnotte) try : cagnotte = input("Combien êtes...
#!/usr/bin/python3 from math import floor, sqrt import sys import mysql.connector def BinaryTree(r): return [r, [], []] def insertLeft(root,newBranch): t = root.pop(1) if len(t) > 1: root.insert(1,[newBranch,t,[]]) else: root.insert(1,[newBranch, [], []]) return root def insertR...
import numpy as np import cv2 def convex(): img = cv2.imread('images/lightning.png') imgray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) rows, cols = img.shape[:2] ret, thr = cv2.threshold(imgray, 127, 255, 0) _, contours, _ = cv2.findContours(thr, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE) cnt = co...
# coding=UTF-8 from numpy import * import random import operator import string bug_rate = 0.20 #read_file = "C:/Users/Chris/Desktop/7.lang3.0.1_all.csv" #save_file = "C:/Users/Chris/Desktop/7.lang3.0.1_all.csv" def chang_array(inputs): # print "str:",inputs a1 = inputs arr = [] j=0 for i in range((...
import unittest from flask import current_app from app import app, db import os class TestOnApp(unittest.TestCase): """Check some app configuration""" def setUp(self): self.app = app self.app_context = self.app.app_context() self.app_context.push() def tearDown(self): self.app_context.pop() def test_app_...
#!/usr/bin/env python3 # -*- encoding: utf-8 -*- from pwn import * context.log_level = 'debug' elf = ELF('horcruxes') A = elf.symbols['A'] B = elf.symbols['B'] C = elf.symbols['C'] D = elf.symbols['D'] E = elf.symbols['E'] F = elf.symbols['F'] G = elf.symbols['G'] call_ropme = 0x0809fffc def parse_exp(output: str) ...
from __future__ import print_function import sys import os import requests import logging import json from os.path import dirname from jsonschema import validate import importlib import pkgutil from halocli.util import Util logger = logging.getLogger(__name__) logging.root.setLevel(logging.INFO) class PluginError(Ex...
import sys import os import json import nltk import pickle import torch import torch.nn.functional as F import matplotlib.pyplot as plt plt.switch_backend('agg') import matplotlib.ticker as ticker import numpy as np def main(): data_path = os.path.join(sys.argv[1], 'valid.json') with open(data_path) as f:...
a=int(input()) s=list(map(int,input().split())) su=0 se=0 for i in range(a): if i%2==0: su=su+s[i] else: se+=s[i] print(max(su,se))
from Auth import Auth auth = Auth("auth_info.json") user_csv = open("student_info.csv", "r") user_csv.readline() for line in user_csv: split = line.split(",") username = split[2][1:-1] password = username[::-1] auth.create_user(username, password)
# This file is part of beets. # Copyright 2016, Adrian Sampson. # # 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, ...
import io import os import csv import typing import logging import datetime import traceback class InvertedFilter(logging.Filter): """Allow all records except those with the given `name`.""" def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) def filter(self, record): ...
# print("geeks", end =" ") # print("geeksforgeeks") # print("geeks", end ="") # print("geeksforgeeks") # 2 # Hacker # Rank # Sample Output # Hce akr # Rn ak # s = input("enter the string: ") # for i in range(len(s)): # if i % 2 == 0: # print(s[i], end="") # for i in range(len(s)): # if...
import patchy from limpyd import fields, database from limpyd.utils import make_key from .redis_lock import LuaLock class Lock(LuaLock): """MonkeyPatch of database.Lock to use LuaLock""" def do_release(self, expected_token): if isinstance(expected_token, bytes) and \ self.redis.con...
''' Author: Darren Daly Version: 1.0 ''' import mysql.connector class UseDatabase: def __init__(self, configuration): """ Initialisation code which executes the context manager is CREATED. """ self.host = configuration['DB_HOST'] self.user = configuration['DB_USER'] self.password = configuration['DB_PASSWORD'...
pnum = [x for x in range(2,100) if all([x%y!=0 for y in range(2,x)])] print(pnum)
from app import db from werkzeug.security import generate_password_hash, check_password_hash class User(db.Model): id = db.Column(db.Integer, primary_key=True) nickname = db.Column('nickname', db.String(250), unique=True , index=True) password = db.Column('password' , db.String(250)) def is_authentica...
import requests from time import sleep import serial import pynmea2 import argparse parser = argparse.ArgumentParser() parser.add_argument("-host", help="Host URL. E.g: http://192.168.1.8:8080/pi") args = parser.parse_args() print('Using host: ',args.host) port="/dev/ttyAMA0" ser=serial.Serial(port, baudrate=9600, tim...
import requests from bs4 import BeautifulSoup def ola(): doubls = 0 saved = 0 all = 0 alert = 0 openfile1 = open('new СAS_487.txt', "r") openfile2 = open('result_topric2.txt', "w") openfile3 = open('topric_out2.txt', "w") Cas_numbers = [] links = [] for line in openfile1: ...
# -*- coding: utf-8 -*- # Generated by Django 1.10.6 on 2017-03-26 10:31 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('admina', '0001_initial'), ] operations = [ migrations.AddField( ...
from fbchat import Client from fbchat.models import * client = Client("lukas.grasse@uleth.ca", "parkingbot123") thread_id = '527926877' #client.sendMessage('hi', thread_id=thread_id, thread_type=ThreadType.USER) client.sendLocalImage('./test.jpg', message='This is a local image', thread_id=thread_id, thread_type=Th...
import functools import os from itertools import product import pygame as pg from pygame import time from pygame.color import Color from pygame.constants import SRCALPHA, BLEND_RGBA_MULT from pygame.mixer import SoundType from pygame.surface import Surface import asset from config import TILE_WIDTH, TILE_HEIGHT, PLA...
# This file is part of beets. # Copyright 2016, Adrian Sampson. # # 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, ...
import pymysql #连接数据库 db = pymysql.connect(host = 'xxxxx',port = 3306,user = 'root',passwd = '****',database = 'xrhTest',charset = 'utf8') #获取游标 cursor = db.cursor() #数据操作 sql = 'select * from tb_stu1;' cursor.execute(sql) ret1 = cursor.fetchone() # 取一条 print(ret1) # cur.execute('INSERT INTO tb_stu1(id,name,sex,bi...
# 暴破,超时了 class Solution: def maxSubArray(self, nums: List[int]) -> int: max_sum = nums[0] for i in range(len(nums)): temp = nums[i] if temp > max_sum: max_sum = temp for j in range(i+1, len(nums)): temp += nums[j] if...
""" Projection maps store lookup tables (python dictionaries) that link PointIDs in a point cloud with pixelIDs in an image. They store many : many relationships and can store arbitrarily complicated projections ( perspective, panoramic, pushbroom etc.). PMaps only store the mapping function; see HyScene for functional...
# Copyright 2021 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import annotations import json from dataclasses import dataclass from textwrap import dedent import pytest from pants.backend.python.goals import package_dists from pant...
import requests import hmac import hashlib import base64 import time token = "YOUR TOKEN" secretKey = b"YOUR SECRETKEY" baseURL = "https://api.binance.com" pingURL = "/api/v1/ping" timeURL = "/api/v1/time" bookURL = "/api/v1/depth" recentTradeURL = "/api/v1/trades" historicalTradeURL = "/api/v1/historicalTrades" rang...
import logging import tempfile import typing from datetime import datetime import arrow from blazeutils.helpers import ensure_list try: import keg_elements.crypto as ke_crypto except ImportError: ke_crypto = None DEFAULT_KEY_SIZE = 32 log = logging.getLogger(__name__) class DecryptionException(Exception):...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- __version__ = '1.0.1' get_nvl_circle_list_query = """ SELECT ncr.id AS id, ST_FlipCoordinates(ncr.geom)::geometry AS geom, ncr.label AS label, ncr.color AS color, ncr.radius AS radius, ncr.location_id AS...
import requests import subprocess import socket urls = ['https://google.co.uk', 'https://bbc.co.uk'] ips = ["192.168.167.20", "192.168.167.6"] urlReached = [] urlNotReached = [] reached = [] not_reached = [] reverse_dns = [] def request_test(sites): for url in urls: resp = requests.get(url) respco...
from __future__ import absolute_import, division, unicode_literals import six from datetime import datetime import re from twisted.trial.unittest import SynchronousTestCase from twisted.internet.task import Clock from mimic.session import NonMatchingTenantError, SessionStore class SessionCreationTests(Synchronous...
class Configs(object): """ Configs(Routes) for the whole detection/tracking system """ def __init__(self): """ Sever or Local """ self.S_or_L = 'S' # running on sever or local environment. 's' or 'S': sever, 'l' or 'L': local # self.VID_NAME = '/Users/huike/master/video/demo....
import matplotlib as mpl mpl.use('Agg') import utils import os import time import argparse import torch import torch.utils.data import torchvision.datasets as dset import torchvision.transforms as transforms import matplotlib.pyplot as plt from tqdm import tqdm from options import TestOptions from loader import Pepe...
''' There is a new mobile game that starts with consecutively numbered clouds. Some of the clouds are thunderheads and others are cumulus. The player can jump on any cumulus cloud having a number that is equal to the number of the current cloud plus or . The player must avoid the thunderheads. Determine the minimum nu...
# Written by Sarika Azad(5172690) for COMP9021 from linked_list_adt import * class ExtendedLinkedList(LinkedList): def __init__(self, L = None): super().__init__(L) def rearrange(self): value_1 = self.head.value value_2 = self.head.next_node.value if value_2 % 2 == 1 and value_1 % 2 ==0: node = self.h...
from .meta import Meta class Module(Meta): pass
#!/usr/bin/env python #Adding the necessary libraries to parse files, alter system files, and upload to drive import argparse, os from pydrive.auth import GoogleAuth from pydrive.drive import GoogleDrive #Parses for necessary arguments of filename and folder location within documents parser = argparse.ArgumentParser(...
html_doc = """ <html><head><title>The Dormouse's story</title></head> <body> <p class="title"><b>The Dormouse's story</b></p> <p class="story">Once upon a time there were three little sisters; and their names were <a href="http://example.com/elsie" class="sister" id="link1">Elsie</a>, <a href="http://example.com/l...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- def odd_iter(): n = 1 while True: n = n + 2 yield n def _not_divisible(n): return lambda x: x%n > 0 def outputPrime(): #The first number is 2: yield 2 initial = odd_iter() while True: n = next(initial) yield n ini = filter(_not_divisible(n),initial) fo...
from scapy.all import * from scapy.layers.inet import * # scapy def tcp_syn(): target_ip = "192.168.106.3" target_port = 9000 ip = IP(src=RandIP(), dst=target_ip) tcp = TCP(sport=RandShort(), dport=target_port, flags="S") raw = Raw(b"X"*1024) p = ip / tcp / raw send(p, loop=1, verbose=0) ...
from sklearn.neighbors import KNeighborsRegressor from sklearn.model_selection import KFold from sklearn.datasets import load_boston from sklearn.preprocessing import scale import numpy as np from sklearn.model_selection import cross_val_score import pandas as pn data = load_boston() scale(data.data) cv = KFold(n_spli...
import cv2 import numpy as np import json import os import pandas as pd # 실습 1 # face_cascade = cv2.CascadeClassifier('../0706_data/haarcascade_frontalface_default.xml') # # img = cv2.imread('../0706_data/face.jpg') # gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # # faces = face_cascade.detectMultiScal...
''' Utility methods for performing database operations ''' ''' Trying to mimic a actual database server ''' import uuid users = [ { "_id": "7a7f4f7f-19fb-4266-b1cf-666158cf17fb", "first_name":"Virat", "last_name": "Kohli", "email": "imvk@gmail.com" }, { "_id": "e4...
# Bài 09: Viết hàm đếm số lần xuất hiện các ký tự trong một String # Ví dụ: # Input: ‘Stringings’ # Output: {‘S’: 1, ‘t’: 1, ‘r’: 1, ’i’: 2, ‘n’: 2, ‘g’: 2, ‘s’: 1} s = 'Stringings' my_dict = {i : s.count(i) for i in s} print(my_dict)
"""Deployment Services Classes.""" import logging from .deployabledevices import DeployableDevices from .deploymentrequests import DeploymentRequests logging.debug("In the deployment_services __init__.py file.") __all__ = ["DeployableDevices", "DeploymentRequests"]
# Generated by Django 3.1.4 on 2020-12-13 10:05 from django.conf import settings from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('Users', '0001_initial'), ] operations = [ ...
#!/usr/bin/env python #-*- coding:utf-8 -*- MY_MODULES = { 'block':'Block', 'mblock':'mBlock', 'sinblock':'sinBlock', 'videostream':'MjpegStream', }
# -*- coding: utf-8 -*- import test import auto_encoder import writer import time if __name__=="__main__": alll = time.time() # アイテム数 item = 1 # 入力次元数 num_input = 10000 # 隠れ1層のユニット数 num_hidden = 100 # イテレーション回数 iteration = 10 yy = open("../Rakuten-real-/userID150-165.csv") ...
import win32com.client import pythoncom import Login as login class XAQueryEvent : query_state = 0 def OnReceiveData(self, code): XAQueryEvent.query_state = 1 def ProcT1102(self): self = win32com.client.DispatchWithEvents("XA_DataSet.XAQuery", XAQueryEvent) self.ResFileName = "C:...
from flask import render_template from flask_login import current_user from util.logutils import loghelpers import logging logger = logging.getLogger(__name__) @loghelpers.log_decorator() def about(): # logger.debug(f"{current_user=}") # logger.debug(f"{current_user.__dict__=}") return render_template( ...
from flask import Blueprint from flask.json import jsonify from ckanpackager.lib.utils import BadRequestError, NotAuthorizedError error_handlers = Blueprint('error_handlers', __name__) @error_handlers.app_errorhandler(BadRequestError) def handle_bad_request(err): response = jsonify({ 'status': 'failed', ...
x=int(input("Enter a number")) y=int(input("Enter a second number")) if x != 0 and y!=0: H=x**2+y**2 print(H**0.5) else: print("PAY MORE ATTENTION")
from django.db import models from django import forms from django.forms import ModelForm, Textarea from .models import Post class PostForm(ModelForm): class Meta: model = Post fields = ['title', 'text', 'image'] labels = { 'title': '', 'text': '', 'imag...
import time import pandas as pd import numpy as np CITY_DATA = { 'chicago': 'chicago.csv', 'new york city': 'new_york_city.csv', 'washington': 'washington.csv' } def get_filters(): """ Asks user to specify a city, month, and day to analyze. Returns: (str) city - name o...
#!/usr/bin/env python3 import sys def Hours(): try: num = int (sys.argv[1]) if num < 0 : raise ValueError ('ValueError? Input number cannot be negative') h, m = divmod(num, 60) print ("{} H, {} M".format(h, m)) except ValueError: print ('V...