text
stringlengths
38
1.54M
import pygame from pygame.sprite import Sprite class Player(Sprite): """ Player class, where the player will control """ def __init__(self, hub, pos_x= 50, pos_y=50): """ Initialize default values """ super().__init__() self.hub = hub self.screen = hub.main_screen self.s...
#!/usr/bin/python # -*- coding: utf-8 -*- import sys import math import time def compute(word): result = [word[0]] for i in range(1, len(word)): alpha = word[i] if alpha >= result[0]: result.insert(0, alpha) else: result.append(alpha) return ''.join(result) ...
s = input() t = input() set_s = set(s) ans = 0 for i in t: if i in set_s: ans += 1 print(ans + 1)
import os import sys os.environ['OPENBLAS_NUM_THREADS'] = '1' import numpy as np import pickle import dill directory = sys.argv[1] #should be the directory of mim level single_frag = sys.argv[2] folder = sys.argv[3] tmpdir = sys.argv[4] frag_name = "fragment" + single_frag + ".dill" print(folder) print(directory) p...
#!/usr/bin/env python # -*- coding: utf-8 -*- import glob from lxml import objectify def formatdate(date): date = date.split('T') date = date[0].split('-') date = date[2]+date[1]+date[0] return date sped = dict() part_list = [] cte_list = [] arq = open('1.txt', 'r') texto = arq.readlines() for line...
"""Modules for making crystallographic plane surfaces.""" from jarvis.core.atoms import Atoms from jarvis.core.utils import ext_gcd import numpy as np from jarvis.analysis.structure.spacegroup import Spacegroup3D from numpy.linalg import norm from numpy import gcd from collections import OrderedDict def wulff_normals...
import network_functions as nf import matplotlib.pyplot as plt import generic_plot_functions as pf if __name__ == '__main__': cities = nf.get_list_cities_names() area_population_file = 'results/all/json/area_population.json' ''' Load info about areas and populations for each city and plot them ''' a...
# plot how the singular strategy and derivative of the fitness gradient varies with a parameter import matplotlib.pyplot as plt import pandas as pd # parameters # --- ''' par_name = 'f' idx_include = list(range(37)) par_name = 'r' idx_include = list(range(28)) par_name = 'c' idx_include = list(range(28)) ''' par...
import pygame def handle_keys(key): if key.type == pygame.KEYDOWN: button = key.key # movement keys if button == pygame.K_UP: return {"move": (0, -1)} if button == pygame.K_DOWN: return {"move": (0, 1)} if button == pygame.K_LEFT: return ...
class Solution: def canConstruct(self, ransomNote: str, magazine: str) -> bool: d = {} for ch in magazine: # Making d for value count if ch not in d: d[ch] = 1 else: d[ch] += 1 for ch in ransomNote: if ch...
import discord from discord.ext import commands import json from mojang import MojangAPI async def get_data(ctx, member, users): if str(member.id) in users: bal = users[str(member.id)]["purse"] hasvip = "User does not have vip" vip = discord.utils.find( lambda r: r.name == '-V....
from django.db import models class Subscriber(models.Model): name = models.CharField(max_length=128) phone = models.CharField(max_length=128) descriptions = models.TextField() def __str__(self): return "Пользователь %s %s" % (self.name, self.phone) class Meta: verbose_name = 'MyS...
# Generated by Django 2.1.7 on 2019-08-25 03:02 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('stockapp', '0003_auto_20190825_0830'), ] operations = [ migrations.AlterField( model_name='country', name='name', ...
import pyaudio import numpy as np import random p = pyaudio.PyAudio() volume = 0.5 # range [0.0, 1.0] fs = 44100 # sampling rate, Hz, must be integer duration = 1.0 # in seconds, may be float f = 440.0 # sine frequency, Hz, may be float f2 = 445.0 # sine frequency, Hz, may be float stream =...
""" Getting existing single job webhook configuration info in Mitto instance. """ import os import sys from dotenv import load_dotenv from create_job_webhook import main as created_job_webhook from mitto_sdk import Mitto load_dotenv() BASE_URL = os.getenv("MITTO_BASE_URL") API_KEY = os.getenv("MITTO_API_KEY") WEBHOO...
import os from flask import Flask from flask_restful import Api from flask_jwt import JWT from security import authenticate, identity from resources.user import UserRegister from resources.item import Item, ItemList from resources.store import Store, StoreList from db import db app = Flask(__name__) #app.config['SQ...
from django.shortcuts import render, HttpResponse from django.conf import settings from rest_framework.decorators import api_view from rest_framework.response import Response import random from .models import Planet from .serializers import PlanetSerializer from api.serializers import GenericSerializer from api.vie...
import os import psycopg2 from dotenv import load_dotenv load_dotenv() def create_connection(): return psycopg2.connect(os.environ.get("DATABASE_URI"))
# Copyright 2015 Metaswitch Networks # # 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 w...
from bs4 import BeautifulSoup from requests import request import os class Parther_clss(object): def __init__(self,path_file_html,filter_l): self.path_file_html=path_file_html self.filter_=filter_l def soup_parth(self): anime_input=[] html = open(self.path_file_htm...
#The basic outline is 1. First of all, we have to get the X and y value from the table #Remember how to import the table values fromt the data frame, using double square brackets #then we need to add the dense layer and then compile #always remember in the layer we need to input the number of nodes, activation function...
# -*- coding: utf-8 -*- """ Created on Mon Oct 19 16:40:18 2020 @author: pedro """ globals().clear() from pathlib import Path import getpass if getpass.getuser() == "pedro": print('Logado de casa') caminho = Path(r'D:\Códigos, Dados, Documentação e Cheat Sheets') elif getpass.getuser() == "pedro-salj": pr...
test = { 'name': 'q3', 'points': 1, 'suites': [ { 'cases': [ { 'code': r""" >>> y = data['tip']; >>> x = data['total_bill']; >>> np.isclose(minimize_average_loss(squared_loss, model, x, y), 0.14373189123158361) True """, 'hidd...
import pygame as pg import settings import LoadImages from Bomb import Bomb from PowerUp import PowerUp import importlib class Player(pg.sprite.Sprite): def __init__(self, game, xSpawn, ySpawn, id): self.groups = game.allSprites, game.players, game.destructibleAndDontBlockExplosion pg.sprite.Sprite.__init__(self,...
# По введенным пользователем координатам двух точек вывести уравнение прямой вида y = kx + b, проходящей через эти точки. x_1 = int(input('Введите X1')) y_1 = int(input('Введите Y1')) x_2 = int(input('Введите X2')) y_2 = int(input('Введите Y2')) k = (y_1 - y_2) / (x_1 - x_2) b = y_2 - (k * x_2) print (f'y = {k...
n=str(input()) length = len(n) ans=0 for i in range(length//2): if n[i]==n[-i-1]: ans+=0 else: ans+=1 print(ans)
from __future__ import print_function from oauth2client import tools import urllib.parse as parser try: import argparse flags = tools.argparser.parse_args([]) except ImportError: flags = None # very much copied from the Google Calendar API Python Quickstart tutorial # If modifying these scopes, delete y...
# 导入相关的库 from absl import app, flags, logging from absl.flags import FLAGS import tensorflow as tf import numpy as np import cv2 from tensorflow.keras.callbacks import ( ReduceLROnPlateau, EarlyStopping, ModelCheckpoint, TensorBoard ) # 导入自定义的库 from yolov3_tf2.models import ( YoloV3, YoloV3Tiny, Yo...
# coding: utf-8 from abc import ABCMeta, abstractmethod import os from stinfo import * ################################################## # 解析クラスの基底クラス ################################################## class AbsAnalyzer(metaclass=ABCMeta): """データロードクラスの基底クラス Attributes: _base_dir (string) ...
#!/usr/bin/env python from frontend import app, init_application from config import DebugConfiguration as config if __name__ == "__main__": init_application(app, config) app.debug = config.DEBUG app.run(host='0.0.0.0', port=config.APP_PORT, threaded=True)
# -*- coding: utf-8 -*- # Define here the models for your scraped items # # See documentation in: # http://doc.scrapy.org/en/latest/topics/items.html import scrapy class DoubanItem(scrapy.Item): # define the fields for your item here like: # name = scrapy.Field() _id = scrapy.Field() movie_name = sc...
import numpy as np from sklearn import cross_validation from sklearn.decomposition import PCA from sklearn.grid_search import GridSearchCV from sklearn.metrics import confusion_matrix, f1_score from sklearn.neighbors import KNeighborsClassifier from sklearn.svm import SVC import preprocess import preprocess_original ...
#import threading #from kivy.clock import mainthread from connection import Connection #from datetime import date #import time #from kivy.utils import strtotuple from kivymd.uix.boxlayout import MDBoxLayout from kivymd.uix.dialog import MDDialog from kivymd.uix.menu import MDDropdownMenu from kivymd.uix.picker import ...
import random data = [] count = 0 with open('reviews.txt', 'r') as f: #with可以自動關閉讀取檔案 for line in f: data.append(line) count += 1 if count % 100000 == 0: # 求餘數時使用% print(len(data)) print('檔案讀取完ㄌ,總共有', len(data), '筆資料') sum_len = 0 for d in data: sum_len += len(d) #print(sum_len) print('留言的平均長度為', sum_...
#!/usr/bin/env python # encoding: utf-8 # @author: liusir # @file: run_all_cases.py # @time: 2020/10/11 5:14 下午 import unittest import os from itsDemoTest.comm import HTMLTestReportCN from itsDemoTest.comm.email_utils import EmailUtils import time from itsDemoTest.comm.ReadConfig import config from itsDemoTest.comm.l...
import torch from segan.discriminator import Discriminator from segan.generator import Generator class SEGANModule(torch.nn.Module): """ Container for both generator and discriminator """ def __init__( self, n_layers: int = 10, init_channels: int = 2, kernel_size: int = 31, ...
import re import time import os import logging from io import BytesIO from typing import Optional, List, Set from dateutil.parser import parse as parse_date from datetime import date, timedelta from pdfminer.high_level import extract_pages from pdfminer.layout import LTTextContainer from selenium.common.exceptions im...
import csv from sqlalchemy import create_engine from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker from model import (Base, Surname, FemaleFirstName, MaleFirstName) engine = create_engine('sqlite:///census_data.db') ...
""" The team.py file is where you should write all your code! Write the __init__ and the step functions. Further explanations about these functions are detailed in the wiki. List your Andrew ID's up here! gkasha mdunaevs aecos """ import random from awap2019 import Tile, Direction, State class Team(object): def...
from setuptools import setup, find_packages setup( name='torrentleech_monitor', version='1.0', packages=find_packages(), long_description=open('README.md').read(), install_requires=['logbook', 'requests', 'beautifulsoup4', 'ujson', 'tvdb_api', 'guessit'], entry_points={ 'console_scripts'...
#!/usr/bin/env python3.7 #Scapy_Graph_Of_IPs.py - Version 1.0 - By Joe McManus - Modified By MMC - 31st March 2019 #import section - scapy, prettytable, collections and plotly. #step 1: Imports. from scapy.all import * from prettytable import PrettyTable from collections import Counter import plotly #Step 2: Read and ...
# Time Complexity : O(mn) # Space Complexity :O(mn) # Did this code successfully run on Leetcode : Yes # Any problem you faced while coding this : No # Your code here along with comments explaining your approach class Solution: def minDistance(self, word1: str, word2: str) -> int: dp = [[0 for _ in range(...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # @Date : Nov-20-20 16:27 # @Author : Kelly Hwong (dianhuangkan@gmail.com) # @Link : http://example.org import os from datetime import datetime import numpy as np import tensorflow as tf from tensorflow.keras.models import Sequential from tensorflow.keras.layers im...
import os import cx_Oracle # 导入数据库 import pandas as pd #导入操作数据集工具 #from sqlalchemy import create_engine #导入 sqlalchemy 库,然后建立数据库连接 import time #导入时间模块 import numpy as np #导入numpy数值计算扩展 class OpOracle(object): # 新式类 def __init__(self, host='172.30.10.180', port='1521', sid='bpmtest', user='ecology', password='bpm...
# Создать (программно) текстовый файл, записать в него программно набор чисел, разделенных пробелами. # Программа должна подсчитывать сумму чисел в файле и выводить ее на экран. user_input = input( "Please input numbers separated by spaces> ") user_words = user_input.split(" ") numbers = [] for word in user_word...
''' @Author: your name @Date: 2020-03-31 21:57:19 @LastEditTime: 2020-03-31 22:29:04 @LastEditors: Please set LastEditors @Description: In User Settings Edit @FilePath: /Algrithm/LeetCode/26.删除排序数组中的重复项.py ''' # # @lc app=leetcode.cn id=26 lang=python3 # # [26] 删除排序数组中的重复项 # # @lc code=start class Solution: def re...
#!/usr/bin/env python """Cron flows.""" # pylint: disable=unused-import # These imports populate the Flow registry from grr.lib.flows.cron import compactors from grr.lib.flows.cron import filestore_stats from grr.lib.flows.cron import system
# coding:utf-8 import argparse import re import time from math import * import numpy as np from my_functions_2 import * startTime = time.time() parser = argparse.ArgumentParser( description='analyse BG and output BG stats parameter(number of sample ,sum, , mean, std, kurtosis, max, min, middle, sum(2, 3, 4)...
import os import re from cs50 import SQL from flask import Flask, flash, redirect, render_template, request, session from flask_session import Session from tempfile import mkdtemp from werkzeug.exceptions import default_exceptions from werkzeug.security import check_password_hash, generate_password_hash from helpers ...
import gym import torch.nn as nn from .resnet18_nav_base import Resnet18NavBaseConfig from .pointnav_base import PointNavBaseConfig, PointNavTask from projects.pointnav_baselines.models.point_nav_models import ( ResnetTensorPointNavActorCritic, ) class Resnet18PointNavExperimentConfig(PointNavBaseConfig, Resnet1...
# https://github.com/mhagiwara/realworldnlp/blob/master/examples/generation/lm.py import torch from typing import Tuple, List from allennlp.models import Model from allennlp.modules.seq2seq_encoders import Seq2SeqEncoder from allennlp.modules import TextFieldEmbedder from allennlp.data.vocabulary import Vocabulary, DE...
#!/user/bin/env python3 # -*- coding: utf-8 -*- import requests from dao.es_dao import es_connect import re import json def transformer_data(data_source): # 通用清洗方案 transfor_data = json.loads(re.findall(' = (.*)}catch', data_source)[0]) return transfor_data def run_spider(): url = 'http://3g.dxy.cn/newh5...
import numpy as np from sklearn.svm import LinearSVC ### Functions for you to fill in ### def one_vs_rest_svm(train_x, train_y, test_x): """ Trains a linear SVM for binary classifciation Args: train_x - (n, d) NumPy array (n datapoints each with d features) train_y - (n, ) NumPy array co...
from django.test import TestCase from .forms import AddUrlForm from django_webtest import WebTest # Create your tests here. class InputUrlTests(TestCase): def test_homepage(self): response = self.client.get('/') self.assertEqual(response.status_code, 200) def test_add_url_form_label(self): form = AddUrlFo...
""" This file is part of Linspector (https://linspector.org/) Copyright (c) 2013-2023 Johannes Findeisen <you@hanez.org>. All Rights Reserved. See LICENSE. """ import configparser import importlib import time class Monitor: def __init__(self, configuration, environment, identifier, log, monitor_configuration, ...
class Solution(object): def find132pattern(self, nums): """ :type nums: List[int] :rtype: bool """ if len(nums) < 3: return False minRecord = self.buildMinReocrd(nums) stack = [] for i in range(len(nums) - 1, -1, -1): i...
#PyBank Challenge - calculate #The total number of months included in the dataset #The net total amount of "Profit/Losses" over the entire period #The average of the changes in "Profit/Losses" over the entire period #The greatest increase in profits (date and amount) over the entire peri...
import math import statistics import numpy as np import scipy.stats import pandas as pd x = [8.0, 1, 2.5, 4, 28.0] x_with_nan = [8.0, 1, 2.5, math.nan, 4, 28.0] # print(x) # print(x_with_nan) y = np.array(x) # massive y_with_nan = np.array(x_with_nan) # massive z = pd.Series(x) # 1D object z_with_nan...
# -*- coding: utf-8 -*- import subprocess import requests # Get project ID from gcloud config project_id = subprocess.check_output( "gcloud config list project --format 'value(core.project)'", shell=True ).rstrip() # Add pull queues to App Engine url = "https://{}.appspot.com/pw/add-pull-queues".format(proj...
# -*- coding: utf-8 -*- import scrapy class VolSpider(scrapy.Spider): name = 'volleyball' start_urls = [ 'http://www.funtable.ru/table/sport/vse-chempiony-sssr-sng-i-rossii-po-voleybolu-muzhchiny.html' ] def parse(self, response): SET_SELECTOR='//*[@class="catalog-item-desc-float...
# Generated by Django 3.1.2 on 2021-05-21 21:48 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('api', '0006_saildetail_ticket'), ] operations = [ migrations.AddField( model_name='ticket', name='token', ...
from tweepy.streaming import StreamListener from tweepy import OAuthHandler from tweepy import Stream import sys import json from datetime import datetime from elasticsearch import Elasticsearch from geopy.geocoders import Nominatim #from requests_aws4auth import AWS4Auth #Variables that contains the user credenti...
#EVEN THIS CHANGE from Class import myPoint import math import matplotlib.pyplot as plt def validNumber(x): ''' Forces the user to insert a number ''' while not x.isnumeric() and not x[1:].isnumeric(): x = input("please insert a number: ") return int(x) def validIndex(l,i): ''' For...
# Modified from: https://github.com/sachin-chhabra/Pytorch-cGAN-conditional-GAN from torch import optim import os import torchvision.utils as vutils from torch.utils.data import DataLoader import numpy as np from torchvision import datasets from torchvision import transforms from usps_data import gan_trans, CustomTens...
"""Cloud object compatibles standard library 'io' equivalent functions.""" from contextlib import contextmanager from io import open as io_open, TextIOWrapper from airfs._core.storage_manager import get_instance from airfs._core.functions_core import format_and_is_storage @contextmanager def cos_open( file, ...
# List/String/Array is somehow equal in Python class Solution(object): def plusOneLong(self, digits): """ :type digits: List[int] :rtype: List[int] """ carry = 0 length = len(digits) digits[length-1] += 1 for i in range(length): digits[len...
""" data_gen.py File containing the functionality to generate test files and folders for testing bellerophon. """ import os import random import time def dir_gen(directory_name): """ Function to create files. :param string directory_name: Fully qualified dierctory name which is to be created """...
import sys, os from sphinx.highlighting import lexers from pygments.lexers.web import PhpLexer sys.path.append(os.path.abspath('_exts')) extensions = [] master_doc = 'index' highlight_language = 'php' project = u'PrestoPHP' copyright = u'2010-2021 Fabien Potencier, Gunnar Beushausen' html_theme = "bizstyle" version...
import wiringpi /* MPU6050 Interfacing with Raspberry Pi http://www.electronicwings.com */ #include <wiringPiI2C.h> #include <stdlib.h> #include <stdio.h> #include <wiringPi.h> #define Device_Address 0x68 /*Device Address/Identifier for MPU6050*/ #define PWR_MGMT_1 0x6B #define SMPLRT_DIV 0x19 #define CONFI...
# pytorch # -*- coding: utf-8 -*- # @Author  : Tangzhao # @Blog:https://blog.csdn.net/tangzhaotz # 加载数据 import torch import torchvision import torchvision.transforms as transforms import torch.utils.data transform = transforms.Compose([ transforms.ToTensor(), transforms.Normalize((0.5,0.5,0.5),(0...
class Solution: def divisibilityArray(self, word: str, m: int) -> List[int]: res, v = [], 0 for w in word: v = (v*10 + int(w)) % m res.append(int(v==0)) return res
import functools import pickle import scipy.sparse as sp from flask import ( Blueprint, flash, g, redirect, render_template, request, session, url_for ) bp = Blueprint('user', __name__, url_prefix='/user') sparse_user_item = sp.load_npz('confi.npz') model = pickle.load(open('model.pkl','rb')) problem_name = pick...
#Coded by R Praveen Ram string = input() result = string[0] for index in range(1, len(string)): if(string[index] == result[-1]): continue result += string[index] print(result)
import random import math def brute(): z = 0 maxPro = float("-inf") for num in range(l, r + 1): pro = (x & num) * (y & num) if pro > maxPro: maxPro = pro z = num return z def toBinary(num): binary = "" while num > 0: binary += str(num%2) nu...
import requests experience = 2 response = requests.get("http://127.0.0.1:8000/predict?experience={}".format(experience)) output = response.json() print(output)
import sys from collections import defaultdict import json class relation_linker(object): """docstring for relation_linker""" def __init__(self, fp_path,train_path,lf_path): self.relation_pool=defaultdict(int) self.file_path=fp_path self.train_path=train_path self.lf_path=lf_path def generatePool(self,min_su...
#!/usr/bin/env python #coding=utf8 import httplib import md5 import urllib import random import json import time import re debug=0 if debug == 1: fh = open("a.log","w") from pandocfilters import toJSONFilter, Emph, Para, Str, stringify, Header , Strong, Plain, Link def rep(v): tt={} tt['t']="Str" t...
import time import xml.etree.ElementTree as ET from StringIO import StringIO from pyspark import SparkConf, SparkContext, HiveContext from multiprocessing.pool import ThreadPool from pyspark.sql.types import StructType, StructField, StringType __author__ = 'Pirghie Dimitrie' conf = SparkConf().setAppName("Preprocess...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models import bcrypt, re # bcrypt + regex from django.contrib import messages # flash messages from datetime import datetime, date, timedelta # datetime import pytz # for time comparison from ..login_registration.models import User # ...
from collections import * from itertools import * from random import * from time import * from functools import * ''' Considering quadratics of the form: n2+an+b, where |a|<1000 and |b|≤1000 where |n| is the modulus/absolute value of n e.g. |11|=11 and |−4|=4 Find the product of the coefficients, a and b, for the qu...
# Generated by Django 3.0.6 on 2020-07-17 09:55 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='ClasseForfait', fields=[ ('...
import wiringpi as wpi from settings import LCDAddr fd_1602 = wpi.wiringPiI2CSetup(LCDAddr) # I2C初始化 def send_bit(comm, rs=1): # 先送最高4位 buf = comm & 0xF0 buf = buf | 0x04 | rs # rs=1是写数据, rs=0是写指令 wpi.wiringPiI2CWrite(fd_1602, buf) wpi.delay(2) buf &= 0xFB # EN 1 -> 0 ...
from enthought.mayavi.core.registry import registry from enthought.mayavi.core.metadata import SourceMetadata from enthought.mayavi.core.pipeline_info import PipelineInfo def mat_reader(fname, engine): """Reader for .zzz files. Parameters: ----------- fname -- Filename to be read. engine -- Th...
"""Module implements various notification methods.""" import os import smtplib import logging from socket import gaierror from email.message import EmailMessage from requests import post from .helpers import env_exists class Notifications: """Handles notifications requests. Attributes: message: st...
def cal(A, B): x = np.linalg.solve(A, B) return x import numpy as np import math def ct(n): PI = math.pi de = PI / 100 return de * n x11 = [ct(0), ct(7), ct(20), ct(29), ct(32), ct(50), ct(64), ct(70), ct(82), ct(90), ct(100)] x21 = [ct(0), ct(4), ct(10), ct(12), ct(14), ct(20), ct(23), ct(27...
# Generated by Django 2.2 on 2020-05-18 14:35 from django.db import migrations, models import django.utils.timezone class Migration(migrations.Migration): dependencies = [ ('app1', '0004_message_seen'), ] operations = [ migrations.AddField( model_name='message', ...
import os import pandas as pd column_name_mapping = { "Start_iViewX_micros": "start", "End_iViewX_micros": "end", "Location_X": "x", "Location_Y": "y", "Duration_micros": "duration", } def rewrite_df(df): try: df = df.rename(columns=column_name_mapping) df["duration"] = df["du...
# -*- coding: cp949 -*- # Galaxy Explorer # By Park Changhwi #레벨이 올라갈수록 행성과 셔틀이 작아진다 #회전할수록 연료가 닳는다 #빨간 행성을 먹으면 점수업 #검은 행성을 먹으면 연료 증가 #밖으로 나가면 다음 레벨 #연료가 다하면 게임 끝 #파란 행성에서는 연료 닳지 않음 import pygame, random, time, math, sys, copy from pygame.locals import * try: import android except ImportError: android = None...
import logging.config import os import sys import traceback import log_setting logging.config.dictConfig(log_setting.LOGGING) logger = logging.getLogger('alarm_combine') def detail(msg): msgstr = "File Name:" + os.path.basename(__file__) + "\t output:" + msg return msgstr def func(): return 3 / 0 tr...
from numpy import array from helpers import draw_line from lab0.polygon import Polygon def draw_point(point: array): draw_line(point + (-3, -3), point + (3, 3)) draw_line(point + (-3, 3), point + (3, -3)) def get_object(origin): p0 = array((origin[0], origin[1])) p1 = p0 + (70, 0) p2 = p1 + (-1...
import hashlib from Crypto.Hash import SHA def findCollision(): i = 0 hashes = set() notdone = True prevsize = 0 size = 0 while notdone: if i % 50000 == 0: print(i) ''' if i == 13644212: print(str(i)) result = SHA.new(str(i)) print(str(int(result.hexdigest(), 16) & 0x3ffffffffffff)) if ...
import re import glob, os cwd = os.getcwd() # os.chdir(cwd) # for file in glob.glob("*.srt"): # print(file) def main(): # read file line by line for file in glob.glob("*.srt"): file = open(file, "r") lines = print(file.read()) file.close() text = '' for ...
#!/usr/bin/env.python # -*- coding:utf-8 -*- ''' 简单模拟加动态规划严重超时 考虑到都是正整数,到0点的距离时递增的,可以用二分法 S[i]表示0点到i点的累积和。从而S[j]-S[i]+l[i]即为i-j的和 ''' N, M = map(int, input().split()) l = list(map(int, input().split())) s = [0] * N s[0] = l[0] e = 1 while e < N: s[e] = s[e - 1] + l[e] e += 1 # print(s) def cal(i, j): glo...
import random import numpy as np from functions import * from warehouse import warehouse import time #small_order_list = [[104,104],[166,266,625],[920,1182,999],[1182,1319]] small_order_list = [[104,1182,357,206,453,1123]] #small_order_list = [[104],[104]] #small_order_list = [[104],[106],[108],[110],[112],[210],[110...
class Racer: def __init__(self, name, track_number): self.name = name self.track_number = track_number self.lap_times = []
# -*- coding: utf-8 -*- """ pdverify.py: verify TDDA constraints for feather dataset """ from __future__ import division from __future__ import print_function import os import sys import pandas as pd import numpy as np USAGE = """Usage: pdverify df.feather [constraints.tdda] where df.feather is a feather fil...
from PyQt5 import QtCore, QtGui, QtWidgets import sys import sqlite3 i=-1 conn = sqlite3.connect('FeedB.db') cur = conn.cursor() cur.execute("""CREATE TABLE IF NOT EXISTS FeedTable ( username varchar(15), Faculty varchar(15), Feed TEXT, Review varchar(15), PRIMARY KEY(username, Faculty) )""")...
import logging.config import os from mycrypt import encrypt, decrypt from mydatabase import conn, query_conn from coinpayments import CoinPaymentsAPI import time import datetime from blockchain import blockexplorer from icq.bot import ICQBot from icq.filter import MessageFilter from icq.handler import ( MessageHand...
import numpy as np #import numpy import matplotlib.pyplot as plt #import Matplotlib import networkx as nx #import networkx my_obj = open("test1.py","r") #created an object to open a file cif = 0 #count for if cfor = 0 #count for for k = 0 #initializing ...
# Copyright 2019 Arie Bregman # # 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 agree...