text
stringlengths
8
6.05M
import nltk # from nltk import word_tokenize, pos_tag,sent_tokenize, RegexpTokenizer from nltk.tokenize import RegexpTokenizer from nltk.corpus import stopwords import json, gensim print ("started") # type(data)=dict with open('hindustan_times_news.csv') as w: ht = w.readlines() with open('times_of_india_news.csv...
#Project Euler Problem 32 # find the sum of all products where the multiplicand/multiplier/product are 1-9 pandigital # e.g. 39*186=7254 numbers=[] pandigitals=[] #Generate a list of pandigital numbers for i in range(1,2000): numbers.append(i) for i in numbers: temp=str(i) #print(temp) count=0 for j...
import json def get_relation_dict(relation_filepath): relation2id = {} id2relation = {} with open(relation_filepath, mode='r', encoding='utf-8') as fr: for line in fr.readlines(): split_list = line.split('\t') relation2id[split_list[0]] = int(split_list[1]) id2re...
import nltk from nltk.book import * from nltk.corpus import brown print(brown.categories()) cfd = nltk.ConditionalFreqDist((genre,word) for genre in brown.categories() for word in brown.words(categories=genre)) genres =['news','religion','hobbies','science_fiction','romance','humor'] modals = ['can','co...
""" Do a quick analysis of the abortive and full length transcript amounts. """ class Quant(object): """ Hold the quantification objects """ def __init__(self, name, FL, AB, PY): self.name = name self.FL = float(FL) self.AB = float(AB) self.PY = float(PY) def __rep...
import telebot from delidog import settings from delidog.models import Chat, Message bot = telebot.TeleBot(settings.BOT_TOKEN) @bot.message_handler(commands=['start', ]) def _send_token(message): chat = Chat.get_chat(message.chat.id) send_message(chat, chat.token) @bot.message_handler(commands=['set_token...
from onegov.core.security import Private from onegov.org.views.export import view_export_collection, view_export from onegov.town6 import TownApp from onegov.org.models import Export, ExportCollection from onegov.town6.layout import ExportCollectionLayout @TownApp.html( model=ExportCollection, permission=Priv...
# coding = UTF-8 import logging import re logging.basicConfig(level=logging.DEBUG) def get_word_count(file_name): with open(file_name, 'r', encoding='utf-8') as f: word_cnt = 0 i = 0 for line in f: i += 1 line = line[:-1].strip(" ") line = r...
import random import torch class NaturalSelection: def __init__(self): self.mutate_chance = 10 self.mutate_impact = 0.01 self.current_population = {} self.new_population = {} self.elite = {} self.high_score = 0 self.new_population_weights = {} self....
# coding: utf-8 """ Lilt REST API The Lilt REST API enables programmatic access to the full-range of Lilt backend services including: * Training of and translating with interactive, adaptive machine translation * Large-scale translation memory * The Lexicon (a large-scale termbase) * Programmatic cont...
from __future__ import print_function import numpy as np import keras from keras import backend as K from keras.models import Sequential from keras.layers import Activation from keras.layers.core import Dense, Flatten from keras.optimizers import Adam from keras.metrics import categorical_crossentropy from keras.prepr...
#!/usr/bin/env python3 """ Test for ip-cidr-list identifier """ import datetime import unittest from base_test import PschedTestBase from pscheduler.limitprocessor.identifier.ipcidrlist import * DATA = { "cidrs": [ "10.0.0.0/8", "192.168.1.0/24" ] } HINTS_HIT = { "requester": "10....
from myhdl import * import random #from myhdl._fixbv import FixedPointFormat as fpf Bits = 31 def disp_fix(x_i): iW = x_i._W print float(x_i), int(x_i), repr(x_i), hex(x_i), bin(x_i, iW[0]) x = (fixbv(3.1415926535897932, min = -2**10, max=2**10, res=1e-6)) #disp_fix(x) y = (fixbv(510.5, min = -2**10, max=2...
# import the Flask class from the flask module from flask import Flask, render_template, redirect, url_for, request # import datetime from the dateime from datetime import datetime # improt flask_sqlalchemy for databases from flask_sqlalchemy import SQLAlchemy # import forms from the wtforms from wtforms import Form, B...
from keras_retinanet import models from keras_retinanet.utils.image import read_image_bgr, preprocess_image, resize_image import cv2 import numpy as np def crop_edges(img): """ Crops black edges from a full Celigo image Must be read in grayscale (single-channel) """ imarray = np.array(img) slid...
#Grade Equivalent def computegrade(score): if (s >= 0.9): a = "A" elif (s >= 0.8): a = "B" elif (s >= 0.7): a = "C" elif (s >= 0.6): a = ("D") elif (s < 0.6): a = ("F") return a #Asks for user input score = input("Enter score: ") try: s = float(sco...
salario = float(input('Qual o teu salario: ')) print('Seu salrio é de', salario * 1.1 if salario >= 1250 else salario * 1.15)
from pathlib import Path from subprocess import run import os from tqdm import tqdm import shutil from psycho.psycho import Psycho from multiprocessing import Pool, cpu_count PHI = int(os.environ["PHI"]) if os.environ["PHI"] != "None" else None NUMJOBS = int(os.environ["NUMJOBS"]) def process_entry(entry): # ass...
/Users/Di/anaconda/lib/python2.7/sre_compile.py
from django import forms class ReviewsForm(forms.Form): review = forms.CharField(required=True) name = forms.CharField(required=True, max_length=14) email = forms.EmailField(required=True)
import unittest import numpy as np from multiatlas.rohlfing import multi_label_segmentation class TestRohlfing(unittest.TestCase): def test_multi_label_segmentation(self): """Tests the implementation of rohlfing (2004) """ train_labels = [[0,1,0,1,1,0,1,2,3,3], [1,1,0,1,...
from django.db import models from django.contrib.auth.models import User from datetime import datetime class Thread(models.Model): title = models.CharField("タイトル", max_length=200, blank=False) message = models.TextField("メッセージ", blank=False) pub_date = models.DateTimeField("作成日時", auto_now_add=True, edita...
#!/usr/bin/env python3 # # Run a test. Just the test spec is provided on stdin. # import icmperror import pscheduler import re input = pscheduler.json_load(exit_on_error=True); log = pscheduler.Log(prefix='tracepath', quiet=True) # TODO: Validate the input # TODO: Verify can-run participant = input['participant'...
# Variaveis geral # cod_emp nós vamos pegar direto cod_emp = 0 N_func = 0 '''========================================================''' # Variaveis de cada categoria N_func_maior_grande = 0 N_func_maior_media = 0 N_func_maior_pequena = 0 N_func_maior_micro = 0 cod_emp_maior_grande = 0 cod_emp_maior_media = 0 cod_emp...
print("Creating list of 3 list's") l = [[]] * 3 print(l) l[0] = 1 print(l) l[1] = [1, 2, 3, 4] print(l) l[2] = 3 print(l) print("Creating list with 3 places") l2 = [int]*3 print(l2) l2[0] = 1 print(l2) l2[1] = 1 print(l2) l2[2] = 1 print(l2)
# http://pise.info/algo/enonces5.htm # Exercice 5.2 """ Ecrire un algorithme qui demande un nombre compris entre 10 et 20, jusqu’à ce que la réponse convienne. En cas de réponse supérieure à 20, on fera apparaître un message : « Plus petit ! », et inversement, « Plus grand ! » si le nombre est inférieur à 10. """ """...
from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), path('bands/', views.BandListView.as_view(), name='bands'), path('bands/<slug:slug>', views.BandDetailView.as_view(), name='band-detail'), path('players/', views.PlayerListView.as_view(), name='players'), path...
import numpy as np import random import os from tqdm import tqdm from PIL import Image import torch import torch.nn as nn from torch.nn.modules import loss from torch import optim from torchvision import transforms def train(model, device, train_loader): model.train() model.to(device) train_loss_D, train...
from app import app import sys from termcolor import colored, cprint if __name__ == "__main__": cprint('CPILOT RUNNING...', 'green', 'on_red') #print(colored('CPILOT RUNNING...', 'green')) app.run()
class Solution(object): def removeInvalidParentheses(self, s): from collections import deque visited = set([s]) ans, queue, flag = [], deque([s]), False while queue: node = queue.popleft() if self.isValid(node): flag = True ans....
# Taking set input dynamically:: s={} print(type(s)) s={int(i) for i in input('Enter::').split()} print(s) print(type(s)) # Set builtin function:: s1={11,12,31,45,4} s1.add(19) print('add function::') print(s1) # add(x) adds x in set unorderly s1.remove(12) print("remove function:: ") print(s1) ...
#-*- coding:utf8 -*- from django.contrib import admin from shopback.categorys.models import Category,ProductCategory class CategoryAdmin(admin.ModelAdmin): list_display = ('cid','parent_cid','name','is_parent','status','sort_order') #list_editable = ('update_time','task_type' ,'is_success','status') lis...
# Syntax highlighter - convert python code into html entities # At the moment this is just a code viewer, but before long, it'll be something awesome. import keyword # Contains a list of all the python keywords. import re class DocumentObj: def __init__(self, text = ''): self.text = text def robust_...
# Generated by Django 3.2 on 2020-07-15 19:46 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('main', '0012_auto_20200715_1817'), ] operations = [ migrations.AlterField( model_name='bazaar_user', name='location_id...
import datetime from functools import wraps def time_and_log(logger): def time_and_log_decarator(function): @wraps(function) def wrapper(*args, **kwargs): a = '' if not args else args ka = '' if not kwargs else kwargs logger.info(f'Attempting to execute `{functi...
msg="welcome to python" print(msg)
from django.db import models from CBF.abstract_models import CommonPostInfo from membership.models import Member from django.template.defaultfilters import slugify class Tag(models.Model): name = models.CharField('Categoria', max_length=80) def __str__(self): return self.name def get_count_relat...
import json import shortuuid from interface import implements from backend.common.messaging.message_handler import MessageHandler import backend.proto.message_pb2 as pb from backend.user_service.user.domain.rider import Rider from backend.user_service.user.domain.driver import Driver def _extract_user_id_list_from...
import sys sys.path.insert(1, str().join(['/' + i for i in __file__.split('/')[1:-3]])) import unittest from sensor_controller import * class TestSetSensor(unittest.TestCase): def setUp(self): self.controller = SensorController() def test_set_sensor_1(self): ...
import requests import zipfile import os apikey = raw_input('API Key: ') HEADERS = {"X-API-Key": apikey} r = requests.get("http://www.bungie.net/Platform/Destiny/Manifest/", headers=HEADERS); manifest = r.json() mani_url = 'http://www.bungie.net'+manifest['Response']['mobileWorldContentPaths']['en'] #Download the f...
import time name = input("请您输入姓名:") age = input("请您输入年龄: ") print('---------------------------') print("您的名字是:"+name) print("您的年龄是: "+age) a = int(time.strftime('%Y',time.localtime()))+100-int(age) man = str(a) print(name+"将在"+man+"年满100周岁!")
from flask import Flask, render_template, request import datetime import sqlalchemy as sa from flask_sqlalchemy import SQLAlchemy from sqlalchemy import Column, Integer, Text, String, Float, DateTime, desc import dateutil.parser import numpy as np from sklearn.linear_model import LinearRegression import logging # logg...
# Generated by Django 2.2.6 on 2019-12-19 03:16 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Word', fields=[ ...
from Bio import SeqIO from math import factorial sequence = '' with open('sampledata.fasta', 'r') as f: for record in SeqIO.parse(f, 'fasta'): sequence = str(record.seq) A, U, G, C = 0, 0, 0, 0 for nt in sequence: if nt == 'A': A += 1 elif nt == 'U': U += 1 elif nt == 'G': ...
from tile import Tile import pygame class Character(Tile): """Contain the functions relative to the main character""" def __init__(self, img, text): Tile.__init__(self, img, text) self.startx = -100 self.starty = -100 def set_starting_pos(self, x, y): """Set the initial ...
#----------------------------------------------------------------------------- # # Copyright (c) 2006-2007 by Enthought, Inc. # All rights reserved. # #----------------------------------------------------------------------------- """ The default UI service factory. """ # Enthought library imports. from traits.api...
#import sys #input = sys.stdin.readline from collections import defaultdict def main(): N = int( input()) A = list( map( int, input().split())) d = defaultdict( int) e = defaultdict( int) ans = 0 for i in range(N): a = A[i] ans += d[a+(i+1)] ans += e[a-(i+1)] d[(i...
if __name__ == "__main__": alien_color = 'green' if alien_color == 'green': print("You just got 5and6 points!") else: print("You just got 10 points!") # version2 alien_color = 'yellow' if alien_color == 'green': print("You just got 5and6 points!") else: pri...
import numpy as np import tensorflow as tf import os os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' class Config(object): """ define a class to store parameters, the input should be feature mat of training and testing Note: it would be more interesting to use a HyperOpt search space: https://github.co...
from ED6ScenarioHelper import * def main(): # 格兰赛尔 CreateScenaFile( FileName = 'T4107 ._SN', MapName = 'Grancel', Location = 'T4107.x', MapIndex = 1, MapDefaultBGM = "ed60018", Flags = 0, ...
from intent_handling.signal import Signal class TermAllUpperIntent: NAME = 'TERM_ALL_UPPER' def __init__(self, parameters): self.parameters = parameters def execute(self, db): sql = 'SELECT code from course_terms WHERE code >= 300 AND term="{}"'.format(self.parameters.quarter) re...
from django.contrib.auth.forms import UserCreationForm from . models import User from django import forms from Eliezer_Website.custom_functions import image_400 class SignUpForm(UserCreationForm): class Meta: model = User fields = ['username', 'password1', 'password2'] class UpdateForm(forms.Mod...
import numpy as np import cv2 from matplotlib import pyplot as plt from sift_extractor import SIFT_Extractor class Homography_Finder: def __init__(self, minNumberOfMatches = 1, numKeyPoints = 500, scaleFactor = 200): #Parameters. self.minNumberOfMatches = minNumberOfMatches self.siftExt = SIFT_Extractor(num...
# -*- coding:utf-8 -*- print 1.0/2 print 1/3 print 1//3 print 1.0//3
''' 1. This python script generates all theoretically possible (A(1-x)A'x)BO3 and A(B(1-x)B'x)O3 perovskite oxides 2. The generated new compounds are also subject to charge neutrality condition and pauling's valence rule @Achintha_Ihalage ''' import numpy as np import pandas as pd import itertools import pathlib fro...
#!/user/bin/python #coding:utf-8 __author__='yanshi' from com.sy.util import data import numpy as np import jieba import gensim from gensim import models class LSACorpus(): def __init__(self, stopWordsPath, fileTitle, fileIntro): initData=data.Init() self.stopWords=initData.loadStopWords(stopWord...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models from django.conf import settings import profiles.models class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ ...
#CSCI 1133 Homework 3 #Sid Lin #Problem 3A def doubleCheck(lst, order): count = 0 for i in range(len(lst)): #this loop counts how many times a term occurs in the list #so it checks for duplicates if(order == ""): #disregards null orders count += 0 elif(order == lst[i...
from typing import List, Dict, Tuple import re from .base_factory import BaseFactory PROG = re.compile(r"([0-9A-Z\s\-]+)\:([0-9A-Za-z]+)") PROG_DASH = re.compile(r"([0-9A-Z]+)\-([0-9A-Z]+)") class UnicodeMapping(BaseFactory): def __init__( self, unicode_mapping_path: str, o...
def checkrow(matrix,max,possiblemaze): for i in range(max): for j in range(max): if matrix[i][j]!=0: possiblemaze[i][j].clear() possiblemaze[i][j].add(matrix[i][j]) for x in range(max): if x!=j: possiblemaze[i][x].discard(matrix[i][j]) return possiblemaze
# File: pos_tagging.py # Template file for Informatics 2A Assignment 2: # 'A Natural Language Query System in Python/NLTK' # John Longley, November 2012 # Revised November 2013 and November 2014 with help from Nikolay Bogoychev # Revised November 2015 by Toms Bergmanis # PART B: POS tagging # The tagset we shall us...
import pysickle.inout as io import os import sys def choose_file(): file_list = os.listdir(os.getcwd()) print('Which file would you like to analyse?') # print files in current directory i = 1 for x in file_list: print('%s: %s' % (i, x)) i += 1 # ask for input file number unti...
def addNumbers(x, y): return x + y def subtractNumbers(x, y): return x - y def multiplyNumbers(x, y): return x * y
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Wed May 16 16:19:51 2018 @author: meicanhua """ import jieba import jieba.posseg as pseg import multiprocessing import os import time import sys # 多进程跑 # jieba.enable_parallel(multiprocessing.cpu_count()) stopwords_nature = ["m","mq","mg","b","begin","bg...
""" this is the base parser for html and json and other format """ import json from bs4 import BeautifulSoup as bs from requests import Session class BaseParser(object): """ base parser for parser requests content """ def __init__(self, *args, **kwargs): """ supply the way to query html...
#./bin/spark-submit --packages org.apache.spark:spark-sql-kafka-0-10_2.12:3.0.0 spark_test.py from pyspark import SparkContext from pyspark.sql.session import SparkSession from pyspark.sql.functions import col spark = SparkSession.builder.master("local").appName("Test PY App").getOrCreate() from pyspark.sql.functio...
from django.urls import path from . import views urlpatterns=[ path('git/',views.deptGit,name='git'), path('git/enseingnement',views.deptGitEns,name='giten'), path('git/matiere',views.deptGitMat,name='gitmt'), path('git/DIC1',views.deptETDIC1,name='gitdic1'), path('git/DIC2',views.deptETDIC2,name='...
# -*- coding: utf-8 -*- """ Created on Mon Apr 9 11:24:29 2018 @author: Marcin """ balance = 3329 annualInterestRate = 0.2 minimumMonthlyPayment = 0 previousBalance = balance monthlyInterestRate = annualInterestRate / 12 while previousBalance >= 0: previousBalance = balance minimumMonthlyPa...
class TreeNode: def __init__(self, x,left=None,right=None): self.val = x self.left = left self.right = right class Solution: def isValidBST(self, root: TreeNode) -> bool: return self.isValidBSTHelper(root,float('-inf'),float('inf')) def isValidBSTHelper(self, root: Tre...
import sys # import scipy import pandas as pd import numpy as np import matplotlib.pyplot as plt from scipy.spatial import distance from sklearn.preprocessing import StandardScaler from sklearn.decomposition import PCA from sklearn.manifold import TSNE random_state = 123 def pca_analysis(X, n_components=2, random_s...
# -*- coding: utf-8 -*- ############# # # Copyright - Nirlendu Saha # # author - nirlendu@gmail.com # ############# import re, sys, inspect from app_core import core_interface as core from libs.logger import app_logger as log def get_url(text): urls = re.findall('http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),...
import json import urllib2, httplib import time import smtplib from datetime import date, timedelta import shutil import math import sys import glob import os from email.mime.multipart import MIMEMultipart from email.mime.base import MIMEBase from email.mime.text import MIMEText import config as cfg import template im...
from typing import List class Solution: def run_fastest_dfs(self, i, j, grid): if i in [-1, self.xlen] or j in [-1, self.ylen]: print("越界", i, j) return elif grid[i][j] != '1': return else: grid[i][j] = '2' # shang se...
from getpass import getpass DATABASE = "database.txt" ban_status = "No" restrictions = "No" def displayAdminMenu(): print("Choose an option: ") print("1. Change password.") print("2. Show the list of users.") print("3. Add a new unique user.") print("4. Block user.") print("5. Turn...
from django.contrib import admin from models import Document class DocumentAdmin(admin.ModelAdmin): list_display = ('title','add_date') ordering = ('add_date',) admin.site.register(Document, DocumentAdmin)
#!/usr/bin/env python # -*- coding: utf-8 -*- # @python: 3.6 import torch from torch import nn import torch.nn.functional as F from torch.utils.data import DataLoader def test_img(net_g, datatest, args): net_g.eval() # testing test_loss_2 = 0 correct_2 = 0 counter_2_target = 0 counter_2_bool ...
import warnings import numpy as np class Predictor(): """ Object representing a function to fit a learning curve (See :class:`learning_curves.LearningCurve`). """ def __init__(self, name, func, guess, inv=None, diverging=False, bounds=None): """ Create a Predictor. Args: ...
# diaryhelper asks questions about your day in a regular interval so that you don't forget about writing your diary q = {} localq = q def debug(): global q, localq q={'what did you eat today?': '21', 'what time did you get up?': '15', 'what did you do today?': '22'} localq = q print(q) # c...
import os import shutil import sys ######## # importing csv module import csv import shutil # csv file name filename = "train.csv" # initializing the titles and rows list fields = [] rows = [] non_bmp_map = dict.fromkeys(range(0x10000, sys.maxunicode + 1), 0xfffd) # reading csv file with open(filename, 'r',encod...
from abc import abstractmethod, ABC from pepy.domain.model import ProjectName, Password class DomainException(ABC, Exception): @abstractmethod def message(self) -> str: pass class ProjectNotFoundException(DomainException): def __init__(self, project_name: str): self.project_name = proje...
# Matematiske operatorer og operatorpresedens (hva som utføres først). # Multiplikasjon, * produkt = 8 * 7 print('Produktet er', produkt) print() #Linjeskift # Divisjon, / resultat = 76 / 4 print('Resultatet av 76:4 er', resultat) #Merk at svaret kommer som float() print() # Helgens lektyre, oppgave til...
# Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def buildTree(self, inorder, postorder): """ :type inorder: List[int] :type postorder: List[int] :rtype: TreeNode ...
#coding=utf-8 import time import smtplib from email.mime.text import MIMEText from email.header import Header from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart def send(head, content) : try: local_date = time.strftime("%Y%m%d", time.localtime()) sender = '' #发...
""" A cache stores static files to speed up future requests. A few built-in caches are found here, but it's possible to define your own and pull them in dynamically by class name. Built-in caches: - test - disk Example built-in cache configuration: "cache": { "name": "Disk", "path": "/tmp/data", ...
""" This module helps reduce the need to know arcpy for mapping. There are a few basic functions here that, when combined correctly, can create any number of maps quickly. This tool can use multiple CSVs, columns, and MXDs to create a large number of maps. Module users should use the create_dir() function first to set-...
import boto3 def lambda_handler(event, context): instances = event.get("instance_ids") or [] state = event.get("state") ec2 = boto3.client('ec2') if state == "running": ec2.start_instances(InstanceIds=instances) elif state == "stopped": ec2.stop_instances(InstanceIds=...
#!/usr/bin/python # -*- coding: utf-8 -*- """ The script gets Teamcity remote build status and set the REMOTE_BUILD_NUMBER parameter. If no builds found the script will exit with errorcode 1. To change this behaviour add argument --no-fail-missing You can customize messages with template strings. See expand_template...
from django.db import models # Create your models here. class Book(models.Model): nome = models.CharField(max_length=50,unique=True) descricao = models.CharField(max_length=100) nota = models.IntegerField() def __str__(self): return self.nome
import logging from flask import Flask from app import factory def add_logging_to_app(app): handler = logging.StreamHandler() handler.setLevel(logging.DEBUG) app.logger.addHandler(handler) return app def create_app(*args, **kwargs): app = factory.create_app(*args, **kwargs) return add_loggin...
#!/usr/bin/python from flask import Flask from flask_restful import Resource, Api, fields, marshal_with, reqparse import hue app = Flask(__name__) api = Api(app) parser = reqparse.RequestParser() parser.add_argument('on', type=bool) parser.add_argument('saturation', type=int) parser.add_argument('value', type=int) p...
from collections import namedtuple, defaultdict Grade = namedtuple('Grade', ('score', 'weight')) class Subject: def __init__(self): self._grades = [] def report_grade(self, score, weight): self._grades.append(Grade(score, weight)) def average_grade(self): total, total_wei...
from torch.utils.data import Dataset from skimage import io from utils import read_data import torch import torch.nn as nn import torch.nn.functional as F class IDCardsDataset(Dataset): """ Dataset of ID card images. """ def __init__(self, dataset_path, transform=None): self.data = read_data...
import pyautogui import time from PIL import ImageGrab,ImageOps from numpy import * class cordinates(): replay=(960,450) dino=(663,464) tree1=(708+26,458) tree2=(741+26,498) spbreak1=(1000,470) spbreak2=(1100,470) def restartgame(): pyautogui.click(cordinates.replay) ...
import numpy as np import utils from pydrake.all import MathematicalProgram, Solve, Variables from pydrake.symbolic import Polynomial from pydrake.common.containers import EqualToDict # the parameters just have to be two arbitrary functions # not necessarily in the nocontact/leftcart contact modes def fuse_functions(V_...
from sklearn.externals import joblib from sklearn.datasets import fetch_20newsgroups import pprint categories = [ 'alt.atheism', 'talk.religion.misc' ] print type(categories) data = fetch_20newsgroups(subset='test',categories = categories,remove=('headers','footers','quotes')) def main(): datatemp = [data['data'][...
""" PCPP-32-101 1.3 Understand and use the concepts of inheritance, polymorphism, and composition - class hierarchies - single vs. multiple inheritance - Method Resolution Order (MRO) - duck typing """ class A: # noinspection PyMethodMayBeStatic def method(self) -> None: print("A.method() called")...
import numpy x = int(input()) A=[] B=[] for i in range(x): A.append(list(map(int,input().split()))) for i in range(x): B.append(list(map(int,input().split()))) print (numpy.dot(numpy.array(A), numpy.array(B)))
# Define a function reverse() that computes the reversal of a string. # For example, reverse("I am # testing") should return the string "gnitset ma I". def string_reverse(string1): reverse_str = string1[::-1] return reverse_str print(string_reverse("I am testing")) def reverse_str1(string2): reverse_st...
#Project Euler Problem 44 # What is the smallest pair of pentagonal numbers whos sum and difference is also pentagonal Range=10000 PentagonalNum=[] PentDiff=[] #Make a bunch of pentagonal numbers and store them in an array for i in range(1,Range): PentagonalNum.append(int(i*(3*i-1)/2)) for i in PentagonalNum: ...
from django_includes._version import __version__ __all__ = ["__version__"]