text stringlengths 8 6.05M |
|---|
# Generated by Django 3.0.3 on 2020-05-05 19:29
from django.conf import settings
import django.core.validators
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swa... |
from Items import Invoice, Item
def main():
print("Welcome!")
invoice = Invoice()
item_name = input ("Enter the name of the first item purchased.")
while (len(item_name) > 0):
item_count = int(input ("How many " + item_name + " were purchased? "))
item_price = float(input... |
# shows a user's playlists (need to be authenticated via oauth)
import sys
import spotipy
import spotipy.util as util
def show_tracks(tracks):
print '==============='
print tracks['items']
print '==============='
for i, item in enumerate(tracks['items']):
track = item['track']
output =... |
from xml.sax.saxutils import escape
class TmxFile:
def __init__(self, file_path, src_lang):
self._file_path = file_path
self._src_lang = src_lang
self.add_header()
def add_header(self):
with open(self._file_path, 'w', encoding='utf8') as f:
f.write(r'<?xml version=... |
# test = input("waiting for you: ")
#
# test #ignored...
#
#
#
#
test = 5
# print(test+"ok") #not working
print(5+5)
print("test"+"ok")
print(4*"ok") #whoaaaaa...
print(int("4"))
# print(int("4f"))
# print("okok" - "ok")
|
###Estudos dos laços
###While
###Interropendo repetições while
nome = 'Marccus'
idade = 18
print(f'O {nome:->20} tem {idade:.2f} anos.!')#F-String |
# coding=utf-8
# Copyright 2018 The Google AI Language Team Authors and The HugginFace Inc. team.
#
# 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/LICENS... |
import cv2
import numpy as np
from matplotlib import pyplot as plt
img = cv2.imread('falcon_heavy.jpg')
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
e1 = cv2.getTickCount()
# your code execution
rocket = img[22:123,80:100]
img[22:123,40:60] = rocket
e2 = cv2.getTickCount()
time = (e2 - e1)/ cv2.getTickFrequency()
p... |
from django.apps import AppConfig
class ListyConfig(AppConfig):
name = 'listy'
|
import telegram
from typing import Tuple, Optional, List
from core.TelegramMessageWrapper import TelegramMessageWrapper
import logging
logger = logging.getLogger(__name__)
class TelegramPresenter:
def __init__(self, bot: telegram.Bot):
self._bot = bot
def send_message(self,
ch... |
import tkinter as tk
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BOARD) # to use Raspberry Pi board pin numbers
GPIO.setup(3, GPIO.OUT) # set up GPIO output channel
mainwindow=tk.Tk()
mainwindow.title('Test ')
mainwindow.geometry('640x340')
my_label=tk.Label(mainwindow,text="My First UI", font=("Arial... |
num_pieces = int(input())
library = {}
output = []
while True:
while num_pieces > 0:
piece, composer, note_key = input().split('|')
if piece not in library:
library[piece] = {'name': composer, 'note_key': note_key}
num_pieces -= 1
command = input().split('|')
act = comman... |
def geometric_sequence_elements(a, r, n):
num = a
output = ''
for _ in range(n):
output+='{}, '.format(num)
num = num * r
return output[:-2]
'''
In your class, you have started lessons about geometric progression.
Since you are also a programmer, you have decided to write a function
... |
import pygame
import glob
from threading import Thread
def get_alarm_sound():
alarmArray = glob.glob('alarm/*')
return alarmArray[0]
class AlarmHandler:
def __init__(self, src=0):
self.stopped = False
self.src = get_alarm_sound() if src == 0 else src
self.objectID = None
def... |
from .cifar10_dataset import *
from .load_dataset import * |
preçoNormal = float(input('Digite o preço do produto: '))
print(''' FORMAS DE PAGAMENTO
[1] A vista Deinheiro/Cheque
[2] Á vista no cartão
[3] 2x no Cartão
[4] 3x ou Mais no cartão
''')
opcPag = int(input('Qual a forma de Pagamento?: '))
if opcPag == 1:
valorFinal = preçoNormal * 0.90
print('O valor fica em R$... |
# print out the first n primes
import numpy as np
import matplotlib.pyplot as plt
import sys
import math
if len(sys.argv) < 3:
n = 1000
else:
n = sys.argv[1]
def is_prime(n):
if n % 2 == 0 and n > 2:
return False
return all(n % i for i in range(3, int(math.sqrt(n)) + 1, 2))
def get_primes(... |
import sqlite3
from PasswordRecovery import Ui_Dialog
from PyQt5 import QtCore, QtWidgets
from AdminWindow import Ui_AdminWindow
from PyQt5.QtWidgets import QMessageBox
from Usercreation import Ui_Registration
class Ui_MainWindow(object):
def open_admin_window(self):
"""
After succesfull login to ... |
# Copyright 2021 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
import pytest
from generate_docs import DocUrlRewriter, find_doc_urls, get_doc_slug, value_strs_iter
from pants.util.docutil import doc_url
def test_gather_value_strs():
help_info ... |
"""App related serializers."""
from rest_framework import serializers
from modoboa.admin import models as admin_models
from ... import models
class MXRecordSerializer(serializers.ModelSerializer):
"""Serializer for MXRecord."""
class Meta:
model = admin_models.MXRecord
fields = ("name", "a... |
from .kv_clients import MemcachedClient
from .query import MemcachedQuery |
# Рассмотрим следующее объявление классов
class A:
pass
class B(A):
pass
class C:
pass
class D(C):
pass
class E(B, C, D):
pass
# Какие последовательности могут являться корректным порядком разрешения методов для класса E?
E, B, C, D, A, object
E, B, A, C, D, object
E, B, D, C, A, object
E, B,... |
"""ChunkSet class.
Used by the OctreeLoader.
"""
from __future__ import annotations
from typing import TYPE_CHECKING, Dict, List, Set
if TYPE_CHECKING:
from napari.components.experimental.chunk._request import OctreeLocation
from napari.layers.image.experimental.octree_chunk import OctreeChunk
class ChunkS... |
#!/usr/bin/env python
##############################################################################
#
# NAME: SRM-probe
#
# FACILITY: SAM (Service Availability Monitoring)
#
# COPYRIGHT:
# Copyright (c) 2009, Members of the EGEE Collaboration.
# http://www.eu-egee.org/partners/
# Lice... |
from setuptools import setup, find_packages
setup(
name='fasth',
version='0.1',
packages=find_packages(),
install_requires=[
'screed',
'click',
'biopython'
],
author='Jordan Gumm',
author_email='jordan@variantanalytics.com',
description='A tool for quick fas... |
from ..type import SimpleType
class NullType(SimpleType):
def __init__(self):
super(NullType, self).__init__()
self.typereference = "NULL"
|
import tensorflow as tf
import numpy as np
import functools
import argparse
import glob
import json
import os
from scipy.io import wavfile
from dataset import nsynth_input_fn
from models import GANSynth
from networks import generator, discriminator
from utils import Dict
from sys import exit
parser = argparse.Argu... |
import os
import sys
import cv2
from multiprocessing.dummy import Pool as ThreadPool
if sys.version_info[0] == 2:
import xml.etree.cElementTree as ET
else:
import xml.etree.ElementTree as ET
voc_dict = {
'aeroplane' : 0,
'bicycle' : 1,
'bird' : 2,
'boat' : 3,
'bottle' : 4,
'bus' : 5,
... |
txt = input()
cro_alpha = ['dz=','c=', 'c-' ,'d-','lj','nj','s=', 'z=']
for alpha in cro_alpha:
txt = txt.replace(alpha,'1')
print(len(txt)) |
# Generated by Django 2.2.6 on 2019-11-01 17:53
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('work', '0001_initial'),
]
operations = [
migrations.RemoveField(
model_name='surveyqty',
name='pole_ht',
),
... |
# 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 ... |
'''
Name: Neil Shah
UCID: ns642
Section: 005
'''
import sys
from socket import*
serverIP = "192.168.1.122"
serverPort = 8000
dataLen = 1000000
#Create a UDP socket
serverSocket = socket(AF_INET,SOCK_DGRAM)
#Assign IP address and port number to socket
serverSocket.bind((serverIP, serverPort))
print... |
import os
import torch
from torch.autograd import Variable
def make_folder(path, version):
if not os.path.exists(os.path.join(path, version)):
os.makedirs(os.path.join(path, version))
def tensor2var(x, grad=False):
if torch.cuda.is_available():
x = x.cuda()
return Va... |
from datetime import datetime, timedelta
import time
import smtplib
import email.utils
from email.mime.text import MIMEText
from privateConstants import *
def toMsEpoch(date):
tt = datetime.timetuple(date)
sec_epoch_loc = int(time.mktime(tt) * 1000)
return sec_epoch_loc
def fromMsEpoch(ms):
s = ... |
# -*- coding: utf-8 -*-
"""
_version.py
~~~~~~~~~~~
Provides Viki version information.
:license: Apache2, see LICENSE for more details.
"""
__version__ = "0.0.1.dev2"
__all__ = ["__version__"] |
from time import time
def isPrime(n):
if n%2 == 0 and not(n==2):
return False
for i in range(3,n,2):
if n%i == 0:
return False
return True |
#!/usr/bin/python
import sys
oldWeekday = None
sum = 0
count = 0
def printline (key, value): print key, "\t", value
def printResult (weekday, sum, count):
if sum == 0 or count == 0:
printline(weekday, 0)
else:
printline(weekday, (sum/count))
for line in sys.stdin:
data = line.strip().split("\t")
... |
import os
import csv
path = os.path.join("budget_data.csv")
with open(path) as budget_data:
# using the csv.reader method to read the data
reader = csv.reader(budget_data)
# skipping the first row because it's not valuable for our analysis
header = next(reader)
# set a counter before the f... |
# try except 完善
# 账户不能为负数
# 注册功能未完成
import Choice
import datetime
import cx_Oracle as ora
import time
# 注册账号
def register(curs, conn):
conn.commit()
# 登陆系统
def logon(curs, conn):
account_id = input("请输入账号ID:")
passwd = input("请输入账号密码:")
global db_passwd
logon_date = datetime.datetime.now().strf... |
from celery import shared_task
from django.core.mail import send_mail
from django.contrib.auth import get_user_model
from django.core.mail import EmailMultiAlternatives
from django.template import loader
UserModel = get_user_model()
# 가입 메일 보내기
@shared_task
def signup_mail(subject, message, sender, receive... |
#!/usr/local/bin/python3
# -*- conding: utf-8 -*-
from flask import Blueprint
department_api = Blueprint('department', __name__, url_prefix='/api/department')
from . import views |
from appengine_django.models import BaseModel
from google.appengine.ext import db
# Create your models here.
|
from sklearn.metrics import f1_score
from sklearn.metrics import confusion_matrix
import codecs
def load_data_file(data_file):
print('loading file ', data_file)
raw_data = []
if not isinstance(data_file, list):
data_file = [data_file]
for file_name in data_file:
with codecs.open(file_na... |
import flask
import json
import os
import logging
import shlex
import time
from datetime import datetime, timedelta
app = flask.Flask(__name__)
app.config['UPLOAD_FOLDER'] = 'upload'
@app.route('/status/<user_name>')
def status(user_name):
d = datetime.today() - timedelta(days=2)
start_time = d.strftime('%Y-%... |
import math
from function import FunctionManager
from regression import minimise_loss, find_classification
from lossfunction import squared_error
from plotting import plot_ideal_functions, plot_points_with_their_ideal_function
from utils import write_deviation_results_to_sqlite
# This constant is the factor for the cr... |
# coding: utf-8
# In[1]:
# Import pandas package
import pandas as pd
# Define a dictionary containing employee data
data = {'Name':['Jai', 'Princi', 'Gaurav', 'Anuj'],
'Age':[27, 24, 22, 32],
'Address':['Delhi', 'Kanpur', 'Allahabad', 'Kannauj'],
'Qualification':['Msc', 'MA', 'MCA'... |
__author__ = 'sjaku'
import requests
from bs4 import BeautifulSoup, Tag
import csv
import pyodbc
import urllib
import os
url = "https://www.otodom.pl/oferta/dom-w-poznaniu-cena-tylko-539-000zl-ID3qyMk.html"
r = requests.get(url)
soup = BeautifulSoup(r.content, "html.parser")
#for dom in soup.find_all(... |
from flask import Flask
class Decorator_Class:
def __init__(self):
self.metric = "metric"
def decorator_p(self, value):
print(f"Value received from declaring usage of decorator {value}")
def decorator_c(func):
print("First entry")
def inner(*args, **kwargs):
... |
# 1. In the code provided, there are three mistake which stop the code to get run successfully; find those mistakes and explain why they need to be corrected to be able to get the code run
# 2. Add embedding layer to the model, did you experience any improvement?
# Task 1
# importing the required libraries
from k... |
##############################################################################
#
# Copyright (C) 2020-2030 Thorium Corp FP <help@thoriumcorp.website>
#
##############################################################################
from .product_template import *
from .lab_product import *
from .thoriumcorp_lab impo... |
from random import random
N = 30
# r = [random() for i in range(N)]
r = [0.32, 0.01, 0.23, 0.28, 0.89, 0.31, 0.64, 0.28, 0.83, 0.93, 0.99, 0.15, 0.33, 0.35, 0.91, 0.41, 0.6, 0.27, 0.75, 0.88, 0.68, 0.49, 0.05, 0.43, 0.95, 0.58, 0.19, 0.36, 0.69, 0.87]
i, m = 3, 5
# i + (M+1)m <= N
M = (N - i) // m - 1
# seq = [(r[i ... |
#!/usr/bin/env python
#-*-coding:utf-8-*-
# @File:utils.py
# @Author: Michael.liu
# @Date:2020/4/23 14:06
# @Desc: 工具类
import numpy as np
from .Relation import *
from .Sentence import *
def cut_sentences(content):
# 结束符号,包含中文和英文的
end_flag = ['?', '!', '.', '?', '!', '。', '…']
content_len = len(content)
... |
import logging
import sys
import io
import zmq
from PIL import Image
from flask import Flask
from flask import render_template
from flask import jsonify
from flask import request
from os import environ
from zmq import ssh
# initialize Flask web server
app = Flask(__name__)
app.logger.addHandler(logging.StreamHandler(... |
#!/bin/python3
nap = ""
v = 0
def new_line():
print("\n")
print("A hét napjai: ")
while v != 7:
v += 1
new_line()
if v == 1:
nap = "Hétfő"
elif v == 2:
nap = "Kedd"
elif v == 3:
nap = "Szerda"
elif v == 4:
nap = "Csütörtök"
elif v ==... |
''' setup file for mqttgateway '''
from setuptools import setup#, find_packages
from mqttgateway import __version__
# Get the long description from the README file
with open('README.rst') as f:
long_description = f.read()
setup(
name='mqttgateway',
version=__version__,
description='Framework for MQT... |
# -*- coding: utf-8 -*-
#while循环方法
sum1=0
n=99
while(n>0):
sum1 = sum1 + n
n=n-2
print('奇数的和是:%d' % sum1)
sum2=0
i=100
while(i>0):
sum2 = sum2 + i
i=i-2
print('奇数的和是:%d' % sum2) |
#coding : utf-8
#Ewan GRIGNOUX LEVERT
#Avril 2020
from PIL import Image, ImageTk
import csv
def ChargementImage(ListeNom):
ListeImages = {}
for nom in ListeNom:
img = Image.open(f"{nom}.png")
ListeImages[nom] = ImageTk.PhotoImage(img)
return ListeImages
def lireFichierCSV(nomFichier):
... |
import comm
import gevent
from itm import UCFunctionality
class ITMKatzSFE(UCFunctionality):
def __init__(self, sid, pid, channels, handlers):
self.sid = sid; self.pid = pid
self.ssid = self.sid[0]
self.Rnd = self.sid[1]
self.parties = self.sid[2]
self.x = dict( (p,None) fo... |
# coding=utf8
import joblib
import re
class SubJobProcess(joblib.JobProcess):
info_from = '卓博人才网'
def __init__(self, queue):
setting = {
'corplist_url': 'http://www.jobcn.com/search/result_servlet.ujson',
'corp_url': 'http://www.jobcn.com/position/company.xhtml?comI... |
from collections import deque
import numpy as np
import os
from PIL import Image
import pickle
import datetime
###################################################################################
class ListUtils(object):
@staticmethod
def deque_to_ndarray(deque):
deque_length = len(deque)
re... |
import os
# MANDATORY. Set this to be the Project Name.
# e.g. "RTP2021", "TIP2021", etc
PROJECT = "STIP2022"
# MANDATORY. Set this to be the Scenario Name
# Pass this as --scenario to build_network_mtc.py
assert(SCENARIO in ["NoProject","Project"])
# MANDATORY. Set this to be the git tag for checking out network pr... |
import os
import sys
import tarfile
import zipfile
import numpy as np
import tensorflow as tf
import six.moves.urllib as urllib
from PIL import Image
from io import StringIO
from collections import defaultdict
from matplotlib import pyplot as plt
sys.path.append("..")
from utils import label_map_util
from utils impor... |
# Copyright 2022 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import annotations
from dataclasses import dataclass
from pants.backend.codegen.protobuf.scala.subsystem import ScalaPBSubsystem
from pants.backend.codegen.protobuf.target... |
#!/usr/bin/python
import xsocket
from xia_address import *
import random
import sys
xsocket.set_conf("xsockconf_python.ini","hello_service.py")
xsocket.print_conf()
while(True):
try:
sock=xsocket.Xsocket(0)
if (sock<0):
print "error opening socket"
exit(-1)
... |
from sexpdata import dumps, loads, Symbol
import signal
import traceback
from euslime.bridge import EuslispResult
from euslime.handler import DebuggerHandler
from euslime.logger import get_logger
log = get_logger(__name__)
class Protocol(object):
def __init__(self, handler, *args, **kwargs):
self.handle... |
import zipfile
import sys
import os.path as op
name = 'OKMIlLVft'
while True:
path = op.join(sys.path[0],name+'.tar.gz')
zf = zipfile.ZipFile(path)
zf.extractall(path = sys.path[0],pwd = bytes(name,"utf8"))
name = zf.filelist[0].filename
name = name.split(".tar.gz")[0] |
from concurrent.futures import ProcessPoolExecutor
from functools import partial
from datasets import audio
import os
import numpy as np
from hparams import hparams
from tacotron.utils.utils import mulaw_quantize
def build_from_path(input_dirs, mel_dir, linear_dir, wav_dir, n_jobs=4):
executor = ProcessPoolExecutor... |
# 给出两个 非空 的链表用来表示两个非负的整数。其中,它们各自的位数是按照 逆序 的方式存储的,并且它们的每个节点只能存储 一位 数字。
#
# 如果,我们将这两个数相加起来,则会返回一个新的链表来表示它们的和。
#
# 您可以假设除了数字 0 之外,这两个数都不会以 0 开头。
#
# 示例:
#
# 输入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
# 输出:7 -> 0 -> 8
# 原因:342 + 465 = 807
#
# Related Topics 链表 数学
# leetcode submit region begin(Prohibit modification ... |
import autodisc as ad
import numpy as np
import plotly
def plotly_meanstd_scatter(data=None, config=None, **kwargs):
'''
param repetition_ids: Either scalar int with single id, list with several that are used for each experiment, or a dict with repetition ids per experiment.
'''
default_config = dict(
... |
#!/usr/bin/env python
# Copyright (c) 2009 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""
Verifies building a target and a subsidiary dependent target from a
.gyp file in a subdirectory, without specifying an explicit output b... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.contrib import admin
from .models import *
admin.site.register(Editorial)
admin.site.register(Genero)
admin.site.register(Autor)
admin.site.register(Dealer)
admin.site.register(Lector)
admin.site.register(Libro)
admin.site.register(Direccion)
... |
"""src/experiment_data_viz/utils.py"""
import os
import uuid
from pathlib import Path
from shutil import rmtree
import pandas as pd
import streamlit as st
def streamlit_static_downloads_folder() -> Path:
"""Create a downloads directory within the streamlit static asset directory.
HACK: This only works when ... |
import numpy as np
class LabelDictionary:
def __init__(self, uniqueLabels):
self.uniqueLabels = uniqueLabels
self.dictionary = self.getDictionary()
def getDictionary(self):
# return dict(zip(np.arange(len(self.uniqueLabels)), self.uniqueLabels))
return dict(zip(self.uniqueLabe... |
from __future__ import print_function
import sys
from operator import add
from pyspark import SparkContext
from csv import reader
import re
def check_latitude(input):
if len(input) == 0:
return 'NULL\tNULL\tNULL'
try:
x = float(input)
return 'FLOAT\tLATITUDE\tVALID' if x >= 40.47 and x... |
# Copyright 2021 Vittorio Mazzia & Francesco Salvetti. 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 ... |
from django.shortcuts import render,HttpResponse,redirect
from django.contrib.auth import authenticate,login as loginUser,logout
from todoapp.models import TODO
from django.contrib.auth.forms import UserCreationForm , AuthenticationForm
from todoapp.forms import TODOForm
from django.contrib.auth.decorators import login... |
from kadi import events
# Range 1
t_start = '2000:001'
t_stop = None
# Range 2
#t_start = '2006:220:00:00:00.000'
#t_stop = '2007:100:00:00:00.000'
# Range 3
#t_start = '2006:349:00:00:00.000'
#t_stop = '2006:354:00:00:00.000'
# Range 4
#t_start = '2006:351:00:00:00.000'
#t_stop = '2006:351:12:00:00.000'
t_event =... |
#!/usr/bin/python
"""
Implementation of the IA for the Sudoku problem,
using AC-3 and Backtracking
Miguel de la Ossa July, 2017
"""
import sys
import copy
from collections import deque, OrderedDict
from heapq import heapify, heappush, heappop
import time
_DEBUG_LEVEL = 1
def main(script, *args):
initialT... |
import math
while True:
x = int(input())
if x == 0: break
n = list(str(math.factorial(x)))
con = 0
for i in range(len(n)-1,0,-1):
if n[i] != '0':
break
con += 1
print(con) |
import numpy as np
import itertools
from sklearn.metrics import confusion_matrix
import matplotlib.pyplot as plt
class Visualize:
"""Implements different visualization methods on top of matplotlib."""
def __init__(self):
"""Initialize the size of the plots."""
plt.rcParams['figure.figsize'... |
# -*- coding: utf-8 -*-
from .models import Repo
from .views import repo
|
import tkinter as tk
from show_train import show_train
from mix_recommend import mix_re
class MainPage():
def __init__(self, window):
self.window_main = tk.Toplevel(window, bg='pink')
self.window_main.geometry('300x250')
self.window_main.title('主 界 面')
btn_train = tk.Butt... |
# 文件读写
# StringIO和BytesIO
# 操作文件和目录
# 序列化
# f.read() f.close()
from io import StringIO
f = StringIO()
print(f.write('hello'))
print(f.write(' '))
print(f.write('world!'))
print(f.getValue())
f = StringIO('hello!\nHi\nGoogbye!')
while True:
s = f.readline()
if s == '':
break
print(s.strip())
from... |
from django.shortcuts import get_object_or_404
from django.views import generic
from ..models import Question
class ResultsView(generic.DetailView):
model = Question
template_name = 'polls/results.html'
context_object_name = 'question'
pk_url_kwarg = 'question_id'
success_url = 'polls/results'
... |
from datetime import datetime
from lxml import etree
class UserParser:
type_converter = {
1: 'TV',
2: 'OVA',
3: 'Movie',
4: 'Special',
5: 'ONA',
6: 'Music'
}
def __init__(self, html, title_type):
self._html = html
self._title_type = title_t... |
#!/usr/local/bin/python3.8
# There are only two boolean
print ( True )
print ( False )
### Example of a True boolean
4.5e9 == 4.5 * (10 ** 9)
# Integer
print ( 2 + 2 )
# Float (Scientific)
print ( 2.0 + 2.0 ) |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Author : Jerry Zhu
import numpy as np
import cv2
import random
import os
# calculate means and std
train_txt_path = './train_label.csv'
# 挑选多少图片进行计算
CNum = 4572
img_h, img_w = 32, 32
imgs = np.zeros([img_w, img_h, 3, 1])
means, stdevs = [], []
... |
__author__ = "Panagiotis Garefalakis"
__copyright__ = "Imperial College London"
# The MIT License (MIT)
#
# Copyright (c) 2016 Panagiotis Garefalakis
#
# 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... |
from .uibase import UIBase
class Button(UIBase):
def __init__(self,text='',size=None):
self.html='<button>{}</button>'.format(text)
return
class Label(UIBase):
def __init__(self,text=''):
self.html='<b>{}</b>'.format(text)
return
class Field(UIBase):
def __init__(self):
self.html="<input ty... |
test_case = int(input())
for _ in range(test_case):
x, y, n = map(int, input().split())
r = n % x
# print(r, y, x)
if r >= y:
print(n - r + y)
else:
print(n - r - x + y)
|
import test
a= test.foo()
#print a
|
from osgeo import gdal, osr
import math
src_filename ='/home/user/thesis/IMG_0048_4.tif'
dst_filename = '/home/user/thesis/output.tif'
def myImageGeoReference(src_filename,dst_filename):
# Opens source dataset
src_ds = gdal.Open(src_filename)
format = "GTiff"
driver = gdal.GetDriverByName(format)
... |
# Copyright 2015 Google.
#
# 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 writing, softw... |
def calculate_net(gross, vat = 0.23):
net_price = gross / (1 + vat)
return round(net_price, 2)
print(calculate_net(100)) |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import torch
import torch.nn as nn
class MLP (nn.Module):
def __init__(self, n_inputs, n_hidden, n_classes):
super(MLP, self).__init__()
self.n_inputs = n_inputs # scalar integer. 307... |
deck=[['b',1],['b',1],['b',1],['b',2],
['b',2],['b',3],['b',3],['b',4],
['w',1],['w',1],['w',1],['w',2],
['w',2],['w',3],['w',3],['w',4]]
comp_hand=[["b",1],["b",3],["w",4]]
play_hand=deck[0:3]
print("player hand : ",play_hand)
print("computer hand : ",comp_hand)
new_comp_hand=... |
from datetime import date
anoAtual = date.today().year
sexo = str(input('Qual o seu sexo? (M)masculino (F)feminino\n')).upper()
if sexo == 'F':
print('Você não precisa fazer o alistamento')
elif sexo == 'M':
anoNasc = int(input('Em que ano você nasceu?\n'))
idade = anoAtual - anoNasc
if idade == 18:
... |
A=int(input("A= "))
B=int(input("B= "))
C=int(input("C= "))
print((A==B)or(A==C)or(B==C)) |
import pandas as pd
import copy
import uuid
class User:
def __init__(self, user_id, name, password, currentAuthority):
self.user_id = user_id
self.token = ""
self.name = name
self.password = password
self.currentAuthority = currentAuthority
def set_token(self):
... |
# coding=UTF-8
import scream
import urllib2
import mechanize
import time
from bs4 import BeautifulSoup
import threading
import unicodedata
from unique import NamesCollection
# import ElementTree based on the python version
try:
import elementtree.ElementTree as ET
except ImportError:
import xml.etr... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.