text stringlengths 8 6.05M |
|---|
from os.path import join
from xml.sax import ContentHandler, parseString
from action import Action
import kodi_baselibrary as kodi
class MessageContentHandler(ContentHandler):
def __init__(self, unit):
self.unit = unit
self.messagecodes = []
self.messages = []
self.insidelabelel... |
from django.contrib import admin
from mapFriends.models import UserProfile
#Modificar el amdin para ver los datos
admin.site.register(UserProfile) |
#-*- coding: utf-8 -*-
#####
#
#Localization for payroll to the Dominican Republic.
#Modifications to the hr.employee object.
#
#Author: Carlos Llamacho @ Open Business Solutions
#
#Date: 2013-10-22
#
#####
from openerp.osv import fields, orm
class hr_employee(orm.Model):
_name = 'hr.employee'
_inherit = 'h... |
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# 1. Exercise Webmining"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
a=256
b=256
a*b
"### Use Python as a calculator to compute 256 times 256"
]
},
{
"cell_type": "code",
... |
import numpy as np
import pickle
from sklearn.metrics import roc_auc_score
from isolation_forest.isolation_forest import IsolationForest
from isolation_forest.tree_grower_generalized_uniform import TreeGrowerGeneralizedUniform
from isolation_forest.tree_grower_basic import TreeGrowerBasic
import os
from utils im... |
# Variable to hold student continent
studentContinent = 'America'
studentSubContinent = 'South America'
if(studentContinent == 'Africa'):
print('You get Cookies and Cream flavor')
elif(studentContinent == 'Asia'):
print('You get Cookies and Cream flavor')
elif(studentContinent == 'Europe'):
print('You get ... |
"""
剑指 Offer 44. 数字序列中某一位的数字
数字以0123456789101112131415…的格式序列化到一个字符序列中。在这个序列中,第5位(从下标0开始计数)是5,第13位是1,第19位是4,等等。
请写一个函数,求任意第n位对应的数字。
"""
"""
这个题简单来说,还是最简单的找规律,排除第一位的0,然后可以发现;
123456789 总共9个数,都是1位的
101112...9899 总共90*2个数,都是两位的
100101102...998999 总共900*3个数,都是三位的
...
那么如果求第n个数,用这个数循环去寻找就知道是在哪个范围里了,比方说第365个数,因为第一个数是0,所以需要排... |
num1=int(input("Enter the first number:"))
num2=int(input("Enter the second number:"))
op= input("Enter operator:")
if(op=="+"):
print(num1+num2)
elif(op=="-"):
print(num1-num2)
elif(op=="*"):
print(num1*num2)
elif(op=="/"):
print(num1/num2)
else:
print("Wrong operator!!!!!") |
import glob
from label_sentences import label_sentences
from sklearn.model_selection import KFold
import pandas as pd
# TODO
sentences_filepaths = glob.glob("sentences/psa_research/*.csv")
for sentences_filepath in sentences_filepaths:
print(sentences_filepath)
label_sentences(sentences_filepath, mode='auto')
... |
from tkinter import Tk
from encrypt import Encrypt
from encrypt_view import EncryptView
# Encrypt 的 Controller 類別
class EncryptController:
# 設定初值
def __init__(self):
self.e = None
self.userinput = ""
self.result = ""
self.app = EncryptView(master=Tk())
self.app.nb["command"] = self.nm
self... |
#!/usr/bin/env python
# Copyright 2017 Google Inc.
#
# 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... |
# -*- coding: utf-8 -*-
class FenwickTree:
def __init__(self, nums):
self.els = [0] * (len(nums) + 2)
for i, num in enumerate(nums, 1):
self.add(i, num)
def add(self, i, k):
while i < len(self.els):
self.els[i] += k
i += i & -i
def sumPrefix(se... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2018/2/2 0:42
# @Author : Lee
# @File : bubble_sort.py
# @Software: PyCharm
from utils.common import swap
from utils.sort_test_helper import SortTestHelper
def bubble_sort(lists):
length = len(lists)
for i in range(length):
for j in range... |
"""
Copyright 1999 Illinois Institute of Technology
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, merge, publis... |
def minion_game():
string = input()
stuart = 0
kevin = 0
for j in range(len(string)):
k = len(string) - j
if string[j] == 'A' or string[j] == 'E' or string[j] == 'I' or string[j] == 'O' or string[j] == 'U':
stuart += k
else:
kevin += k
if stuart == ke... |
from django.views.generic import ListView , DetailView
from django.conf.urls import url
from django.contrib import admin
from django.contrib.auth import views as auth_views
from . import views
from Main import views as main_views
from feeds.models import Post
urlpatterns = [
url(r'^$', ListView.as_view(query... |
# Copyright (c) 2017, Intel Research and Development Ireland Ltd.
#
# 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 app... |
#!/usr/bin/env python
# coding: utf-8
# Copyright (c) Qotto, 2019
"""Contain GlobalStore
"""
from logging import getLogger
from tonga.models.structs.persistency_type import PersistencyType
from tonga.stores.base import BaseStores
from tonga.stores.errors import BadEntryType
from tonga.stores.manager.errors import Un... |
# Copyright 2019 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from collections import defaultdict
from dataclasses import dataclass
from pants.core.util_rules.source_files import SourceFiles
from pants.core.util_rules.source_files import rules as so... |
import csv
import re
import tempfile
import urllib
import requests
from django_extensions.db.models import TimeStampedModel
from storage.s3wrapper import S3Wrapper
"""
Generic mixins for reading from files in a Django management command.
The files can be a local file, a URL or on an S3 bucket.
`self.S3_BUCKET_NAME` n... |
from skimage import io
from skimage.transform import downscale_local_mean
from skimage.filters import threshold_triangle as threshold
from skimage.segmentation import clear_border, random_walker
from skimage.measure import label, regionprops
from skimage.morphology import binary_opening, square, remove_small_objects
f... |
from _typeshed import Incomplete
def k_components(G: Incomplete, min_density: float = ...) -> Incomplete: ...
|
from itertools import combinations
import operator as op
import itertools as it
from functools import reduce
import re
import json
import math
|
import logging
import pytest
from log_it import CRITICAL, DEBUG, ERROR, INFO, WARNING, log_it
LOG_LEVEL = {
"debug": DEBUG,
"info": INFO,
"warning": WARNING,
"error": ERROR,
"critical": CRITICAL,
}
def test_callable_log_levels():
for level in LOG_LEVEL:
assert calla... |
from pyUbiForge.ACU.type_readers.minimap_textures import Reader as MMClass
from pyUbiForge.ACU.type_readers.texture import Reader as TextureClass
from plugins import BasePlugin
from PIL import Image
from io import BytesIO
import struct
from typing import Union, List
import pyUbiForge
import logging
class Plugin(BaseP... |
from mido import MidiFile
import operator
def MIDIconvert(file):
mid = MidiFile(file)
sequence=[]
previous=0
for i, track in enumerate(mid.tracks):
#print('Track {}: {}'.format(i, track.name))
for msg in track:
if msg.type == 'note_on'or msg.type == 'note_off':
#(msg.note)
if msg.... |
import logging
from sqlalchemy import update, select
from src.hana.db.model import cookies
from src.hana.db.mysql import init_connection
logging.basicConfig(
datefmt="%Y%m%d %H:%M:%S",
format="%(asctime)s %(levelname)-8s %(message)s",
level=logging.INFO,
)
def u_update(connection, table):
"""
T... |
from waitlist import entry
if __name__ == '__main__':
entry.main()
|
__author__ = "Narwhale"
# current_users = ['A','B','C','D','admin','F','G','H','J']
# new_users = ['A','R','Q','B','L']
#
# for i in new_users:
# if i in current_users:
# print('用户名已存在,请重新输入')
# else:
# print('此用户名可以使用')
#-----------------------------------
current_users = ['Ai','B','C','D',... |
import tensorflow as tf
import theano
import pandas as pd
import numpy as np
import matplotlib
import os
import math
import pydot
import graphviz
matplotlib.use('pdf')
import matplotlib.pyplot as plt
from keras.layers import Dense, Dropout, LSTM, Embedding, Activation, Lambda, Bidirectional
from keras.engine import Inp... |
#!/usr/bin/python3
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np
import time
def rot_mat(roll, pitch, yaw):
roll = -roll
pitch = -pitch
yaw = -yaw
D = np.array([[ np.cos(yaw), np.sin(yaw), 0],
[ -np.sin(yaw), np.cos(... |
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from django.core.exceptions import ObjectDoesNotExist
from django.http import HttpResponse, Http404, HttpResponseRedirect
from django.shortcuts import render, get_object_or_404
from django.db.models import Q
from .forms impor... |
import hashlib
def encrypt_string(hash_string):
sha_signature = \
hashlib.sha512(hash_string.encode()).hexdigest()
return sha_signature
hash_string = input("Enter a String: ")
sha_signature = encrypt_string(hash_string)
print("Hash Equivalent : ", end ="")
print(sha_signature) |
import json
import datetime
def get_list_json(results):
return json.dumps([result.to_dict() for result in results], cls=ComplexEncoder)
def get_json(result):
return json.dumps(result.to_dict(), cls=ComplexEncoder)
class ComplexEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, ... |
import cv2,time
video=cv2.VideoCapture(0)
a=1
while True:
a=a+1
check,frame=video.read()
print(frame)
gray=cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)
cv2.imshow("capture",gray)
key=cv2.waitKey(1)
if key == ord('q'):
break
print(a)
video.release()
cv2.destroyAllWindows()
|
import tkinter as tk
class gui:
# gui general parameters
TITLE = "Drone Simulation"
GUI_WIDTH = 1100
GUI_HEIGHT = 700
GUI_TOP_LEFT_CORNER_X = 50
GUI_TOP_LEFT_CORNER_Y = 50
BUTTON_WIDTH = 10
# frame size parameters
DISPLAY_CANVAS_WIDTH = 800
DISPLAY_CANVAS_HEIGHT = 500
# d... |
# -*- coding:utf-8 -*-
from selenium import webdriver
from time import sleep
import pandas as pd
from selenium.webdriver.android.webdriver import WebDriver
driver = webdriver.Chrome() # Chrome浏览器
driver.get("http://www.baidu.com")
driver.find_element_by_class_name("s_ipt").send_keys("selenium")
driver.find_element_b... |
# Name: Taidgh Murray
# Student ID: 15315901
# File: rectangle.py
############################################################################
import graphics
win = graphics.GraphWin("Rectangle", 200,200)
p1= win.getMouse()
p2= win.getMouse()
rectangle=graphics.Rectangle(p1, p2)
rectangle.setOutline(... |
# -*-coding=utf-8-*-
__author__ = 'Rocky'
'''
http://30daydo.com
Contact: weigesysu@qq.com
'''
import requests
session = requests.Session()
headers = {
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
'Accept-Encoding': 'gzip,deflate,br', 'Accept-Language': 'z... |
# -*- coding: utf-8 -*-
# @Author: zjx
# @Date : 2018/6/4
import web
import config
import sys
import json
from db.DataStore import sqlhelper
from db.SqlHelper import Proxy
# 路由
urls = (
'/', 'select',
'/delete', 'delete'
)
# 启动服务
def start_api_server():
sys.argv.append('0.0.0.0:%... |
import time
start_time = time.time()
number = 1000
summa = 0
for i in range(1, number):
if i % 3 == 0 or i % 5 == 0:
summa += i
i += 1
print(summa)
print("Elapsed Time: ",(time.time() - start_time)) |
# _*_ coding: utf-8 _*_
# 程序 9-2 (Python 3 version)
import requests
url = 'http://www.moe.gov.cn/'
html = requests.get(url).text.splitlines()
for i in range(0,15):
print(html[i])
|
# -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2014, 2015 CERN.
#
# Invenio is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the
# License, or (at your option) any... |
# 110. Balanced Binary Tree
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def isBalancedHelper(self, root):
if not root:
return 0, True
elif not root.left... |
import requests
import json
import datetime
from .translator import Translator
class User:
def __init__(self, playerName: str = None, playeruuid: str = None):
self.playerName = playerName
self.playeruuid = playeruuid
if self.playerName == None and self.playeruuid == None:
raise ... |
# Your code for the 1st query goes here
# Make sure to write the "put" function to create data structure from data base.
# Make sure to write the "get" function to query from data structure
# Refer app.py to see what "put" and 'get" should return
# your implementation of data structure goes here
def put():
data_st... |
# Generated by Django 2.1.7 on 2020-01-15 08:15
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('Rank', '0008_forgotpassword'),
]
operations = [
migrations.AddField(
model_name='contest',
name='status',
... |
# -*- coding: utf-8 -*-
"""
Created on Wed Jun 10 10:46:11 2020
@author: TOP Artes
"""
import pandas as pd
import numpy as np
from model.estado import Estado
from model.pre_processor import PreProcessor
from control.control_regressor import ControlRegressor
class ControlEstado:
def __in... |
from __future__ import unicode_literals
from ptpython.layout import CompletionVisualisation
def configure(repl):
repl.completion_visualisation = CompletionVisualisation.POP_UP
repl.show_line_numbers = True
repl.highlight_matching_parenthesis = True
repl.prompt_style = "ipython"
repl.confirm_exi... |
from DPjudge import Status, host
class Reopen(Status):
# ----------------------------------------------------------------------
"""
This class is invoked by the Judgekeeper to inform The Diplomatic Pouch
openings list that this DPjudge is up and available. The bin/reopen
tool is run manually when the judge is ba... |
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker, scoped_session
engine = create_engine('mysql+pymysql://root:123456@127.0.0.1:3306/blog?charset=utf8',pool_size=100)
Session = sessionmaker(bind=engine)
dbsession = scoped_session(Session) |
import tkinter as tk
from tkinter import *
from tkinter import ttk
import os
from colorama import Fore, Back, Style
from datetime import datetime, timedelta, time
import pika
import defs_common
import uuid
import json
#import cfg_outlets
import cls_OutletConfig
import time
import threading
class OutletWidget():
... |
n, char = input().split(" ")
for x in range(2):
for y in range(int(n)):
print(char * (y+1))
for x in range(int(n)):
print(char)
|
#Simple implementation of a doubly linked list
class Node:
def __init__(self, data=None):
self.data = data
self.next = None
self.prev = None
class DoublyLinkedList:
def __init__(self, node=None):
self.head = node
self.tail = node
self.length = 0 if node is None ... |
import sys
from EMR.ScheduledJobUpdaterOozie import ScheduledJobUpdaterOozie
from Lambda.LambdaUpdater import LambdaUpdater
from Utils.ChangedResources import ChangedResources
from Utils.EMRUtil import EMRUtil
# logging.basicConfig(level=logging.DEBUG)
# _LOG = logging.getLogger(__name__)
if __name__ == '__main__':
... |
# Exercício 9.35 - Livro
import os.path, sys, urllib.request
mascaraEstilo = "'margin: 5px 0px 5px 0px;'"
def geraEstilo(nivel):
return mascaraEstilo
def geraListagem(pagina, diretorio):
nraiz = os.path.abspath(diretorio).count(os.sep)
for raiz, diretorios, arquivos in os.walk(diretorio):
nivel =... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2018-05-31 22:15
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.Create... |
from glob import glob
import json
import os
import pickle
import string
import text2vec
import h5py
import nltk
import numpy as np
from tqdm import tqdm
import yaml
import matplotlib.pyplot as plt
import random
from math import sqrt
import nltk.stopwords as noisy_words
def smooth_text_plus(text, dominant_word):
"... |
import tornado.ioloop
import tornado.web
class MainHandler(tornado.web.RequestHandler):
def get(self):
self.write("Hello world")
class StoryHandler(tornado.web.RequestHandler):
def get(self, story_id):
self.write("You requested the story " + story_id)
class BuyHandler(tornado.web.RequestHa... |
# Author:ambiguoustexture
# Date: 2020-02-06
import re
pattern_file = re.compile(r'''
(?:File|ファイル) # Uncaptured, 'File' or 'ファイル'
:
(.+?) # Capture target,
# 0 or more arbitrary characters,
# non-greedy match
\|
... |
import random
import sys
import time
def mengetik(s):
for c in s + '\n' :
sys.stdout.write(c)
sys.stdout.flush()
time.sleep(random.random() * 0.2)
mengetik(' \033[31;1m• ✆••>€•LIT>MR.4Nz<[BPI] \n \033[33;1m• Mr.CL4Y0<[BPI] \n \033[37;1m• ᴹᴿ.$⁴ᴺᵀᴿ¹-SSC<[BPI]<[MCC]')
|
#coding:utf-8
import jieba
import sys
import re
from documentRead import DocumentRead
reload(sys)
sys.setdefaultencoding('utf8')
stopwords = open("H:\\stopwords.txt", 'rb').read().splitlines()
directory ='H:\\user_content'
documentReader=DocumentRead(directory)
documentReader.load_document()
documents=documentReader... |
# 印出 0.2 比例的兩個整數
print(0.2.as_integer_ratio())
# 判斷 0.235 是否為整數
print(0.235.is_integer())
# 判斷 2.000 是否為整數
print(2.000.is_integer())
# 檔名: typedemo01.py
# 作者: Kaiching Chang
# 時間: July, 2014
|
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time
class TwitterBot:
def __init__(self):
self.bot = webdriver.Firefox()
def startProcess(self):
bot = self.bot
bot.get("http://localhost:3001/admin")
time.sleep(2)
for x in bot.find... |
"""PDF credentials tests."""
import os
import shutil
import tempfile
from django.test import override_settings
from django.urls import reverse
from modoboa.admin import factories as admin_factories
from modoboa.core import models as core_models
from modoboa.lib.tests import ModoTestCase
class EventsTestCase(ModoT... |
#*_* coding=utf8 *_*
#!/usr/bin/env python
from tornado import web
from unreal import enum
from unreal import session
from unreal import config
from unreal import exception
from unreal.utils import mysql
CONF = config.CONF
def require_login(func):
def wrapper(handler, *args, **kwargs):
if not handler.is_... |
class ATM:
def __init__(self):
self.cnt = defaultdict(int)
self.money = [20, 50, 100, 200, 500]
def deposit(self, banknotesCount: List[int]) -> None:
for i in range(5):
self.cnt[self.money[i]] += banknotesCount[i]
def withdraw(self, amount: int) -> List[int]:
r... |
import keras
from keras.models import *
from keras.layers import *
from augment import Process
from keras.callbacks import *
from keras.optimizers import *
class NN(object):
def __init__(self, row, col):
self.row = row
self.col = col
def load_data(self):
data = Process(self.row, self.col)
trai... |
def add_node(v):
global node_count
if (v in nodes):
print("The node already present in the graph")
else:
node_count = node_count + 1
nodes.append(v)
for n in graph:
n.append(0)
temp = []
for i in range (node_count):
temp.appe... |
print('Hello! What is your name?')
name = input()
print('Well, ' + name + ', Think of random number from 1 to 100, and I will try to guess it!')
lowest = 1
highest = 100
mean = 0
guessestaken = 0
guessing = True
while guessing:
guessestaken = guessestaken + 1
mean = int((lowest+highest)/2)
print('Is it '... |
import sys; sys.path.insert(0, "/home/adriano/goamazondownloader")
"""S-Band radar data download"""
# Author: Adriano P. Almeida <adriano.almeida@inpe.br>
# License: MIT
from goamazondownloader import (Downloader, os, requests as req, BeautifulSoup,
ElementTree as ET)
from goamazondown... |
# coding=utf-8
from datetime import datetime
import json
import os
import sys
reload(sys)
sys.setdefaultencoding("utf-8")
__author__ = 'ITTC-Jayvee'
project_path = os.path.dirname(os.path.abspath(os.path.dirname(__file__)))
data_path = '%s/data' % (project_path)
# project import
sys.path.append(project_path)
import U... |
from . import MovieFilterPolicy
class KeywordPolicy(MovieFilterPolicy):
def __init__(self, word):
self.word = word
def _isInteresting(self, movie):
return self.word.lower() in movie.title.lower()
|
"""
The plot subpackage contains tools for plotting signals and annotations.
"""
from wfdb.plot.plot import plot_items, plot_wfdb, plot_all_records
|
# This file is part of beets.
# Copyright 2016, François-Xavier Thomas.
#
# 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... |
# Copyright (c) 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
# This file takes two arguments, the relative location of the shell script that
# does the checking, and the name of the sysroot.
# TODO(brettw) the bui... |
import numpy as np
import random
from machine_learning import dataset, plot
def dist2_min(d): return d.min()
def dist2_max(d): return d.max()
def dist2_avg(d): return d.sum() / (d.shape[0] * d.shape[1])
def agnes(datas, num_clusters, dist_functor=dist2_avg):
k = num_clusters
m = len(datas)
indexes_m = ... |
#Simple unit tests covering preprocess_data.py, encode_image.py, vgg16.py and imagenet_utils.py
import pytest
from preprocess_data import preprocessing
from vgg16 import VGG16
from encode_image import model_gen,encodings
from imagenet_utils import preprocess_input as i_preprocess_input
import os
import numpy as np
f... |
from prometheus_client.registry import REGISTRY
from prometheus_client import start_http_server
from helpers import global_config, logs
import yaml, logging, asyncio
from pprint import pprint
from .collector import OpenHABCollector
logger = logging.getLogger('collector')
logger.setLevel(global_config._LOGLEVEL)
logger... |
import unittest
from Drone import Drone
from Battery import Battery
class DroneTestMethods(unittest.TestCase):
def test_start_stop(self):
drone = Drone(5, (10,20), (10,20,0), 0.2, (0,0), Battery(300,100,3))
self.assertEqual(drone.start(), 0)
self.assertEqual(drone.start(), -1)
self... |
customers = {
0:{
"id":0,
"name":"John",
"city":"San Francisco",
"email":"johny.bravo@cn.com"
},
1:{
"id":1,
"name":"Mark",
"city":"Las Vegas",
"email":"mark.zuckerberg@fb.com"
},
2:{
"id":2,
"name":"Thomas",
"ci... |
# Imprimir os números pares entre 0 e um
# número fornecido sem utilizar o if
num = int(input('Número: '))
x = 0
while ((num%2) == 0 and num != 0):
print(num)
num = num - 2
|
from django.urls import include, path
from rest_framework.routers import DefaultRouter
from delivery.views import CourierViewSet, OrderViewSet
router = DefaultRouter()
router.register('couriers', CourierViewSet, basename='couriers')
router.register('orders', OrderViewSet, basename='orders')
urlpatterns = [
path(... |
def cicloHamiltoniano(grafo):
def genera(ciclo, nodiCiclo):
ultimoNodo = ciclo[-1] # Ultimo nodo aggiunto
if len(ciclo) == len(grafo): # nodo foglia
if 0 in grafo[ultimoNodo]: # Se si chiude il ciclo
return True
else: # nodo interno
for adiacente in gr... |
string = input()
digits = [] # или с листове или със стрингове
letters = []
other_characters = []
for ch in string:
if ch.isdigit():
digits.append(ch)
elif ch.isalpha():
letters.append(ch)
else:
other_characters.append(ch)
print("".join(digits))
print("".join(letters))
print("".jo... |
import requests
def main():
response = requests.get("http://www.google.com")
# response = requests.get("http://www.google.com/random-address/")
print("Status Code: ", response.status_code)
# print("Headers: ", response.headers)
# print("'Content-Type': ", response.headers['Content-Type'])
print... |
from bs4 import BeautifulSoup
import random
import requests
from fake_useragent import UserAgent
import datetime
import traceback
from scraper.functionScraper import *
from scraper.classListingObject import *
from scraper.classHelpClasses import *
from classes.classPostalData import *
from classes.SBBAPI import *
def ... |
#改良版バブルソート
#A = [9,2,7,5,4]
A = [1,2,3,8,7,9]
for i in range(0,len(A)-1):
print(A)
count = 0
for j in range(len(A)-1,i,-1):
if A[j] < A[j-1]:
A[j],A[j-1] = A[j-1],A[j]
count += 1
if count == 0:
break
print(A)
|
#! /usr/bin/python
# -*- coding: utf-8 -*-
from tkinter import *
app=Tk()
app.title("Aplicaion grafica en python")
etiqueta=Label(app, text="Hola Mundo!!!")
button = Button(app, text="OK!!!")
etiqueta.pack()
button.pack()
app.mainloop()
|
from open_pension_crawler.OpenPensionCrawlSpiderBase import OpenPensionCrawlSpiderBase
class ClalbitSpider(OpenPensionCrawlSpiderBase):
name = 'clalbit'
allowed_domains = ['clalbit.co.il']
start_urls = ['https://www.clalbit.co.il/pensiongemel/financialreports/funds/clalpension/Pages/default.aspx']
reg... |
import redis
client = redis.Redis()
client.sadd('myset', 'Andik')
client.sadd('myset', 'Sergio')
client.sadd('myset', 'irfan')
client.sadd('myset', 'Zoya')
client.sadd('employee', 'Andik')
client.sadd('employee', 'Sergio')
client.sadd('employee', 'Lilipaly')
client.sadd('employee', 'Beni')
client.sadd('employee', '... |
#!/usr/bin/env python
import rospy
import cv2
import math
from sensor_msgs.msg import Image
from struct import unpack
from cv_bridge import CvBridge, CvBridgeError
from cmvision.msg import Blobs, Blob
import copy
# Change this to your desired image topic
defaultImageTopic = "/camera/rgb/image_color"
colorImage = Imag... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'CertifyDlg.ui'
#
# Created by: PyQt5 UI code generator 5.9.2
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_CertifyDlg(object):
def setupUi(self, CertifyDlg):
Certif... |
from PIL import Image
import random
# NOTE: Feel free to add in any constant values you find useful to use
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
# NOTE: Feel free to add in any helper functions to organize your code but
# do NOT rename any existing functions (or else, autograder
# won't be able to fin... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from head import *
from threading import Timer
from db_base import MssqlConnection
def load_threshold(stopEvent, param, ):
"""
从数据库中载入环境限制范围
:param stopEven:
:param param:
:rtype:
"""
def load(room_id, threshold):
db_inst = MssqlConnect... |
# Copyright (c) 2021 Mahdi Biparva, mahdi.biparva@gmail.com
# miTorch: Medical Imaging with PyTorch
# Deep Learning Package for 3D medical imaging in PyTorch
# Implemented by Mahdi Biparva, April 2021
# Brain Imaging Lab, Sunnybrook Research Institute (SRI)
"""
****** NOTE: ALL THE CODE BELOW ARE TAKEN FROM TORCH... |
#!/usr/bin/env python
#Copyright (c) 2013, Eduard Broecker
#All rights reserved.
#
#Redistribution and use in source and binary forms, with or without modification, are permitted provided that
# the following conditions are met:
#
# Redistributions of source code must retain the aframeve copyright notice, this list ... |
# coding: utf-8
# # Simple Character-level Language Model using LSTM
# 2017-04-21 jkang
# Python3.5
# TensorFlow1.0.1
#
# - <p style="color:red">Different window sizes were applied</p> e.g. n_window = 3 (three-character window)
# - input: 'hello_world_good_morning_see_you_hello_grea'
# - outpu... |
import pika
import json
import sys
connection = pika.BlockingConnection(pika.URLParameters("amqp://hi:hi@pi-point:5672"))
channel = connection.channel()
channel.exchange_declare(exchange='logs', exchange_type='direct')
ins = json.load(sys.stdin)
channel.basic_publish(exchange = 'logs', routing_key='pi-point', body = ... |
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
* UMSE Antivirus Agent Example
* Author: David Alvarez Perez <dalvarezperez87[at]gmail[dot]com>
* Module: UMSE Intelligence Server
* Description: This module launch the "UMSE Intelligence Server".
*
* Copyright (c) 2019-2020. The UMSE Authors. All Rights Reserved.... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.