text stringlengths 38 1.54M |
|---|
#!/usr/bin/python3
import os
import sys
FILE_LOCATION = "/var/log/hymera/"
class csvWriter():
def __init__(self, fileName):
self.file = FILE_LOCATION + fileName
os.environ["FILENAME"] = FILE_LOCATION + fileName
with open(self.file, "w") as f:
pass
def writeToFile(self, dataToWrite):
with open(self.file,... |
# Program: monkey_problem.py
# Class: cs131
# Date: 10/8/14
# Author: Joel Ristvedt
# Description: The Monkey Problem program solves for the number of coconuts
# in the problem in the instructions function over a range designated by the
# user. The user specifies w... |
# -*- coding: UTF-8 -*-
from django.http import HttpResponse,HttpResponseRedirect
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.models import User
from django.contrib.auth.decorators import login_required
#from django.contrib.auth.forms import
from django.shortcuts import redirec... |
#!/usr/bin/env python
# coding=utf-8
#决策树算法
import pandas as pd
from sklearn.ensemble import GradientBoostingRegressor
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
#读取文件数据
Wdata = pd.read_csv('F:\learningsources\graduation project\dataset\depth_train.csv',sep=' ',header=None,nam... |
from django.contrib import admin
# from django.contrib.gis.db import models
# from mapwidgets.widgets import GooglePointFieldWidget
#
# class Port(admin.ModelAdmin):
# formfield_overrides = {
# models.PointField: {"widget": GooglePointFieldWidget}
# }
|
#!/usr/bin/env python
"""
Use: ./realign.py 1000_logs.fa alignpt.fa
"""
import sys
import fasta
import itertools
nuc = open(sys.argv[1])
pt = open(sys.argv[2])
doc = open("alignew.fa", "w")
for (nident, nseq), (pident, pseq) in itertools.izip(fasta.FASTAReader(nuc), fasta.FASTAReader(pt)):
position = 0
for p ... |
import curses
def main(stdscr):
curses.start_color()
curses.use_default_colors()
stdscr.addstr(f"{curses.COLORS}\n")
for i in range(0, curses.COLORS):
curses.init_pair(i + 1, i, -1)
try:
for i in range(0, 511):
stdscr.addstr(f"{i} ", curses.color_pair(i))
stdscr... |
import copy
import time
import pygame
import cv2
import cv2.aruco as aruco
import numpy as np
from Dame.constant import X, Y, PLAYER1
from Dame.ai_logic import minimax
from Dame.table import draw_piece, creating_piece
from Dame.logic import execute_move
def get_piece_on_board():
board = np.zeros([Y, X], dtype=int... |
# Generated by Django 2.1.7 on 2019-03-27 07:21
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('AcAdmin', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='add_officer',
name='id',
... |
from app import app
from flask import render_template
# contendra todas nuestra vistas
@app.route("/")
def index():
return render_template("public/index.html")
@app.route("/about") # todo
def about():
return render_template("public/about.html")
|
# Generated by Django 2.2.3 on 2019-07-22 21:24
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='About',
fields=[
('id', models.AutoField(au... |
import cv2
def CatchFace(window_name, catch_pic_num, path_name):
cv2.namedWindow(window_name)
cap = cv2.VideoCapture(0)
classfier = cv2.CascadeClassifier(
r"./openCv/opencv/data/haarcascades/haarcascade_frontalface_alt2.xml"
)
color = (115, 233, 86)
num = 1
while cap.isOpened():
... |
from django.db import models
from django.contrib.auth.models import User
class Estudante(User):
matricula = models.CharField(max_length=15)
|
"""
Terminator plugin to open a file using a chosen editor.
Author: michele.silva@gmail.com
License: GPLv2
"""
import inspect, os, shlex, subprocess
from terminatorlib import plugin
from terminatorlib import config
AVAILABLE = ['EditorPlugin']
DEFAULT_COMMAND = '{filepath}'
DEFAULT_EDITOR = 'kate'
DEFAULT_REGEX = '[^... |
#!/usr/bin/python3
class Solution(object):
def rightSideView(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
if root is None:
return []
res = []
curLevel = [root]
while curLevel:
nextLevel = []
tmpRes =... |
#!/usr/bin/env python3
import os
import re
import sys
import pickle
import shutil
import hashlib
import tempfile
import subprocess
# list of: descr(str) fname(str) tags(list(str)) md5(str) size(int)
database = []
def dbRead():
global database, fileSizes, hashes
database = pickle.load(open('archive.p', 'rb'))
def ... |
# Generated by Django 2.2.1 on 2020-04-16 08:08
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('user', '0001_initial'),
]
operations = [
migrations.RemoveField(
model_name='actioncomment',
name='action',
... |
"""Write an application which takes an integer number as an input (num).
Return a list of 'num' primary elements from fibonacci sequence starting from beginning
e.g: Given: fibonacci sequence "0, 1, 1, 2, 3, 5, 8, 13, 21, ..."
When: user type '4' as application input
Then: application returns [2, 3, 5, 13]"""... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
query for chatterbot
input format:
question:can be any string
output files:
anwser: result from query
Usage:
query.py -q <question> -w <way(edit_distance,tfidf)>
"""
import re
import os, sys
import pandas as pd
import traceback
import requests... |
#segundo taller de diccionarios
"""
Escribir un programa que almacene el diccionario con los créditos de las asignaturas de un
curso matemáticas, física, química y solicitar al usuario los créditos de estas, después
muestre por pantalla los créditos de cada asignatura en el formato <asignatura> tiene
<créditos> crédito... |
from isbn_srch import isbn_srch as srch
from json import dumps
while True:
search = input("isbn: ")
if search == "quit":
print("quitting isbn search....")
break
data = srch(isbn = search, create_json = True, json_name = "isbn+title")
print (data) |
# !/usr/bin/env python
# -*- coding: utf-8 -*-
"""Custom exception raised by pyswitcheo"""
# Human readable http error codes
import json
from http import HTTPStatus
_ERR = {
HTTPStatus.BAD_REQUEST: "Your request is badly formed.",
HTTPStatus.UNAUTHORIZED: "You did not provide a valid signature.",
HTTPStat... |
from SimMuon.MCTruth.muonAssociatorByHitsNoSimHitsHelper_cfi import *
muonSimClassifier = cms.EDProducer("MuonSimClassifier",
muons = cms.InputTag("muons"),
trackType = cms.string("glb_or_trk"), # 'inner','outer','global','segments','glb_or_trk'
trackingParticles = cms.InputTag("mix","MergedTrackTruth"),... |
kąt = 0
tm = TM1637.create(DigitalPin.P8, DigitalPin.P12, 2, 4)
servos.P0.set_angle(0)
def on_forever():
global kąt
if 0 == pins.digital_read_pin(DigitalPin.P14):
basic.show_arrow(ArrowNames.NORTH)
pins.digital_write_pin(DigitalPin.P15, 0)
basic.pause(100)
kąt += 10
serv... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('league', '0002_auto_20150910_1014'),
]
operations = [
migrations.AddField(
model_name='league',
name... |
from flask import Flask, escape, request, jsonify
import json
app = Flask(__name__) # create an app instance
@app.route('/')
def hello():
name = request.args.get('name', 'World')
return 'Hello, {escape(name)}!'
@app.route('/pokedex', methods=['GET'])
def view_pokedex():
return ... |
#to find the minimum no from list
def findmin(lst):
print("The minimum no ",min(lst))
lst=[]
no=int(input("Enter the limits"))
for i in range(no):
ele=int(input())
lst.append(ele)
print(lst)
findmin(lst) |
class ListNode(object):
def __init__(self,x):
self.val = x
self.next = None
a = ListNode(None) |
"""
#!-*- coding=utf-8 -*-
@author: BADBADBADBADBOY
@contact: 2441124901@qq.com
@software: PyCharm Community Edition
@file: prune.py
@time: 2020/6/27 10:23
"""
import sys
sys.path.append('/home/aistudio/external-libraries')
from models.DBNet import DBNet
import torch
import torch.nn as nn
import numpy as np
import co... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import
'''
Takes the output of ipmitool and creates a Zabbix template from it.
'''
__author__ = "Tom Walsh"
__version__ = "0.1.0"
__license__ = "MIT"
import argparse
from pyghmi import exceptions, ipmi
from logzero import logger
from dateti... |
# Generated by Django 2.2.2 on 2019-06-27 19:20
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Alimentos',
fields=[
('id', models.AutoFiel... |
import re
import sys
import time
import paramiko
import logging
from subprocess import Popen
from rackops.oob.base import OobBase
class Dell(OobBase):
def console(self):
ipmi_host = self.oob_info["ipmi"]
try:
Popen(['moob', '-u', '{}'.format(self.username),
'-p', '{}'... |
#!/usr/bin/env python
# coding: utf-8
# #PANDA INTRODUCTION
# In[1]:
get_ipython().system('pip install pandas')
# In[2]:
import pandas as pd
# In[3]:
df = pd.read_csv("http://rcs.bu.edu/examples/python/data_analysis/Salaries.csv")
# In[7]:
df.head()
# In[11]:
df.head(10)
# In[12]:
df.head(20)
... |
import os
import random
import numpy as np
import pickle
from . import dataset_split
from .constants import VNET_INPUT_KEYS, VNET_OUTPUT_KEYS, PRIME_VNET_OUTPUT_KEYS
from pathlib import Path
from tqdm import tqdm
import shutil
class ScorePerformPairData:
def __init__(self, piece, perform):
self.piece_path ... |
# this file is created by Gursimar Kaur
from django.http import HttpResponse
from django.shortcuts import render
def home(request):
return render(request, 'home.html')
def aboutus(request):
return render(request, 'aboutus.html')
def contactus(request):
return render(request, 'contactus.html')
def analy... |
"""HelloWorld Integration for Cortex XSOAR - Unit Tests file
This file contains the Unit Tests for the HelloWorld Integration based
on pytest. Cortex XSOAR contribution requirements mandate that every
integration should have a proper set of unit tests to automatically
verify that the integration is behaving as expecte... |
""" Print the sum of digits in 100!
This is a very easy question ,
I choose to learn python functional programming features from this
I have used reduce(x, y, z)
x is a binary operator that returns a value
y is an iterable object (list, generator .... )
z is the starting value.
... |
import os
import re
import sys
from svcshare.clientcontrol import hellanzbcontrol
from svcshare.clientcontrol import sabnzbdcontrol
class ClientControl(object):
"""Interface to the client using the shared service."""
def __init__(self, proxy, client_name, client_url, client_key):
"""Create a ClientControl ob... |
message = input("Enter your message: ")
message = message.upper()
print(message)
if "H" in message:
print("Letter 'H or h' is present in " + message)
else:
print("Letter 'H or h' isn't present in " + message)
|
import os
import tensorflow as tf
from beam_search import BeamSearch
class BSDecoder(object):
def __init__(self, model, batch_reader, model_config, data_config, vocab, data_loader):
self.model = model
self.batch_reader = batch_reader
self.model_config = model_config
self.data_conf... |
#coding:utf-8
from gensim.models import Word2Vec
import os
#walks = [map(str, walk) for walk in walks]
def load_walks():
walks=[]
for filename in os.listdir("path/result_s_equal"):
print(filename)
for i in open("path/result_s_equal//"+str(filename)).readlines():
newi=i.strip().split('\t')
walks.... |
import re
from flask import Flask, render_template, request, redirect, session, flash
from mysqlconnection import MySQLConnector
from flask.ext.bcrypt import Bcrypt
app = Flask(__name__)
EMAIL_REGEX = re.compile(r'^[a-zA-Z0-9.+_-]+@[a-zA-Z0-9._-]+\.[a-z]+$')
NAME_REGEX = re.compile(r'^[a-zA-Z]+$')
bcrypt = Bcrypt(app)
... |
import random
total_vertex = 10000
f = open("./test.txt", "w")
f.write("{}\n".format(total_vertex))
total_map = {}
for i in range(total_vertex):
total_map[i] = set();
for i in range(total_vertex):
num = random.randint(1, total_vertex / 10)
if num <= len(total_map[i]):
continue
for n in ... |
"""
@File :redis_dealer.py
@Author :JohsuaWu1997
@Date :14/07/2020
"""
from dealer import BasicDealer
import redis
import json
import numpy as np
import pandas as pd
[host, port] = ['192.168.137.153', 6379]
class Dealer(BasicDealer):
def __init__(self, trade_id, unit=100):
self.redisPool = redis.Conn... |
# Generated by Django 3.1.7 on 2021-04-06 06:04
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('Bit', '0002_auto_20210405_2348'),
]
operations = [
migrations.CreateModel(
name='Course_year_2',
fields=[
... |
def longest_subarray_all_equal(A):
"""
Write a program that takes an array of integers and finds the length of a longest subarray whose entries are equal
"""
left, right, max_length = 0, 0, 1
for i in range(1, len(A)):
if A[i] == A[i - 1]:
right += 1
max_length = ma... |
import pandas as pd
#data=pd.read_csv('D:/mother/round1_ijcai_18_train_20180301.txt',nrows=10000,delimiter=' ',header=0)
data=pd.read_csv('D:/mother/round1_ijcai_18_train_20180301.txt',delimiter=' ',header=0)
data.shape
aa=data[['is_trade']]
aa.iloc[:,0].value_counts()
data.isnull().any()
a1=data[['item_category... |
import numpy as np
import math
def normalize(n):
norm = (n[0] ** 2 + n[1] ** 2) ** 0.5
n[0] /= norm
n[1] /= norm
return n
def get_point_type(pt, mask):
try:
if mask[pt[0], pt[1]] == 1:
boundary_detector = mask[pt[0] - 1, pt[1] - 1] * mask[pt[0] - 1, pt[1]] * mask[pt[0] - 1, p... |
# Generated by Django 2.0.7 on 2018-07-26 08:21
from django.db import migrations, models
import django.utils.timezone
import uuid
class Migration(migrations.Migration):
dependencies = [
('shop', '0003_auto_20180725_1358'),
]
operations = [
migrations.AddField(
model_name='or... |
import math
import sys
from pandas import read_csv
import matplotlib.pyplot as plt
# colorblind-friendly colors from the IBM Design Library
# https://davidmathlogic.com/colorblind/#%23648FFF-%23785EF0-%23DC267F-%23FE6100-%23FFB000
ibm_blue = '#648FFFaa'
ibm_violet = '#785EF0'
ibm_red = '#DC267F'
ibm_orange = '#FE6100... |
#from django.test import LiveServerTestCase
from django.contrib.staticfiles.testing import StaticLiveServerTestCase
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import sys
import unittest
class NewVisitorTest(StaticLiveServerTestCase):
@classmethod
def setUpClass(cls):
... |
"""
Helper classes to convert iTunes library XML file to SQLite database to use in Flask app
Usage:
db = SongDb('itunes/library/file.xml', echo=False)
db.create_db()
db.populate_db()
"""
import shutil
import sys
import xml.etree.cElementTree as ET
from peewee import DoesNotExist
from pyItunes import Library
from juk... |
import csv
from Crypto.PublicKey import RSA
from Crypto.Signature import PKCS1_v1_5
from Crypto.Hash import SHA
fp = open("epkk-epwa.csv" , "rt")
try:
reader = csv.reader(fp)
for row in reader:
print(row)
finally:
fp.close()
"""
fp = open("epkk-epwa.csv" , "rt")
l = fp.readline()
print(l.split(','))
"""
cate... |
# coding: utf-8
# In[1]:
decimal = int(input("digite um numero decimal:"))
print(bin(decimal))
|
#!/usr/bin/env python
#
# SPDX-License-Identifier: Apache-2.0
# Copyright Contributors to the OpenTimelineIO project
import unittest
import os
import pkg_resources
import sys
try:
# Python 3.3 forward includes the mock module
from unittest import mock
could_import_mock = True
except ImportError:
# Fal... |
# Copyright 2014 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.
import logging
import optparse
import os
import signal
import subprocess
import sys
import tempfile
import py_utils
from devil.android import device_temp_f... |
from typing import List, Optional
from models.elastic import ESFilterGenre, ESQuery
from models.film import SFilm
from models.interface import AbstractDataStore, AbstractMovie
class Movie(AbstractMovie):
def __init__(self, datastore: AbstractDataStore) -> None:
self.datastore = datastore
def set_mov... |
# -*- encoding: utf-8 -*-
import sys
from math import sqrt
# Parameters for the text gen
max_inrange = 20 # How big difference between a byte in tape and new byte can be for byte reusage
# ------------------------------------------------------------------
# Helper functions for genlogic()
class Bftextgen_exception(E... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals, division, print_function, absolute_import
import re
import inspect
import datetime
import calendar
from flask import url_for
from .compat import *
from .core import commands, Url
commands.add("g google", "http://www.google.com/search?q={}", default=Tr... |
# -*- coding: utf-8 -*-
from django.core.urlresolvers import reverse
from django.db import models
from filebrowser.fields import FileBrowseField
class BaseCategory(models.Model):
title = models.CharField("Название", max_length=255)
slug = models.SlugField("URL", unique=True)
description = models.TextFiel... |
"""
# Example 7.1 CES Production Function Revisited
# Estimating CES Production Function
# Judge, et. al. [1988], Chapter 12
"""
import numpy as np
import pandas as pd
import scipy.optimize as opt
judge = pd.read_csv("http://web.pdx.edu/~crkl/ceR/data/judge.txt",names=['L','K','Q'],sep='\s+')
L, K, Q = judge.L, judge... |
import sys
sys.stdin = open('input.txt')
import string
N = int(input())
_36_to_deci = {h: deci for deci, h in enumerate(string.digits + string.ascii_uppercase)}
deci_to_36 = {deci: h for deci, h in enumerate(string.digits + string.ascii_uppercase)}
count = {deci: 0 for deci in range(36)}
sum = 0
for n in range(N):
... |
import os
from skimage import io,transform
import numpy as np
import matplotlib.pyplot as plt
#肺部数据链接
path_lung = 'G:/阿里天池/肺和结肠癌的组织病理学影像/lung_image_sets/lung_image_sets'
#结肠癌链接
path_colon = 'G:/阿里天池/肺和结肠癌的组织病理学影像/colon_image_sets/colon_image_sets'
# path_lung_aca_img = []
# path_lung_aca_label = [] #标签1
#
# path_lung... |
import sdl2, sdl2.ext
import pybasic.sprite as sp
import pybasic.draw as draw
__all__ = ['create_window', 'refresh_window', 'get_window']
_window = None
def create_window(title, size, position=None, flags=None):
global _window
_window = sdl2.ext.Window(title, size, position, flags)
_window.show()
d... |
import threading
from DBInterface import DBConnection, loginDB, employeeDB, allocationsDB, cabsDB, driversDB, employeeAddressDB
class AgencyInterface (threading.Thread):
def __init__( self, clientConnection, msgList, db ):
threading.Thread.__init__(self)
self.type = "Agency Interface"
self.loginType = "agency"... |
# Create your models here.
from django.db import models
from django.contrib.auth.models import User
# from managers import FriendshipManager
from django.db.models.signals import post_save
class MyUser(models.Model):
user = models.OneToOneField(User)
name = models.CharField(max_length=100, default = 'Me')
... |
from appium import webdriver
# {cmp=com.lemon.lemonban/.activity.MainActivity}
print('new UiSelector().text({})'.format("heell")) |
import json
from models.GCN import GCN
import torch
from dataloader import DEAP
from trainer import Trainer
from torch_geometric.data import DataLoader
import torch.optim as optim
def run(config, train_dataset, val_dataset):
device = 'cpu' if torch.cuda.is_available() else 'cpu'
model = GCN(1, 64, 4, 0.01).t... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : {{create_time}}
# @Author : by {{author_name}}
# @File : {{file_name}}
# @Email : {{email}}
"""
token化模块,除了用已经用的tokenizer,用户必须实现TokenizerBase中的get_tokenizer方法,
"""
import os
from ..core.dataprocessing import DataProcess
DP = DataProcess()
logger = DP.logger
# tr... |
import os
import json
json_file = os.environ.get('JSON_CONFIG')
json_config = json.load(open(json_file)) if json_file else {}
ARTICLES_PER_PAGE = json_config.get('ARTICLES_PER_PAGE', 5)
DATABASE_NAME = json_config.get('DATABASE_NAME', 'mrshoeblog')
PORT = json_config.get('PORT', 8088)
COMMENTS_ENABLED = json_config.get... |
import sys
if len(sys.argv) != 3:
sys.stderr.write("Usage: Python %s inputfile outputfile\n" % sys.argv[0])
raise SystemExit(1)
# print(sys.argv[0])
inputfile = sys.argv[1]
outoputfile = sys.argv[2]
|
"""
These functions read the input, and write the output.
"""
from pandas import read_csv
def read_and_tune_csv_data(fname):
data = read_csv("data/{}".format(fname), dtype=dict(
Sex='category',
Cabin='category',
Embarked='category',
))
return data
def read_train_data():
ret... |
from handler import Handler
from dbschema import User
import crypto
import json
class BlogHandler(Handler):
def set_secure_cookie(self, key, value):
cookie_value = crypto.secure_mesg(value)
self.response.headers.add_header(
'Set-Cookie',
'{0}={1}; Path=/'.format(... |
# coding: utf-8
from abc import ABCMeta, abstractmethod
from threading import Thread
class Subject(object):
#def __init__(self, )
def register(self, newObserver):
self.action()
def unregister(self, deleteObserver):
self.action()
def notifyObserver(self):
... |
class Car :
speed = 5 # 클래스 안에서, 멤버함수 밖에 위치한 변수 (클래스 변수)
def drive(self):
self.speed = 10 # 클래스 안에서, 멤버함수 안에 위치한 변수 (인스턴스 변수)
def output(self):
print ('Car.speed :', Car.speed)
print ('self.speed :', self.speed)
print(Car.speed)
print('-'... |
import numpy as np
a = np.ones((2, 3))
print("a:\n", a, end='\n')
a *= 3
print("a:\n", a, end='\n')
b = np.random.random((2, 3))
b += a
print("b:\n", b, end='\n')
|
class Doctor:
def __init__(self, number):
self.patientAge = number
self.currentPatient = None
self.timeRemaning = 0
def tickTock(self):
if self.currentPatient != None:
self.timeRemaning = self.timeRemaning - 1
if self.timeRemaning == 0 :
... |
# -*- coding: utf-8 -*-
import unittest
from pythainlp.tokenize import THAI2FIT_TOKENIZER
from pythainlp.ulmfit import (
THWIKI_LSTM,
ThaiTokenizer,
document_vector,
merge_wgts,
post_rules_th,
post_rules_th_sparse,
pre_rules_th,
pre_rules_th_sparse,
process_thai,
)
from pythainlp.u... |
#!/usr/bin/env python
# coding:utf-8
# N.B. : Some of these docstrings are written in reSTructured format so that
# Sphinx can use them directly with fancy formatting.
# In the context of a REST application, this module must be loaded first as it
# is the one that instantiates the Flask Application on which other mod... |
import datetime
import enum
class DayOfWeek(enum.Enum):
# Domingo
sunday = "sunday",
# Segunda - feira
monday = "monday",
# Terça - feira
tuesday = "tuesday",
# Quarta - feira
wednesday = "wednesday",
# Quinta - feira
thursday = "thursday",
# Sexta - feira
friday = "fri... |
import heapq
import time
from typing import AbstractSet, Callable, Dict, Optional, Sequence, Tuple
from pddlenv import env
from pddlenv.base import Action, Predicate, Problem
from pddlenv.search import base, utils
Heuristic = Callable[[AbstractSet[Predicate], Problem], float]
class GreedyBestFirst:
def __init_... |
from flask import Flask, request, redirect, url_for, flash, jsonify
from features_calculation import doTheCalculation
import json, pickle
import pandas as pd
import numpy as np
app = Flask(__name__)
@app.route('/api/makecalc/', methods=['POST'])
def makecalc():
"""
Function run at each API call
"""
jsonf... |
class Solution(object):
def maxAreaOfIsland(self, grid):
self.maxArea= 0 #存储最大岛屿的面积
row = len(grid) #存储地图的行数
col = len(grid[0]) #存储地图的列数
for i in range(row):
for j in range(col): #开始从左到右,从上到下的搜索岛屿
if grid[i][j] == 1: #如果发现了陆地的话
cu... |
# -*-coding:"utf-8"-*-
# import pymongo
import tweepy
import time
import random
# joguinho do papel com elementos da grande família!!!!!!!!!!
'''
Quem
Com quem
Fazendo
Onde
Chegou (alguém)
E disse
Moral da história
'''
def popozonize(arqs):
# testando tempo de execução
start = time.time()
conto = ""
... |
from Config import Config
class Browser:
def getDriver(self):
self.driver = Config.environment
return self.driver |
#!/usr/bin/python3
"""
Splitter plików Dr.a Makuchowskiego.
Wymaga do działania:
1. pliku: neh.data.txt
2. folderu splitted
"""
file = open("neh.data.txt", "r")
lines = file.readlines()
file.close()
print("Rozpoczynam parsowanie pliku")
for line in lines:
if "data" in line:
file.close()
file = ... |
"""
Вивести дійсні числа зі списку.
"""
my_list = ['fgjio', 'tthf', 56, 59, 'ufiud', 54.6, 58.3, 77.3]
index_float= 0
for elem in my_list:
elem = index_float
index_float += 1
if index_float isinstance (float):
print(elem)
|
import math, os
from helpers import analytics
analytics.monitor()
dirname = os.path.dirname(__file__)
filename = os.path.join(dirname, "bin", "p099_base_exp.txt")
baseExpPairsFile = open(filename, "r")
pairs = [[int(n) for n in line.split(",")] for line in baseExpPairsFile]
def main():
largest = 0
line =... |
"""
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
This file contains the implementation of a generic graph for the
Travelling Salesman Problem (TSP).
Author: Mattia Neroni, Ph.D., Eng. (Set 2021).
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
"""
impo... |
import pytest
import allure
import json
#=======================================================================================================================
#==================================================== Code 200 =========================================================
#====================================... |
name = input("Sisesta oma nimi: ")
print("Tere, " + name + "!")
city = input("Kus on su elukoht: ")
if city.lower() == "kuressaare":
print("Hei ma olen ka sealt!")
age = int(input("Kui vana sa oled: "))
if age < 18:
print("Sa oled veel liiga noor, et autot juhtida!")
elif age > 18:
print("Sa oled... |
from Vector import Vector
import math
import random
class Vehicle:
maxSpeed = 2
maxForce = 0.05
width = 0
height = 0
c = None
mutationRate = 0.4
def __init__(self, x, y, dna, health):
self.position = Vector(x, y)
self.velocity = Vector(0, -2)
self.acceleration = Ve... |
import sqlite3
from Consts import Consts
from Objects.TwitterLogger import TwitterLogger
class SqliteAdapter():
def __init__(self):
self.connect()
def connect(self):
try:
self.conn = sqlite3.connect(Consts.TWITTER_DB_LOCATION)
except Exception as exc:
print exc
... |
# Blender API imports
import bpy
from bpy.props import StringProperty, BoolProperty, IntProperty
from bpy_extras.io_utils import ImportHelper
from bpy.types import Operator
# Importing the TCK file reader
from . import readtck
# TrainTracts Blender addon info
bl_info = {
"name" : "TrainTracts",
"description"... |
APP_LABEL = 'regmain'
class ATTENDANT_TYPE(object):
NORMAL = 'normal'
VOLUNTEER = 'volunteer'
WORKER = 'worker'
ALL = (NORMAL, VOLUNTEER, WORKER)
class SEX_TYPE(object):
MALE = 'male'
FEMALE = 'female'
TRANSGENDER = 'transgender'
ALL = (MALE, FEMALE, TRANSGENDER)
class FLOW_TYP... |
#########################################################
#importing required files/libraries
import simulation
import optparse
import sys
import os
try:
sys.path.append(os.path.join(os.path.dirname(
__file__), '..', '..', '..', '..', "tools")) # tutorial in tests
sys.path.append(os.path.join(os.enviro... |
"""Imports."""
from node import Node
class LinkedList:
"""Class for new linked lists."""
def __init__(self, iter=[]):
"""Initializer."""
self.head = None
self._len = 0
for item in iter:
self.head = self.insert(item)
def __len__(self):
"""Return len of... |
from django.shortcuts import render, get_object_or_404
from django.db.models import *
import decimal
from django.http import JsonResponse
from django.template.loader import render_to_string
from django.urls import reverse
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from datetime import *
... |
# Compare Version Numbers
'''
Compare two version numbers version1 and version2.
If version1 > version2 return 1; if version1 < version2 return -1;otherwise return 0.
You may assume that the version strings are non-empty and contain only digits and the . character.
The . character does not represent a decimal point a... |
"""
Digital Signal Processing 4
Assignment 2: FIR Filters
By Kai Ching Wong (GUID:2143747W)
"""
import numpy as np
import matplotlib.pyplot as plt
from FIR_Fil import FIR_filter as fir
###############################################################################
"""Task 1"""
ecg = np.loadtxt('Rick... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.