text
stringlengths
8
6.05M
# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% # % Extreme EEG Signal Analyzer with P300 Detector % # % Algorithms % # % % # % Copyright (C) 2019 Cagatay Demirel. All rights reserved. % ...
import unittest import os import platform from conans import tools from conans.test.utils.tools import TestClient from conans.test.utils.test_files import temp_folder from conans.paths import CONANFILE, long_paths_support from conans.model.ref import ConanFileReference, PackageReference import re conanfile_py = """ ...
class Time: """Represents the time of a day. attributes: hour, minute, second""" def print_time(t): '''takes a Time object and prints the time''' print("%.2d:%.2d:%.2d"%(t.hour, t.minute, t.second)) def time2int(t): seconds = (t.hour*60 + t.minute) *60 + t.second return seconds def int2time(s...
#!/usr/bin/env python # -*- coding: utf-8 -*- # Imports from skimage import io import pandas as pd import fastparquet as fp import numpy as np import os import tempfile def readTiff(filename): """Read data from the tiff file and return a Pandas dataframe""" filenamePrefix = os.path.splitext(os.path.base...
import xml.etree.ElementTree as ElementTree import json import datetime # add <!doctype HTML> yourself f = open("today.json") jsondata = json.load(f) f.close() tree = ElementTree.parse("base.html") html = tree.getroot() guide = html.find("./body/div[@id='guide']") TFACTOR = 3 # 1 min = TFACTOR pixels x = 150 now = ...
import pymorphy2 import string # функция по обработке текста и преобразования его в нормализованный список def tokenize_text(file_text): morph = pymorphy2.MorphAnalyzer() tokens = file_text.split(" ") tokens = [i.lower() for i in tokens if (i not in string.punctuation)] # удаление пунктуации tokens = [...
from tensorflow.keras.preprocessing.image import ImageDataGenerator def process_data(train_path, test_path, img_dims, batch_size): """ Creat Train set (with data augmentation) and test set using ImageDataGenerator Parameters ---------- train_path : path of train set test_path : path of test se...
#!/usr/bin/env python #coding:utf-8 from flask import Flask,render_template,request from flask_jsonrpc import JSONRPC import json app = Flask(__name__) jsonrpc = JSONRPC(app, '/api') @jsonrpc.method('user.list') def index(username, passwd): if username=='chen' and passwd=='123': return 'Hello,Flask JSON-R...
class Solution: def arrayPairSum(self, nums: List[int]) -> int: if(len(nums) == 0): return 0 nums.sort() sum=0 b=len(nums) for a in range(0,b,2): sum+=nums[a] return sum
import codecademylib3_seaborn from sklearn.model_selection import train_test_split from sklearn.datasets import load_breast_cancer from sklearn.neighbors import KNeighborsClassifier from matplotlib import pyplot as plt breast_cancer_data = load_breast_cancer() X_train, validation_data, y_train, validation_test = train...
#https://leetcode-cn.com/contest/weekly-contest-218/problems/goal-parser-interpretation/ class Solution: def interpret(self, command: str) -> str: resultStr:str = "" index = 0 while index < len(command): if command[index] == '(': if command[index+1] == ')': ...
import random import time for x in range(360): data = open("data.txt", "a") line1 = str(x) line2 = str(random.uniform(1,10)) data.write(line1 + ' ' + line2 + '\n') data.close() time.sleep(0.1)
n = input("Enter n: ") n = int(n) count = 1 divisors = [] sum_of_divisors = 0 is_perfect = False while count <= n - 1: if n % count == 0: divisors += [count] sum_of_divisors += count count += 1 if sum_of_divisors == n: is_perfect = True print("Number {} with divisors {} is perfect? {}"....
import datetime import secrets from blog import app, mongo from blog.decorators import token_required from blog.posts.models import Post from flask_pymongo import ObjectId from flask import request, jsonify @app.route('/post/create', methods=['POST']) @token_required def create_post(current_user): data = request.js...
primeiroTermo = float(input('Digite o primeiro termo: ')) diferenca = float(input('Diferenca: ')) print(primeiroTermo, end=" >> ") for i in range(1, 11): primeiroTermo += diferenca print(primeiroTermo, end=" >> ") print("FIM")
""" 2017 Steamworks vision code for Team 2811 (StormBots) """ import cv2 import numpy as np from grip import GripPipeline import os from networktables import NetworkTables import logging import time import sys import math import datetime import traceback # tested using pip package Adafruit-GPIO # sudo pip install A...
#-*-coding: utf-8 -*-# class HousePark(): __lastname__ = "박" #프라이빗의 의미 def __int__(self, name): self.full_name = self.__last_name__ + name def trabel(self,where): print("%s, %s 여행을 가다"%(self.full_name, where)) pey = HousePark("응용") print(pey.__lastname__)
from authentication.models import Person from rest_framework import serializers from django.contrib.auth.hashers import make_password class PersonSerializer(serializers.ModelSerializer): class Meta: model = Person exclude = ['created_at', 'updated_at'] extra_kwargs = { 'passwo...
class Solution(object): def generateTrees(self, n): if n == 0: return [] return self.dfs(1, n) def dfs(self, start, end): if start > end: return [None] res = [] for idx in range(start, end + 1): leftnodes = self.dfs(start, idx - 1) ...
# app/models.py from flask_login import UserMixin from werkzeug.security import generate_password_hash, check_password_hash from app import db, login_manager class Employee(UserMixin, db.Model): """ Create an Employee table """ # Ensures table will be named in plural and not in singular # as is...
from django.shortcuts import render, redirect from django.contrib.auth import logout from django.contrib.auth.models import User from django.contrib.auth.decorators import login_required from django.views.decorators.http import require_http_methods from django.views.decorators.csrf import csrf_exempt from django.http.r...
from django.contrib import admin from app1.models import Kitap,Yazar # Register your models here. admin.site.register(Kitap) admin.site.register(Yazar)
"""abcd URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/2.2/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based vi...
# -*- coding: utf-8 -*- """ /*************************************************************************** ColorRampManager A QGIS plugin plugin to manage and download color ramp definitions ------------------- begin : 2012-08-04 ...
from PIL import Image import requests from io import BytesIO from datetime import datetime # Get delivery date of cart order # Some sample token. Instead replace with the token returned by authentication endpoint JWT_TOKEN = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJ0ZXN0IiwiaWFkIjoxLCJhY3AiOm51bGwsInRicCI6bnV...
"""System ID""" systemID1 = "Team 1 BS" systemID2 = "Team 2 CCS" systemID3 = "Team 3 EMS" systemID4 = "Team 4 DS" systemID5 = "Team 5 LS" systemID6 = "Team 6 SACS" """Command Codes""" AB = "Apply Brakes" SL = "Signal Lights" AG = "Apply Gas" BL = "Brake Lights" EL = "Emergency Lights" HL = "Headlights" """Date Time S...
# import pytest # from wechaty.wechaty import Wechaty # import pdb # @pytest.mark.asyncio # async def test_mention_text_without_mentions(test_bot: Wechaty) -> None: # """Test extracting mention text from a message without mentions""" # msg = await test_bot.Message.find(message_id="no_mention") # await msg...
''' Suppose we could access yesterday's stock prices as a list, where: The indices are the time in minutes past trade opening time, which was 9:30am local time. The values are the price in dollars of Apple stock at that time. So if the stock cost $500 at 10:30am, stock_prices_yesterday[60] = 500. Write an efficient f...
#form learned from https://www.youtube.com/watch?v=3XOS_UpJirU from django import forms class PersonForm(forms.Form): person = forms.CharField(label='')
from app import db from models import BlogPost # create the db and the db db.drop_all()
from sqlalchemy.orm import Session from quipper import ( models, schemas, ) def create_message(db: Session, message: schemas.MessageCreate): message = models.Message( sender=message.sender, conversation_id=message.conversation_id, message=message.message, ) db.add(message...
from funcparserlib.lexer import make_tokenizer, Token import re ENCODING = 'utf-8' regexps = { 'escaped': r''' \\ # Escape ((?P<standard>["\\/bfnrt]) # Standard escapes | (u(?P<unicode>[0-9A-Fa-f]{4}))) # uXXXX ''', 'unescaped': r''' ...
# Globle variables of configuration parameters DATA_BASE_PATH = "/Volumes/WorkDisk/data/tick2016" # path of raw data OUTPUT_PATH = "/Users/qt/Desktop/Notes/vol_prediction/output" # path to save figures and outputs OUTPUT_DATA_PATH = "/Users/qt/Desktop/Notes/vol_prediction/output...
print("this is line line 1 by master") print("this is line line 2 by master") <<<<<<< HEAD print("this is line line 1 by cloud2") print("this is line line 2 by cloud2") print("this is line line 1 by cloud1") print("this is line line 2 by cloud1") print("this is line line 1 by cloud3") print("this is line line 2 by clou...
""" 同步调用就是你喊你朋友吃饭,你朋友在忙,你就在那等,一直等他忙完了,然后你们一起去吃饭 异步调用就是你喊你朋友吃饭,你朋友说知道了,待会我忙完了去找你,你先忙别的 """ from multiprocessing import Pool import time,os def main(): def func1(): print("进程池中的进程:%d----%d"%(os.getpid(),os.getppid())) for i in range(3): print("-------%d-------"%i) time.sleep(1...
# This file is part of Buildbot. Buildbot 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, version 2. # # This program is distributed in the hope that it will be useful, but WITHOUT # ANY WARRANTY; without eve...
#https://leetcode-cn.com/problems/divide-two-integers/ #不可用 乘法 除法 MOD #不能直接用减法实现,考虑 被除数特别大,而除数又特别小,运算会超时; #不用位移,采用二分法,不停用 除数的N次幂去裁剪区域 + 迭代 class Solution(object): def divide(self, dividend, divisor): """ :type dividend: int :type divisor: int :rtype: int """ changeEx...
# -*- coding: utf-8 -*- # Generated by Django 1.9.8 on 2016-09-18 22:38 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('core', '0026_auto_20160914_1448'), ] operations = [ migrations.AddField( ...
from __future__ import unicode_literals __version__ = '2018.07.21'
import socket import os import time s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) msg = "mesaj" s.sendto(msg.encode(),('127.0.0.1', 9999))
import scipy.stats as stats import numpy as np import fitsio from sklearn import mixture import pickle import pandas as pd def mags2nanomaggies(mags): return np.power(10., (mags - 22.5)/-2.5) def df_from_fits(filename, i=1): """ create a pandas dataframe from a fits file """ return pd.DataFrame.from_reco...
import requests from bs4 import BeautifulSoup yourid="the7mincheol@naver.com" yourpwd="24901402" session=requests.Session() r=session.get("http://class.likelion.net/users/sign_in") html=BeautifulSoup(r.text,"html.parser") token2=html.input.next_sibling["type"] print(token2) token=html.input.next_sibling["value"] pr...
import pickle from struct import pack, unpack from copter.storage import Secret, StorageItem, DataType class IncrementalFile: def __init__(self): self.path = '/tmp/secrets' def add(self, key): with open(self.path, 'ab') as fp: data = pickle.dumps(StorageItem(DataType.ADD, key)) ...
#!/usr/bin/python3 import os uname=input("enter input from user") a=uname.isalpha() if a ==True: passwd="hello"+uname os.system("sudo useradd -m -p "+passwd+" "+uname) print("user created!") else: print("all charcter are not in string!")
#!/bin/python import sys import copy import re infile = open(sys.argv[1], "r") class Cube: KEEPALIVECOUNT = [2,3] ACTIVATECOUNT = 3 def __init__(self, active=False): self.active = active self.nextState = None def getState(self): return self.active def computeCycle(self,...
vertice_a = float(input('Informe o valor do vértice A: ')) vertice_b = float(input('Informe o valor do vértice B: ')) vertice_c = float(input('Informe o valor do vértice C: ')) if (vertice_b - vertice_c) < vertice_a < (vertice_b + vertice_c) and (vertice_a - vertice_c) < vertice_b < (vertice_a + vertice_c) and (vertic...
import tools import re class Mutation: """ Pos is stored zero-indexed such that the start methionine is pos=0 """ regex = re.compile("^([A-Z]?)(-?\d+)([A-Z]?)$") __slots__ = ['ref', 'pos', 'alt'] def __init__(self, ref, pos, alt): self.ref = ref self.pos = pos self.alt ...
#!/usr/bin/python3 # encoding=UTF-8 from pyserpent import Serpent from os import urandom from binascii import crc32 from progbar import ProgBar # progressbar import sys # stderr class LinbootHexEncryptor(Serpent): """ Encrypts intel hex-file with serpent in CBC mode. Initially developed for AVR firmware...
import collections from inputplotdataISM import inputplotdict import argparse parser = argparse.ArgumentParser() parser.add_argument('-f', '--plotitem', default='gf12imhdcv') args = parser.parse_args() print args.plotitem plotlist=[args.plotitem] for plotneed in plotlist: inputplotdict[plotneed]['_plotfunction'](...
import nltk import os import pandas as pd import numpy as np from operator import itemgetter def get_data(num_docs=10000, batch_size=128, data_path=None, get_minibatches=True): """ Gets the word2vec training data. :param num_docs: int; number of documents to use in training :param batch_size: int; siz...
from typing import List from matplotlib import colors import matplotlib.pyplot as plt import matplotlib as mpl import numpy as np #optische Abstandssensor Kennlinie def optischeSensor(x:List[float], y:List[float]): #background plt.style.use('Solarize_Light2') #graph title plt.title("Optische Abstandss...
# -*- coding: utf-8 -*- # Copyright 2019-2020 Lovac42 # Copyright 2014 Patrice Neff # Copyright 2006-2019 Ankitects Pty Ltd and contributors # License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html # Support: https://github.com/lovac42/Blitzkrieg from .main import *
# Imports from idc import BADADDR, INF_BASEADDR, SEARCH_DOWN, FUNCATTR_START, FUNCATTR_END import idc import idaapi import datetime # Settings definePrefix = "" # Prefix for the #define Output functionPrefix = "fn" # Prefix for Function Renaming in IDA offsetPrefix = "o" # Prefix for Offset Renaming in IDA # Globals ...
# # gdb helper commands and functions for Linux kernel debugging # # kernel log buffer dump # # Copyright (c) Siemens AG, 2011, 2012 # # Authors: # Jan Kiszka <jan.kiszka@siemens.com> # # This work is licensed under the terms of the GNU GPL version 2. # import gdb import sys from linux import utils printk_log_type...
# -*- coding: utf8 -*- import os import datetime import time import gtools.sql.compare as sql_cmp import stat_data #SERVER_IDS = (1, 2, 3, 4, 5, 6, 7, 8) SERVER_IDS = (10004,10005,10006,10007,10008) STAT_DAYS = ((2014,9,24), (2014,9,25)) if __name__ == "__main__": os.system("mkdir log") for ser...
import requests import time import json import datetime from Bot_body import telegramBot bot = telegramBot() bot.chunk.fill_date(datetime.datetime.today()) while 1: bot.update() time.sleep(1)
import warnings warnings.simplefilter("ignore", UserWarning) from scipy.optimize import curve_fit import numpy as np import sys import pdb import os # Add my local path to the relevant modules list sys.path.append('/Users/Daniel/Github/Crawlab-Student-Code/Daniel Newman/Python Modules') import Generate_Plots as genp...
from lxml import etree tree = etree.parse("nlp.txt.xml") root = tree.getroot() import sys def find_tuple(dependency): # traverse all deps for dep in dependency.findall("dep"): if "type" in dep.attrib and dep.attrib["type"] == "nsubj": for dep2 in dependency.findall("dep"): ...
N, M = input().split() N, M = [int(N), int(M)] map = [ [] ] * N for i in range(N): map[i] = input() min = 987654321 for s_x in range(N-7): for s_y in range(M-7): cnt1 = 0 cnt2 = 0 for i in range(s_x, s_x+8): for j in range(s_y, s_y+8): distance = s_x - i + s_...
# -*- coding: utf-8 -*- # html = """<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <style type="text/css"> #page-content { background: white; ...
# coding: utf-8 class Solution: # @param n, an integer # @return an integer def reverseBits(self, n): binstr = bin(n)[2:].zfill(32) ans = int(binstr[::-1], base=2) return ans a = Solution() print a.reverseBits(43261596)
#!/opt/loca/bin/python import sys, re, itertools, optparse from math import * optParser = optparse.OptionParser( usage = "python %prog [options] <number of tables to combine> <miRNA DESeq Table> " + "<transcript DESeq table> <alias table> <That number of tables> <out_prefix>", description= "Th...
from ..context import ptpy import pytest available_camera = None try: available_camera = ptpy.PTPy(knowledge=False) except Exception as e: print(e) pass # Use the same camera for a testing session. And skip all tests that use it. @pytest.fixture(scope='session', autouse=True) def camera(): if availab...
import os import json import time import warnings import numpy as np from numpy import newaxis from keras.layers.core import Dense, Activation, Dropout from keras.layers.recurrent import LSTM from keras.models import Sequential from keras.models import load_model from keras.callbacks import EarlyStopping configs = j...
# Author: Curran Lipsett # Date: 12/18/2014 print("Hello World") # This is a simple print statement
#!/usr/bin/python # -*- coding: utf-8 -*- from bts.core import tokenize from bts.models import TermHits, ModelTerms, Field, TermUpdate from datetime import datetime, date, timedelta from google.appengine.api.labs import taskqueue from google.appengine.ext import db import logging TERM_DELIMITER = "@|@" MAX_RUNTIME = ...
from rest_framework import serializers from rest_framework.serializers import Serializer, ModelSerializer from TestOnline.models import Company
""" API for Game Board that allows interaction with boards. """ import json import random from time import sleep import uuid from rest_framework.decorators import api_view from rest_framework.response import Response from rest_framework import status from rest_framework.throttling import AnonRateThrottle from rest_...
from pysubparser import parser from pysubparser.util import time_to_millis from pydub import AudioSegment # find segments of conversation import sys FIVE_SECONDS = 5000 def get_segments(subtitles): segments = [] prev_end = -1000000 curr_segment = None for subtitle in subtitles: this_start ...
pin="881120-1068234" yyyymmdd = "19"+pin[0:6] num = pin[7:] print(yyyymmdd) print(num)
import textwrap import requests_mock import transaction from purl import URL from onegov.form import FormCollection from onegov.pay import PaymentProviderCollection def test_setup_stripe(client): client.login_admin() assert client.app.default_payment_provider is None with requests_mock.Mocker() as m: ...
import OpenPNM as op import time st = time.time() from OpenPNM.Geometry import models as gm #============================================================================== '''Build Topological Network''' #============================================================================== pn = op.Network.Cubic(shape=[...
# módulo destinado a construir el árbol del torneo import funciones_utiles as fu from mis_estructuras import Listirijilla """As seen at https://github.com/IIC2233/contenidos/blob/master/semana-03/ 01-arboles%20y%20listas%20ligadas.ipynb""" class Partido: _id = 16 def __init__(self, equipo1=None, equipo2=No...
import discord from discord.ext import commands from pymongo import MongoClient import os from dotenv import load_dotenv import asyncio from tools import _db, _json, tools, embeds, _c, wembeds import random from PIL import Image, ImageFont, ImageDraw, ImageFilter from discord_components import DiscordComponent...
"""Cluster Mass Richness proxy module Define the Cluster Mass Richness proxy module and its arguments. """ from typing import List, Tuple, final import numpy as np from scipy import special import sacc from ..parameters import ( ParamsMap, RequiredParameters, DerivedParameterCollection, ) from .cluster_m...
# Generated by Django 2.2.5 on 2020-05-21 16:01 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('listings', '0017_auto_20200521_2058'), ] operations = [ migrations.AlterField( model_name='comm...
# -*- coding: utf-8 -*- # Generated by Django 1.11.8 on 2020-03-26 08:00 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('user', '0017_auto_20200319_1057'), ] operations = ...
from django.urls import path,re_path from . import views from django.conf.urls import url #導入url套件 app_name='MessageEmotion' from django.conf.urls import url, include from django.contrib import admin # app_name = 'blog' urlpatterns = [ path('', views.MessageEmotion, name="MessageEmotion"), re_path(r'^ajax/aja...
from tkinter import * from tkinter import ttk from tkinter import messagebox from random import randint maingame =Tk() maingame.title("TIC TAC TOE") maingame.configure(background = '#FA5858') activePlayer = 1 listPlayer1 = [] listPlayer2 = [] computerList = [] comupterPlayed = [] gamemode = 0 def setplayer...
#!/usr/local/bin/python # encoding: utf-8 """ fetch_ryanair_prices.py Created by Jakub Konka on 2011-10-8. Copyright (c) 2011 University of Strathclyde. All rights reserved. """ import sys import os import re from mechanize import Browser br = Browser() br.open("http://www.ryanair.com/") for f in br.forms(): print...
#!/usr/bin/env python3 import sys import subprocess import os import json from datetime import datetime, date from pymongo import MongoClient from plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot from plotly.graph_objs import Pie, Figure, Layout, Heatmap, Scatter def import_meta_data(direct...
import asyncio from discord.ext import commands @commands.group(brief="TBD") async def channel(ctx: commands.Context): if ctx.invoked_subcommand is None: await ctx.send("Need subcommand") @channel.command(brief="TBD") async def create(ctx: commands.Context, *, name: str): # text channel format : no...
from python_framework import Controller, ControllerMethod, HttpStatus from dto import ContactDto @Controller(url = '/contact', tag='Contact', description='Contact controller') class ContactController: @ControllerMethod(url = '/', requestClass = ContactDto.ContactRequestDto, responseClass = Contact...
from jinja2 import Template import os import pdb import sys print(sys.argv) # read in yaml file as string file_string = "" with open("./resources/envoy.yaml", "r") as file: file_string_array = file.readlines() file_string = "".join(file_string_array) # get env vars and set defaults LISTENER_ADDRESS = os.geten...
from bs4 import BeautifulSoup import urllib.request import csv
import pyglet import math from pyglet.gl import * from pyglet.window import key class Model: def get_texture(self, file): tex = pyglet.image.load(file).texture glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST) glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEARES...
''' This package demonstrates to check 1) View total number of access of a site for a page for all users 2) View total number of access between a start date and end date for a user 3) View the top N clients that are access the site for the most We implement the requirements in two ways, using Hashmap and o...
import numpy as np from src.Module.module import Module class ReLU(Module): def forward(self, X): return np.where(X < 0, 0, X) def backward_delta(self, input, delta): return delta * np.where(input < 0, 0, 1)
def my_function(): global c, b, a, d, 次数 c = 1 b = 0 a = 0 d = 0 microbot.microbot_init() microbot.clear_light() WonderCam.wondercam_init() WonderCam.change_func(WonderCam.Functions.CLASSIFICATION) 次数 = 0 microbot.onremote_ir_pressed(microbot.IRKEY.R0, my_function) def my_functi...
import random from rsa import is_probably_prime from rsa import get_inverse import hashlib class DSA: def __init__(self, hash_algorithm, seed_length): self._hashalg = hash_algorithm self._hash = hashlib.new(self._hashalg) self._outlen = hashlib.new(self._hashalg).digest_size * 8 pr...
import sqlite3 def banco(): conn = sqlite3.connect(':memory:') c = conn.cursor() c.execute('''CREATE TABLE teste (id integer, nome text not null)''') c.execute("INSERT INTO teste VALUES (1, 'felipe')") c.execute("INSERT INTO teste VALUES (2, 'dias')") c.execute("INSERT INTO teste VALUES (3, '...
from setuptools import setup, find_namespace_packages with open("README.rst", "r", encoding="utf-8") as fh: long_description = fh.read() setup( name="json2rst", # Replace with your own username version="0.0.1-dev", author="zed tan", author_email="zed@shootbird.work", description="Inelegant too...
import numpy as np import string, glob, sys from collections import Counter alphabet = string.ascii_lowercase deletion_table_file = '/home/yao/Code/ConfusionTables/deletiontable.csv' insertion_table_file = '/home/yao/Code/ConfusionTables/insertionstable.csv' substitution_table_file = '/home/yao/Code/ConfusionTables/s...
#!/usr/bin/env python # coding: utf-8 # In[2]: import matplotlib.pyplot as plt import numpy as np #install using pip ==> pip install numpy # ## Line and setp methods # ### Recap of the line plot # In[4]: x = np.arange(10) y1 = [1, 9, 7, 10, 3, 16, 2, 20, 5, 22] y2 = [11, 22, 7, 1, 14, 6, 8, 2, 15, 3] plt.plot(...
from collections import Counter from itertools import product import numpy as np from sklearn.metrics import accuracy_score def get_unique_proba(labels): total = len(labels) c = {k: v/total for k,v in Counter(labels).items()} return c def gini_impurity(labels): unique = np.array(list(get_unique_proba(label...
from dataclasses import dataclass, field from abc import abstractmethod from typing import List import copy class PersistenceProvider: @abstractmethod def save_state(self, path: List[str], state: dict): pass def get_state(self, path: List[str]) -> dict: pass EMPTY_STATE = { "local":...
# this app is an instagram crawler that uses your username and password to log In and then it goes to the target username that you give to the program. # Then it scrolls down and prints the links of all images. # The target username is sepehr.akbarzadeh by default but you can change it. # Developer : Shahriar Hashemi #...
from flask import Flask, render_template, request app = Flask(__name__) ans = {"ans1": "hummingbird moth", "ans2": "mimic octopus"} def checkans(guess, ans): return guess == ans @app.route("/") @app.route("/home") def home(): return render_template("home.html") @app.route("/about") def about(): ...
# Generated by Django 2.0.2 on 2019-09-26 20:04 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('app', '0002_auto_20190927_0044'), ] operations = [ migrations.AlterField( model_name='userprofile', name='person', ...
from settings import PATH_TO_NUMPY_DATA_FOLDER from np_datasets_wizard.utils import np_to_json import easygui import json import numpy as np def get_lead_signal(ecg, lead_name): return ecg['Leads'][lead_name]['Signal'] def cut_from_signal(ecg, start_point, leads_names, patch_len): result = [] for lead_n...