text
stringlengths
38
1.54M
from urllib import request, parse import time import random import json ''' 破解有道词典 V2 处理js加密代码 ''' ''' 通过查找,能找到js代码中操作代码 1. 这个是计算salt的公式 i = "" + ((new Date).getTime() + parseInt(10 * Math.random(), 10)); 2. sign: n.md5("fanyideskweb" + t + i + "]BjuETDhU)zqSxf-=B#7m"); md5一共需要四个参数,第一个和第四个都是固定值的字符串,第三个是所谓的salt,第二个是 第二个...
from configparser import ConfigParser from pymongo import MongoClient import re import string from collections import defaultdict import pickle import src.data.aws_ec2_functions as aws punctuations = string.punctuation config = ConfigParser() config.read('config.ini') # Make sure AWS Ec2 Instance is running and get p...
from PyQt5 import QtWidgets class Main(QtWidgets.QWidget): def __init__(self): super().__init__() self.setupUi() def setupUi(self): self.resize(800, 600) self.verticalLayout_2 = QtWidgets.QVBoxLayout(self) self.verticalLayout = QtWidgets.QVBoxLayout() self.hori...
# -*- coding: utf-8 -*- # # command to create : # docker exec odoo12_odoo_1 /usr/bin/odoo scaffold product_next_coming /usr/lib/python3/dist-packages/odoo/aditional_addons # { 'name': "product_next_coming", 'summary': """ Show a column with the date of the next delivery of a product """, 'descr...
# a set is another way to group things. you can't have duplicates in a set, and it's in a random order. # my_set = {"banana", "blueberry"} # print(my_set) # add more items to our set # my_set.add("mango") # print(my_set) # add a duplicate to try. it didn't get added cause duplicate aren't allowed in a set # my_set....
""" http://blast.ncbi.nlm.nih.gov/blastcgihelp.shtml http://www.ncbi.nlm.nih.gov/toolkit/doc/book/ch_demo/?rendertype=table&id=ch_demo.T5#ch_demo.id1_fetch.html_ref_fasta """ from collections import OrderedDict import pandas as pd import pylab __all__ = ["FASTA", "MultiFASTA"] """ json file like in ensembl: mo...
"""Transformations in three dimensions - SE(3). See :doc:`transformations` for more information. """ from ._utils import ( check_transform, check_pq, check_screw_parameters, check_screw_axis, check_exponential_coordinates, check_screw_matrix, check_transform_log, check_dual_quaternion) from ._conversions i...
import io import re import os import tensorflow as tf import numpy as np from tensorflow.keras.preprocessing.text import Tokenizer from tensorflow.keras.preprocessing.sequence import pad_sequences def splitsentence(file_path): input = [] csv_reader = io.open(file_path, encoding='utf-8').read().strip()....
from math import isnan import matplotlib.pyplot as plt from mpl_toolkits import mplot3d import tkinter as tk class Goujon : def __init__(self,num): self.coordX = [] self.coordY = [] self.coordZ = [] self.nbContact = 0 self.liste_contact = [] self.contact_...
import os.path from SocketFunc import SocketClass closeSocket = False socket = SocketClass('localhost', 9000) def openFile(path): if os.path.isfile(path): return open(path, 'r').read() else: return "" while not closeSocket: while True: serverMsg = socket.receive(socket.socket) ...
from django.test import TestCase from django.utils import timezone from chat_wars_database.app.business_core.models import Item from chat_wars_database.app.guild_helper_bot.commands import _execute_deposit from chat_wars_database.app.guild_helper_bot.commands import _execute_report from chat_wars_database.app.guild_he...
import docker import os import time # Create a docker client: client = docker.from_env() services_autoscale = [] def log(str): print("LOG: " + str) def do_scale(service, number): os.system("docker service scale {}={}".format(service.attrs['Spec']['Name'], number)) def get_services_for_autoscaling(): for...
# -*- coding: utf-8 -*- """ Created on Thu Jul 25 18:26:43 2019 @author: Dell """ import tensorflow as tf import os model_dir = './' model_name = 'AfPredict.pb' def create_graph(): with tf.gfile.FastGFile(os.path.join(model_dir, model_name), 'rb') as f: graph_def = tf.GraphDef() graph_def.Pars...
from django.conf.urls import url from django.contrib import admin from . import views urlpatterns = [ url(r'^upload-result/', views.upload_result, name='upload_result'), ]
import time from base import Page from data import url from data.industry import INDUSTRY from data.users import NEW_USER_EMAIL as new_email from tools.postgresql import get_user_data from tools.mongodb import mongodb_insert_user from pages.sign_up.sign_up_page_locators import SignUpPageLocators from pages.sign_up.sign...
"""Classes and methods for parsing files""" from __future__ import print_function import logging from collections import namedtuple from itertools import izip_longest from fnmatch import fnmatch import gzip import bz2 import zipfile __all__ = ['Fasta', 'Fastq'] logger = logging.getLogger(__name__) def grouper(iterab...
from model.car import Car def ferrari_objectmother(name='Ferrari', model='365 California GT', country='italy', color='red'): return Car(name=name, model=model, country=country, color=color) def tesla_cars_objectmother(name='Tesla', model='Model S', country='EEUU', color='black'): return Car(name=name, model...
# 09 August 06:15AM-37:AM 22min # GFG # Logic 12min # Coding 10min def mergeSubarray(a, low, mid, high): left = a[low:mid+1] right = a[mid+1:high+1] i, j, k = 0, 0, low print(left) print(right) while i < len(left) and j < len(right): if l...
# Words 'n' Predicates # program parameters word_file = 'word-list.txt' # === Utility Functions (do NOT modify) === def get_word_list(): words = [] with open(word_file) as f: for line in f: line = line.strip().lower() words.append(line) # ensure our list of words are sor...
from rest_framework import serializers from data.models import DataContinent, DataCountry, DataCity class ContinentSerializer(serializers.ModelSerializer): # countries = serializers.StringRelatedField(many=True, read_only=True) # countries = serializers.RelatedField(many=True, read_only=True) class Meta:...
import random import bpy def clean_previews(): for img in bpy.data.images.values(): if img.name.startswith("Preview:"): img.use_fake_user = False bpy.data.images.remove(img) def render_preview(name): scene = bpy.data.scenes["Scene"] scene.render.filepath = f"/tmp/preview-...
from setuptools import setup def readme(): with open('README.rst') as f: return f.read() setup( name='lol_api', version='0.2.2', description='wrapper and utils for League of Legends API', long_description=readme(), url='https://github.com/gradam/lol_api', author='Jakub "Gradam" Se...
#!/usr/bin/python3 import argparse import os import ssg.build_ovals def main(): parser = argparse.ArgumentParser( description="Convert shorthand OVAL file to a valid full OVAL.") parser.add_argument("input", help="Input shorthand OVAL file") parser.add_argument("output", help="Output OVAL file")...
# Generated by Django 3.1.4 on 2021-01-28 16:02 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('employee', '0021_auto_20210129_0002'), ] operations = [ migrations.AlterField( model_name='appr...
'''최단 경로 알고리즘 ( 다익스트라, 플로이드 워셜, 벨만포드) 이 3가지 알고리즘으로 대표됨 ''' '''dijkstra 최단경로 알고리즘은, 그래프에서 여러 노드가 있을 때, 특정 노드에서 출발하여 다른 노드로 가는 각각의 최단 경로를 구해주는 알고리즘 (음의 간선이 없어야함) 다익스트라 알고리즘은 실제 GPS SW의 기본 알고리즘''' # 다익스트라는 Greedy Algorithm의 일종 ( 매번 가장 비용이 적은 노드를 선택 ) '''다익스트라 과정 1. 출발노드 설정 2. 최단 거리 테이블 초기화 ...
from pacman.actors.state import State from pacman.my_timer import ClockTimer # logger = logging.getLogger() # logging.debug("---------------------------------------------------------------------------------------------------------") # import traceback # for line in traceback.format_stack(): # print(line.strip())...
import cv2 import numpy as np cap = cv2.VideoCapture(0) while(cap.read()) : ref, frame = cap.read() roi = frame[:1080, 0: 1920] # roi = frame.copy() #convert color to gray gray = cv2.cvtColor(frame, cv2.COLOR_RGB2GRAY) # delete noise gray_blur = cv2.GaussianBlur(gray, (15,15), 0) #...
import collections import tensorflow as tf import tensorflow_federated as tff class TensorflowFederatedModel(tff.learning.Model): def __init__(self, params, dataset): self.params = params self.dataset = dataset self._variables = None @tf.function def forward_pass(sel...
''' More work from Udemy ''' # Calculating acceleration v =25 # Final velocity u = 0 # Initial velocity t = 10 # Time a = (v - u)/t # Calculate acceleration print a # Conditionals if a == 2: print "True" if not a == v: # Equivalent to != print "a /= v" if a != 15: print "derp" # <= , >=...
import xlrd from datetime import datetime,date # 文件路径 file_path = '1.xlsx' # 设置编码 xlrd.Book.encoding = 'utf8' # 获取数据 data = xlrd.open_workbook(file_path) # 获取所有的sheet sheet = data.sheet_names() for item in sheet: table = data.sheet_by_name(item) # print(item) # 取总行数 # print(table.nrows) # 取总列数 # print(table.nco...
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'consultarStock.ui' # # Created by: PyQt5 UI code generator 5.13.0 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtGui, QtWidgets class Ui_Form(object): def setupUi(self, Form): Form.setObj...
# -*- coding: utf-8 -*- ''' 程序配置文件 选择不同的环境参数指定不同的数据库 ''' import os import logging #获取当前文件的绝对路径 basedir = os.path.abspath(os.path.dirname(__file__)) #Development的数据库连接路径 deveuri = 'mysql+pymysql://root:123456@47.105.82.150:3306/beehive?charset=utf8' #redis数据库路径会被程序内basic库中redis引用 redis_url = {'url':'127.0.0.1...
from ScenarioHelper import * def main(): CreateScenaFile( "e4101.bin", # FileName "e4101", # MapName "e4101", # Location 0x0000, # MapIndex "ed7000", 0x00000000, # Flags ...
# Mengimpor library import pandas as pd import matplotlib.pyplot as plt import numpy as np # Mengimpor dataset dataset = pd.read_csv('D:\Mastering Machine Learning\Dataset\iklan_sosmed.csv') X = dataset.iloc[:,[2, 3]].values y = dataset.iloc[:,4].values # Membagi data ke dalam training dan test set from sklearn.model...
# -*- coding: utf-8 -*- ''' Local settings - Run in Debug mode - Use console backend for emails - Add Django Debug Toolbar - Add django-extensions as app ''' from .common import * # noqa # DEBUG # ------------------------------------------------------------------------------ DEBUG = env.bool('DJANGO_DEBUG', default...
from flask import Flask, jsonify, request from slack import WebClient from slack.errors import SlackApiError import os client = WebClient(token=os.environ['RT_SLACK_API_TOKEN']) app = Flask(__name__) @app.route('/slack', methods=["POST"]) def index(): release= request.json["versionProductName"] rel...
''' [medium] 存在一个长度为 n 的数组 arr ,其中 arr[i] = (2 * i) + 1 ( 0 <= i < n )。 一次操作中,你可以选出两个下标,记作 x 和 y ( 0 <= x, y < n )并使 arr[x] 减去 1 、arr[y] 加上 1 (即 arr[x] -=1 且 arr[y] += 1 )。最终的目标是使数组中的所有元素都 相等 。题目测试用例将会 保证 :在执行若干步操作后,数组中的所有元素最终可以全部相等。 给你一个整数 n,即数组的长度。请你返回使数组 arr 中所有元素相等所需的 最小操作数 。   来源:力扣(LeetCode) 链接:https://leetco...
from GETDATA.csv2triple import * from GETDATA.getbaike import * from GETDATA.getrawname import * from GETDATA.gettriple import * from includefile import *
import itertools import hashlib import os import time start = time.time() if os.path.exists("test.txt"): os.remove("test.txt") else: print("The file does not exist") f = open("test.txt", "a+") count = 0 #string = "abcdefgh" string = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ01234567...
import os, tempfile from seamless.highlevel import Context, Cell ctx = Context() ctx.mount(os.path.join(tempfile.gettempdir(), "transformer-compiled")) ctx.transform = lambda a,b: a + b ctx.transform.example.a = 0 ctx.transform.example.b = 0 ctx.result = ctx.transform ctx.result.celltype = "json" ctx.equilibrate() pr...
import shutil from pathlib import Path import hydra import matplotlib.pyplot as plt import numpy as np import torch from hydra.utils import to_absolute_path from omegaconf import OmegaConf from torch import nn, optim from torch.utils import data as data_utils from torch.utils.tensorboard import SummaryWriter from ttsl...
from django.test import TestCase from django.urls import reverse_lazy from django.test import TestCase from rest_framework.test import APIClient from rest_framework import status from rest_framework.authtoken.models import Token from rest_framework.test import APIRequestFactory import json import sys import tempfile ...
# -*- coding: utf-8 -*- """ Created on Mon Nov 25 20:33:08 2019 @author: kisch """ import unittest from NumberToWords import NumberToWords class TestNumberToWords(unittest.TestCase): def setUp(self): self.N_to_W = NumberToWords() def test_make_words(self): self.assertEqual(self.N...
#!-*-coding:utf-8-*- import sys import numpy as np import matplotlib.pyplot as plt from matplotlib.animation import ArtistAnimation def scatter( rho , n ): # 相関を持つ2つの乱数を生成し、それをxとyとする x = np.random.randn( n ) y = x * rho + np.sqrt(1-rho**2) * np.random.randn( n ) return x , y def identity( x ): re...
import sys from PyQt5.QtWidgets import QApplication, QMainWindow from interface.custom_widgets.central_widget import CentralWidget class MainWindow(QMainWindow): def __init__(self, parent=None): super().__init__(parent) self.init_ui() def init_ui(self): central_widget = CentralWidget...
from django.shortcuts import render, HttpResponse from django.template import RequestContext from django.contrib import messages from django.views.generic import View def receive_message(request): """接收消息""" # 获取消息 storage = messages.get_messages(request) for message in storage: print(message...
from tkinter import * from tkinter import messagebox as ms import sqlite3 from PIL import ImageTk,Image with sqlite3.connect('database1.db') as db: c = db.cursor() db.commit() db.close() class main: def __init__(self,master): self.master = master self.username = StringVar() ...
#!/usr/bin/env python """ Settings to use in Cramer-Rao calculations. Hazen 10/17 """ pixel_size = 100.0 psf_fft_z_range = 600.0 psf_fft_z_step = 100.0 spline_size = 30 spline_z_range = 750.0 test_z_range = 500.0 test_z_step = 50.0 x_size = 300 y_size = 200 zmn = [] #zmn = [[1.3, 2, 2]] #zmn = [[1.3, -1, 3], [1.3...
from binance.client import Client from binance.websockets import BinanceSocketManager from binance.enums import * from binance.exceptions import BinanceAPIException, BinanceRequestException, BinanceWithdrawException from time import gmtime, strftime from pynput import keyboard # Replace your_api_key, your_api_secret w...
# Напишите ваше решение speed = int(input('Скорость передачи данных: ')) coast = int(input('Стоимомть: ')) time = int(input('Врмя скачивания ')) a = speed * 1024 b = (time / a) * 1024 * 1024 * 1024 c = (b - (1024 * 3)) * coast print(b, c)
from __future__ import absolute_import from __future__ import division from __future__ import print_function import collections import hashlib import numbers import tensorflow as tf from tensorflow.python.eager import context from tensorflow.python.framework import constant_op from tensorflow.python.framewor...
import multiprocessing import threading import queue import sys import time import warnings from .Imaging import * from .MotorControl import * from .errors import * import numpy import cv2 from cvlib.object_detection import draw_bbox from PIL import Image, ImageTk class MotorisedCameraTracking: """The API for the...
#!/usr/bin/env python # -*- coding: utf-8 -*- #定义背景图像和鼠标图像名称 background_image_filename = "panzi.jpg" sprite_image_filename = "fish.png" screen_size = (640, 480) import pygame from pygame.locals import * from sys import exit #初始化pygame,为使用硬件做准备 pygame.init() #创建一个窗口 screen = pygame.display.set_mode(screen_size, 0, 3...
import torch from torch.autograd import Variable import itertools from util.image_pool import ImagePool from .base_model import BaseModel from . import networks class Pix2PixBraTS17MultipleOutputsModel(BaseModel): def name(self): return 'Pix2PixBraTS17MultipleOutputsModel' @staticmethod def modif...
from abc import ABCMeta, abstractmethod from model import util import numpy as np from scipy.ndimage import convolve from time import time class Convolute(metaclass = ABCMeta): def naive_convolution(self, matrix, kernel): """ A naive convolution which uses brute force loops. Very slow. :pa...
from django.contrib import admin from django.urls import path from .import views urlpatterns = [ path('admin/', admin.site.urls), path('',views.homepage), path('addbook',views.AddBook.as_view()), path('retrieveaddbook',views.retrieveAdddbook.as_view()), path('viewallbook',views.viewAllBook.as_view(...
from worldbankapp import app from wrangling_scripts.wrangling_simple import data_wrangling from wrangling_scripts.wrangling_multi import return_figures # Flask automatically looks for html files in the templates folder. from flask import render_template import plotly.graph_objs as go import plotly import json # Load a...
# -*- coding:ascii -*- from mako import runtime, filters, cache UNDEFINED = runtime.UNDEFINED __M_dict_builtin = dict __M_locals_builtin = locals _magic_number = 10 _modified_time = 1428426029.411011 _enable_loop = True _template_filename = 'C:\\Users\\John\\test_dmp\\homepage\\templates/login.loginform.html' _template...
from django.db import models from django.utils.translation import gettext as _ from django.utils.text import slugify import random import string from django.contrib.auth.models import User from datetime import datetime from io import BytesIO from PIL import Image from django.core.files import File from profiles.models...
# Write a program that prints the numbers from 1 to 100. # But for multiples of three print “Fizz” instead of the number # and for the multiples of five print “Buzz”. # For numbers which are multiples of both three and five print “FizzBuzz”. a = 0 for a in range(1, 101): if a % 3==0: print("Fizz") eli...
from ij import IJ from ij.plugin.frame import RoiManager from ij.gui import WaitForUserDialog imp = IJ.openImage("/Users/prakash/Desktop/BobSegDataAndResults/MAX_20180417_NMY-2_speed-test-01-05_MYOSIN_ALONE.tif"); imp.show() IJ.run("Set Scale...", "distance=0 known=0 pixel=1 unit=pixel"); WaitForUserDialog("","Mov...
from flask import Flask, jsonify, request, Blueprint from services.solicitacao_matricula_services import * from infra.to_dict import to_dict, to_dict_list from infra.validacao import validar_campos import sqlite3 solicitacao_matricula_app = Blueprint('solicitacao_matricula_app', __name__, template_folder='templates') ...
def odleglosc( x1, y1, x2, y2 ): a = ( x1 - x2 ) b = ( y1 - y2 ) return ( a**2 + b**2 ) ** 0.5 mieszkancy = [] sklepy = [] with open("mieszkancy.txt","r") as f: for linia in f: x, y = linia.strip().split(" ") x = int(x) y = int(y) mieszkancy.append( [x,y] ) with open("...
import click from data.services import RottenTomatoesSearcher from tables.builders import MovieSearchTableBuilder, TvShowSearchTableBuilder from tables.rows.builders import MovieSearchRowBuilder, TvShowSearchRowBuilder searcher = RottenTomatoesSearcher() movie_search_table_builder = MovieSearchTableBuilder(MovieSearc...
import os import sys import utils.utils as utils from entities.result import * from entities.operator import * class oracleOp(object): def __init__ (self, oid, name, time, percent, mem, obj): self.oid = oid self.name = name self.time = time self.percent = percent self.mem = mem self.obj = o...
import numpy as np import matplotlib.pyplot as plt import os import pandas as pd def sigmoid(scores): return 1 / (1 + np.exp(-scores)) def log_likelihood(features, target, weights): scores = np.dot(features, weights) ll = np.sum(target * scores - np.log(1 + np.exp(scores))) return ll def logistic_regre...
from django.shortcuts import render from django.http import HttpResponse from django.http import HttpResponseRedirect import requests import json from django.views.decorators.csrf import csrf_exempt # use this to assure login before accessing page from django.contrib.auth.decorators import login_required import datetim...
#Anna Wójcik import numpy as np from scipy.optimize import linprog macierz = np.array([[-2, 8, 2], [3, -1, 0]]) min = abs(macierz.min()) macierz = macierz + min a = [1,1] b = [-1,-1,-1] #gracz1 min_m = -macierz macierz1 = np.transpose(min_m) wartosci1 = linprog(a,macierz1,b) wartosc_gry1 = 1.0/np.sum(wartosci1.x) ...
import rospy import cv2 import math import time import numpy as np from scipy.linalg import expm from geometry_msgs.msg import Twist from sensor_msgs.msg import JointState from std_msgs.msg import Float64 from sensor_msgs.msg import LaserScan from sensor_msgs.msg import Image from cv_bridge import CvBridge import tf ...
# Generated by Django 2.0.2 on 2018-03-05 01:41 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('fact_flow', '0005_user'), ] operations = [ migrations.RemoveField( model_name='claim', name='end_index', ), ]
#!/usr/bin/env python3.5 from flask import Flask, render_template,request from execute import DEFAULT, hdmi app = Flask(__name__) #app.run(host='0.0.0.0', port='5002') #wsgi_app = app.wsgi_app @app.route('/', methods=['GET', 'POST']) def tv_status(): col = DEFAULT[1] default = DEFAULT[0] if request.metho...
#coding=utf-8 import bs4 import LoadDatInfo import sys import xmlAPI ''' Author: Junjie Li Analyze ICML and JMLR homepage 2016/04/11 ''' def get_author_list(author_bs): return author_bs.text.replace('\r','').replace('\n','').replace('\t','').split(',') def get_download_url(link_bs,homepage_url): ...
# coding: utf-8 # facial_expression_node.py import multiprocessing as mp import pathlib import os import time import tkinter as tk import PIL.Image import PIL.ImageTk from command_receiver_node import CommandReceiverNode class FacialExpressionNode(CommandReceiverNode): """ 顔の表情を画面に表示するクラス """ def _...
import os import sys from flask_wtf import FlaskForm from flask_wtf.file import FileField from wtforms import StringField, SubmitField, FloatField, IntegerField, TextAreaField, SelectField, PasswordField from wtforms.validators import DataRequired, Length, Email, InputRequired class TableForm(FlaskForm): table_...
'''*4.3 (Algebra: solve linear equations) You can use Cramer’s rule to solve the following system of linear equation: 2 * 2 2 * 2 ax + by = e cx + dy = f x = ed - bf ad - bc y = af - ec ad - bc Write a program that prompts the user to enter a, b, c, d, e, and f and display the result. If ad – bc is 0, report that T...
import numpy.random as nprnd from time import clock def r_step_generator(lo, hi): num = lo while True: num += nprnd.randint(0, 100) if num < hi: yield num else: raise StopIteration N = 10 ** 3 t1 = clock() u = range(0, (N // 100) * 99) x = nprnd.randin...
import networkx as nx import numpy as np from itertools import combinations import cvxopt from cvxopt import glpk,solvers import time from decimal import Decimal, ROUND_HALF_UP from fractions import Fraction #Given a graph G and prevPaths a list of all paths of a certain length l returns all paths of length l + 1 #Not...
""" HappyBase tests. """ import gc import random import logging import asyncio as aio from functools import partial from typing import AsyncGenerator, Tuple, List import pytest from thriftpy2.thrift import TException from aiohappybase import ( Table, Connection, ConnectionPool, NoConnectionsAvailabl...
from django.shortcuts import render # intro view: learn more, start now or go away from django.views.generic import DetailView class IntroTemplateView(DetailView): def get(self, request, *args, **kwargs): return render(request, 'index.html') def login(request): return render(request, 'login.html')
import numpy as np import matplotlib.pyplot as plt from scipy.signal import correlate2d from scipy.ndimage.measurements import label from Ferromagnet import * #Counting magnetic domains: def getBiggest(spins,updown): ups = (1+updown*spins)/2 kernel = np.array([[0,1,0],[1,0,1],[0,1,0]]) #Defines connectivity ...
# -*- coding: utf-8 -*- # Generated by Django 1.9.5 on 2016-04-28 13:53 from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('auth', '0007_alter_validato...
import aseegg as ag import numpy as np import pandas as pd import matplotlib.pyplot as plt import csv data = pd.read_csv('sub1trial8.csv', delimiter=',', engine='python') data.columns = ['-','kanal1', 'kanal2', 'kanal3', 'kanal4','cyfra' ] fs=200 dlugosc = data['-'] kanal1=data['kanal1'] #print(kanal1) t =...
"""python train2.py --tune=wdecay --wdecay_type=per_param --wdecay=1e-6 python train2.py --tune=wdecay --wdecay_type=per_param --wdecay=1e-6 --lr=1e-4 --hyper_lr=1e-3 """ import os import sys import csv import ipdb import time import math import hashlib import datetime import argparse # YAML setup from ruamel.yaml im...
python function 1)in-build function2)user defiend function #function is a block of code.when the function is call block of code will be executed.. ##different between parameter and arguments 1)we passing a parameter in the form of variable in a parentisis when the function is defiend 2)and when the function is call w...
import numpy as np import pandas as pd df=pd.DataFrame(np.arange(0,20).reshape(5,4), index=['row1','row2','row3','row4','row5'], columns=['1','2','3','4']) print(df.head()) df.to_csv('test1.csv')
class TransactionWeight(object): def __init__(self, name, weight): self.name = name self.weight = weight
dim = 8 sample_period = 10 # in milliseconds sample_period=sample_period*8 # # (*8) -> convert to samples ms dirname = 'data/random' #dirname = 'full_random_10' load_fname = dirname + '/primitives.npz' # class points toward 'data/' already, just need the rest of the path past = 100 past = 50 future = 10 v_ = 5 # dece...
from mindwavepy import Mindwave import mido from .utils import log, error, lerp, slide import time class App: def __init__(self, mindwave_dev, midi_dev): self.mindwave = self.connect_mindwave(mindwave_dev) self.midi_port = self.connect_midi_port(midi_dev) self.ASICs = [None, None] ...
TIME_ZONE_CHOICES = ( (None, "Select"), ("1.0", "A: Paris, +1:00"), ("2.0", "B: Athens, +2:00"), ("3.0", "C: Moscow, +3:00"), ("4.0", "D: Dubai, +4:00"), ("4.5", "-: Kabul, +4:30"), ("5.0", "E: Karachi, +5:00"), ("5.5", "-: New Delhi, +5:30"), ("5.75", "-: Kathmandu, :5:45"), ("6.0", "F: Dhaka, +6:0...
""" A way of notifying change to a number of classes eg in db replications and in distributed computing notifying about changes to nodes or vice versa Encapsulate the core (or common or engine) components in a Subject abstraction, and the variable (or optional or user interface) components in an Observer hierarchy. The...
emailAddress = input("Enter your email address?: ").strip() userName = emailAddress[:emailAddress.index("@")] domainAddress = emailAddress[emailAddress.index("@") + 1:] print("Your username is {} and your domain name is {}".format(userName, domainAddress))
import os, sys, inspect # realpath() will make your script run, even if you symlink it :) cmd_folder = os.path.realpath(os.path.abspath(os.path.split(inspect.getfile(inspect.currentframe()))[0])) if not(cmd_folder in sys.path): sys.path.insert(0, cmd_folder) # use this if you want to include modules from a subfol...
""" Copyright (c) 2021, Mattia Segu Licensed under the MIT License (see LICENSE for details) """ import torch import torch.nn as nn import torch.nn.parallel import torch.utils.data import torch.nn.functional as F class Identity(nn.Module): def __init__(self, *args, **kwargs): super(Identity, self).__init...
import os fpath = 'Resized_Images/train2014' files = os.listdir(fpath) for name in files: src = os.path.join(fpath, name) new = str(int(name[-16:-4])) + '.jpg' new = os.path.join(fpath, new) os.rename(src, new)
from rest_framework import pagination from rest_framework.response import Response from collections import OrderedDict class PaginationWithPageCount(pagination.PageNumberPagination): page_size_query_param = 'page_size' def get_paginated_response(self, data): return Response(OrderedDict(( ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4 # all the imports import os import json import sqlite3 from flask import Flask, request, session, g, redirect, url_for, abort, \ render_template, flash import urllib.request from flask_github import GitHub fro...
''' Created on Mar 9, 2018 This class override PyLDAvis builder to aggregate labels to the final visualization @author: wilson.penha ''' import jinja2 import json import numpy import os from pyLDAvis import urls from pyLDAvis._display import prepared_data_to_html, save_html from pyLDAvis._prepare import Prepa...
#! /usr/bin/env python3 # coding: utf-8 """Actions with Json files.""" import json class Json: """Functions to write and read the json file.""" def save_connection_params(self, host, user, password): """Add connection parameters to Json.""" conn_params = {"host": host, "user": user, "passwor...
# ========================================================================== # # Copyright NumFOCUS # # 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 # # https://www.apache.org...
import os def clear_screen(): clear_screen = lambda: os.system('cls') clear_screen() print('\n') print('\n') # **** End of function clear_screen() **** # def assign_banner_attributes(debug, *args): # assign string(s) passed in as args to string_list string_list = [] for...