text
stringlengths
8
6.05M
from django import template register = template.Library() @register.inclusion_tag('venues/venue_account_item.html', takes_context=True) def venue_account_item(context, venue_account): request = context['request'] return { 'request': request, 'venue_account': venue_account }
''' Author: Fanchen Bao Date: 01/14/2018 Description: A small program to examine how many numbers (natural and 0) of a certain number of digits are in pi, with the number of digits provided by the user. User is prompted to enter number of digits for the number to be examined. At the same time user is also prompted to...
from django.apps import AppConfig from django.utils.translation import ugettext_lazy as _ class EstatesConfig(AppConfig): name = 'estates' verbose_name = _('estates')
"""Advent of Code Day 20 - Infinite Elves and Infinite Houses""" def find_factors(number): """Returns the prime factorisation of a number.""" factors = set() for i in range(1, int(number**0.5) + 1): if number % i == 0: factors.add(i) factors.add(number // i) return...
AUTHENTICATION_ENDPOINT = '/InvestaApi/User/AuthenticateUser' STOCK_TRANSACTION_BY_STOCK_ID = '/InvestaApi/Stock/GetStockTransactionByStockIdAndDate' STOCK_ID = '/InvestaApi/Stock/SearchStockSnippet' BROKER_ID = '/InvestaApi/Stock/SearchBrokerSnippet' STOCK_TRANSACTION_BY_BROKER_ID = '/InvestaApi/Stock/GetStockTransact...
class Solution: def minDistance(self, word1: str, word2: str) -> int: i = len(word1) + 1 j = len(word2) + 1 dp = [[0] * j for b in range(i)] # 初始化完毕 for x in range(i): for y in range(j): if x == 0: dp[x][y] = y ...
#!/usr/bin/env python import sys import getopt from sklearn import datasets from hard_coded_classifier import HardCodedClassifier from random import shuffle def make_verify_fn(classsifier): """A function that makes a function that we can classify things with""" def verify(data_answer): # pull the da...
total = 0 while True: numero = int(input('Digite um número -> ')) if numero != 0: total += numero else: break print('\33[32mTotal = {}'.format(total), end='')
# 튜플은 값의 삭제, 수정이 불가능하다. a = (1,2,3) print(a,type(a)) b = (4,5) print(b,type(b)) c = a + b c = c + (6,) print(c)
x=input() print(x)
import torch from torch import nn import numpy as np import torch.nn.functional as F from utils import * from .Base import BaseNet class TextCNN(BaseNet): def __init__(self, config, vocab_size, word_embeddings): super().__init__(config) self.config = config #embedding layer self.em...
import bpy import bmesh from math import * APLITUDE = 10 obj = bpy.context.active_object bm = bmesh.from_edit_mesh(obj.data) for v in bm.verts: x, y, z = v.co v.co[2] = sin(v.co[0]) * APLITUDE bmesh.update_edit_mesh(bpy.context.active_object.data)
# https: // www.hackerrank.com/challenges/sparse-arrays/problem # Complete the matchingStrings function below. def matchingStrings(strings, queries): result = [] for value in queries: count = 0 for item in strings: if value == item: count = count + 1 result....
import struct import hashlib import binascii from M2Crypto import BIO, EVP, SMIME, X509, m2 FOOTER_SIZE = 6 EOCD_HEADER_SIZE = 22 def verify_file(path): with open(path, 'rb') as ota_file: ota_file.seek(0, 2) length = ota_file.tell() ota_file.seek(-FOOTER_SIZE, 2) footer = bytearray...
from .cifar100 import *
# Write a program that maps a list of words into a list of integers representing the lengths of the correponding # words. Write it in three different ways: 1) using a for loop, 2) using the higher order function map(), and 3) # using list comprehensions. # 1) using for loop def word_map(): list1 = [] list2 = ...
# the python code here is to generate the test suite for testing the approximation of NST(G_i) / NST(G_{i-1}) # each json file in the testsuite indicates the number of vertices and the density # each json file contains a list [g1, NST(g1), g2, NST(g2), (u, v)] # where g1 is a graph, and g2 is g1 with the edge (u,v) rem...
# defines function "main" def main(): # calls function "calcappend" calcappend() # defines function "calcappend" def calcappend(): # prompts user for integer input times = int(input("How many numbers do you want to use? ")) # created an empty list resultlist = [] # loops as much times as the...
import os import sys os.chdir('/home/peitian_zhang/Codes/News-Recommendation') sys.path.append('/home/peitian_zhang/Codes/News-Recommendation') import torch from utils.utils import evaluate,train,prepare,load_hparams,test from models.KNRM import KNRMModel if __name__ == "__main__": hparams = { 'name':...
from django.contrib import admin from django.conf import settings from django.conf.urls import patterns, url from django.views.generic import TemplateView from haystack.views import SearchView from haystack.query import SearchQuerySet from .views import (AuthorList, AuthorDetail, ArticleDetail, Arti...
# coding: utf-8 # imports import Game as Game # variables # functions def Main(): """ Code start """ Game.Start() Game.Run() # code starts here if __name__ == "__main__": Main()
import cv2 # ---------------------text on image---------------- img = cv2.imread('C:\\fakepath\\hackathon.png', 1) # params: # - image obj # - text to put # - tuple starting point of text (x2,y2) # - font face variable # - font size # - tuple color in bgr (b,g,r) # - thickness in int (-1 will fill th...
# Generated by Django 2.1 on 2018-10-23 06:39 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('home', '0002_auto_20181023_0633'), ] operations = [ migrations.AddField( model_name='dailyinput', name='dummy', ...
# @Title: 高度检查器 (Height Checker) # @Author: 2464512446@qq.com # @Date: 2019-09-06 17:20:04 # @Runtime: 28 ms # @Memory: 11.4 MB class Solution(object): def heightChecker(self, heights): """ :type heights: List[int] :rtype: int """ return sum(h1!=h2 for h1,h2 in zip(heights,...
from image_search.db import DB import colorsys import math def list_add(l1, l2): return [a1 + a2 for (a1, a2) in zip(l1, l2)] def cosine_sim(l1, l2): dot = sum([a1 * a2 for (a1, a2) in zip(l1, l2)]) norm1 = math.sqrt(sum([a * a for a in l1])) norm2 = math.sqrt(sum([a * a for a in l2])) return d...
# This script takes everything under each "digit" # and combines it onto one line ####################### #Structure of the data # 1 # line # textone # texttwo # 2 # textthree # linetwo # 3 # somethingone # somethingtwo ####################### from sys import argv file = argv[1] data = open(file).readlines() for n, ...
import time import logging from pathlib import Path import xmltodict from Bio import Entrez import pandas as pd from tqdm import tqdm # Set up logging logger = logging.getLogger(__name__) logger.setLevel(logging.INFO) handler = logging.FileHandler("pmc_api_pull.log") formatter = logging.Formatter("%(asctime)s - %(nam...
#!/usr/bin/env python # Flip bit at position N def flip_bit(number, n): mask = (0b1 << n-1) result = mask ^ number return bin(result) # Check if bit is ON or OFF def check_bit4(input_bit): mask = 0b1000 desired = input_bit & mask if desired > 0: return 'on' else: return '...
import os import pickle import numpy as np import vegans.utils.loading.architectures as architectures from vegans.utils.loading.DatasetLoader import DatasetLoader, DatasetMetaData class MNISTLoader(DatasetLoader): def __init__(self, root=None): self.path_data = "mnist_data.pickle" self.path_targ...
import unittest import pandas as pd import os import itertools from selenium import webdriver from selenium.webdriver.chrome.options import Options from selenium.webdriver.common.by import By class ExcelReader(unittest.TestCase): @classmethod def setUpClass(cls): cls.driver = webdriver.Chrome(executa...
# Generated by Django 2.2.4 on 2019-08-15 18:43 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('base', '0006_pypartner'), ] operations = [ migrations.AlterField( model_name='pypartner', name='city', f...
from utils import win_state_llist from utils import lose_state_llist from game_board.llist.llist import doAction from game_board.llist.llist import makeNewGame from django.test import TestCase class TestWinLose(TestCase): def testWin(self): startergraph = makeNewGame() starterboard = {'graph': st...
from core import control import bge keyboard = bge.logic.keyboard JUST_ACTIVATED = bge.logic.KX_INPUT_JUST_ACTIVATED ACTIVE = bge.logic.KX_SENSOR_ACTIVE WHEEL_SPEED = 1023 class User(control.Controller): def update(self): left_wheel = 0 right_wheel = 0 if keyboard.events[bge.eve...
from Stack import Stack expr = input(); print(expr) stack = Stack() for l in expr: if l == '(': print("Opening") stack.push("(") elif l == ')': print("Closing") if stack.pop() != '(': print("Not Balanced") exit(0) if stack.isEmpty(): print("Balanced") else: print("Unbalanced")
from django import template from django.utils.safestring import mark_safe from apps.quiz.models import * register = template.Library() @register.inclusion_tag(filename='quiz/question_nav.html', name='question_nav') def question_nav(user, quiz, current_question): """ Тег выводит элемент навигации по...
''' torchvision.transforms.CenterCrop(size)[SOURCE] Crops the given PIL Image at the center. Parameters size (sequence or int) – Desired output size of the crop. If size is an int instead of sequence like (h, w), a square crop (size, size) is made. '''
#!/usr/bin/env python3 #coding: utf-8 def fact(n): if n == 1: return 1 return n*fact(n-1) print (fact(10))
#coding=utf-8 from django import forms from django.utils.translation import ugettext_lazy as _ from models import VIPUser #class VipUserForm(forms.ModelForm): # class Meta: # model = VIPUser # fields = ('email','is_vip', 'expire')
import os import fnmatch import platform import threading import ast import copy import msvcDemangler import merge_subs import subprocess # TODO list: # vtable dumper needs to include as much info as possible about each function # UPDATE THE IDA FUNCTION TO INCLUDE RTTI: THIS WILL INCLUDE THE CLASS HIERARCHY ...
# # str:Unicode # #bytes:十六进制 # # s = 'hello 猪八戒' # print(type(s)) # <class 'str'> Unicode # # # # str 》》》》》bytes:编码 # # 方式1 # b = bytes(s, 'utf8') # print(b) # 将str变为十六进制的数 b'hello \xe7\x8c\xaa\xe5\x85\xab\xe6\x88\x92' utf8规则下的bytes类型 # # 方式二 # # b2 = s.encode('utf8') # 编码 # # print(b2) # # # gbk编码下的bytes数据 # ...
import logging import time from dotenv import load_dotenv from hardware.camera.drivers import CameraDriver, PiCameraDriver from hardware.trash_detector import TrashDetector from prediction.prediction import Prediction, LocalPrediction from presentation.led_panel import LedPanel from storage.datastore import DataStore...
import pygame import time from src.engineSettings import * from src.gameObject import GameObject from src.character import Character pygame.init() win = pygame.display.set_mode((0, 0), pygame.FULLSCREEN) pygame.display.set_caption("game") prevTime = time.time() run = True character = Character(YELLOW, 'assets/sprite...
from django.shortcuts import render from rest_framework.views import APIView from . models import * from rest_framework.response import Response from . serializer import * from django.core.mail import send_mail from django.conf import settings # Create your views here. class ReactView(APIView): serializer_class = R...
import numpy as np from scipy import sparse from pynndescent import NNDescent from sknetwork.hierarchy import Paris from sknetwork.hierarchy.postprocess import cut_straight from tqdm import tqdm class ParisClusterer(object): def __init__(self, featureMatrix): self.featureMatrix = featureMatrix def bu...
def some_func(arg1, arg2, *args, kv_arg1=1, kv_arg2=2, **kwargs): print(arg1, arg2, end=" ") print("kv_arg1=", kv_arg1, " kv_arg2=", kv_arg2, sep="") for arg in args: print(arg, end=" ") print() for key, val in kwargs.items(): print(key, "=", val, end=" ", sep="") print() some_...
# 과제 및 실습 # LSTM # 전처리 , Early_stopping 등등 다 넣을 것!! # 데이터 1 ~ 100 # x y # 1,2,3,4,5 6 # . . . # 99,96,97,98,99 100 # 1. 데이터 import numpy as np x = np.array(range(1,101)) size = 6 def split_x(a,size): return np.array([a[i:(i+size)] for i in [i for i in range(len(x)-size+1)]]) ...
# The Experiments package controls visual stimulation and analyzes recorded data. # # Copyright (C) 2010-2012 Huang Xin # # See LICENSE.TXT that came with this file.
#replace string to strng s='this is a string...ex...this is a string' print s.replace('is','was') print s.replace('is','was',3) print s.replace(' is ',' was ')
#-*- coding:utf8 -*- import json import time from django.db import models from shopback.base.models import BaseModel from shopback.base.fields import BigIntegerAutoField,BigIntegerForeignKey from shopback.users.models import User from shopback.items.models import Item from shopback import paramconfig as pcfg from shopb...
# -*- coding: utf-8 -*- """ Created on Sat Nov 2 11:22:33 2019 @author: Jp """ import csv import torch import torch.nn as nn import pandas as pd import numpy as np #get data data = csv.reader("tempAMAL_train.csv") data = pd.read_csv("tempAMAL_train.csv",engine='python') data = data.drop('datetime',a...
from django.db import models from django.db.models.base import ModelStateFieldsCacheDescriptor # Create your models here. class Newuser(models.Model): Username = models.CharField(max_length=150) Email = models.CharField(max_length=150) pwd = models.CharField(max_length=150) Age = models.IntegerField() ...
#!/usr/bin/python import json import os import sys import datetime import subprocess import platform import argparse import socket import importlib import hashlib import re import shlex try: raw_input # Python 2 PYTHON3 = False except NameError: # Python 3 raw_input = input PYTHON3 = True if PYT...
import sys import SimEngine from Printer import logPrint class TRAE(object): def __new__(cls, mote): settings = SimEngine.SimSettings.SimSettings() if mote.id in [0,1,2,3]: class_name = 'TRAE{0}'.format(settings.trae) else: class_name = 'TRAEBase' retur...
class Ref: @staticmethod def none(): r = Ref() r.__is_none = True return r def __init__(self): self.__is_none = False self.val = None def __call__(self, val=None): if self.__is_none: return if val is None: r...
""" 优雅写法 1 order_type = 'special_gift' if item.sku_kind == SKUKind.SKU_KIND_PACKAGE else 'gift' 2 "100" if config.fee_payer == "zhihu" else "0" 3 result = [val for val in DEMO_SKU_CONFIG if val.sku_id == str(sku_id)] return result[0] if result else None 4 sum([val.real_amount for val in items]) 5 params = d...
# Although Python does not need an emtry point, # it is quite common in Python programs to create a function called main() and # to call it to start off processing. # Since no function can be called before it has been created, # we must make sure we call main() after the function it relies on # have be defined. # The...
import numpy as np import scipy.stats as ss #Black and Scholes def d1(S0, K, r, sigma, T): return (np.log(S0/K) + (r + sigma**2 / 2) * T)/(sigma * np.sqrt(T)) def d2(S0, K, r, sigma, T): return (np.log(S0 / K) + (r - sigma**2 / 2) * T) / (sigma * np.sqrt(T)) def blsprice(type,S0, K, r, sigma, T): if typ...
''' https://leetcode.com/problems/friend-circles/description/ 深度优先遍历在处理这种链接问题简直太容易,核心就是 将所有节点遍历一遍,条件是如果该节点没有在seen集合中出现过, 然后遍历的时候如果找到1的话,就继续搜索,加入seen,直到结束,就把所有能加入的加入了 Runtime: 82 ms Your runtime beats 35.54 % of python submissions. ''' class Solution(object): def findCircleNum(self, M): """ :ty...
import math import scipy.stats import streamlit as st sigma1=st.number_input("Enter Sigma_1 Value")#50 sigma2=st.number_input("Enter Sigma_2 Value")#60 x1_bar=st.number_input("Enter x1_bar Value")#123.2 n1=st.number_input("Enter n1 Value")#58 n2=st.number_input("Enter n2 Value")#48 x2_bar=st.number_input("E...
# --------------------------------------------------------------- # Lists - part 1 # ------ # A python list is used to store several bits of data # in one place under a single variable name. # It is a very useful think to have when you have hundreds, thousands # or millions of bits of data. Imagine writing a million di...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # author: cg错过 # time : 2018-04-24 from monitorbin.util.mysqlConnect import DoMysql from monitorbin.util.sysTime import RunTime class CountPicNum: # 统计'动态','食谱'这两项当天上传的图片数量 # 此项为每天只检测一次 # 打算在这里将存放sql语句的文件写死 strGetFoodPicNumSql = "sql/get-foodPicNum.sq...
class Solution: def maxVowels(self, s: str, k: int) -> int: max_cnt = 0 vowels = set(['a', 'e', 'i', 'o', 'u']) c = 0 for i in range(k): # print(1, i, s[i]) if s[i] in vowels: c += 1 if c > max_cnt: # print("Initial max: ",...
# -*- coding: utf-8 -*- # Generated by Django 1.10.7 on 2018-01-23 10:20 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('nova', '0072_delete_api'), ] operations = [ migrations.CreateModel( ...
from django.contrib import admin from .mo # Register your models here.
import webbrowser import sys import subprocess try: keyword = sys.argv[1] except IndexError: exit() url = dict() # Add your links here # url['keyword'] = 'URL' url['goo'] = 'https://www.google.com' url['fb'] = 'https://www.facebook.com' url['duck'] = 'https://duckduckgo.com' url['bing'] = 'https://...
""" Utilities for finding the newest file and waiting for it to finish. """ import os import time def get_newest_file(path): """ Find the newest file in the path. There should be a more direct way to find the new download, but I'm not sure how. """ return max( (os.path.join(path, f) for f i...
from scipy.misc import imread, imresize, imsave import numpy as np def preprocess_class(str): if (str == "mnactec"): return 0 elif (str =="mercat_independencia"): return 1 elif (str =="ajuntament"): return 2 elif (str =="societat_general"): return 3 elif (str =="estacio_nord"): return 4 elif (str =="do...
import numpy as np import cv2 import pickle from sklearn.svm import LinearSVC from sklearn.preprocessing import StandardScaler from moviepy.editor import VideoFileClip from Windows import Windows from svm import train from search import * color_space = 'RGB' orient = 30 pix_per_cell = 16 cell_per_block = 2 hog_c...
# The Vision Egg: Dots # # Copyright (C) 2001-2003 Andrew Straw. # Copyright (C) 2005,2008 California Institute of Technology # # URL: <http://www.visionegg.org/> # # Distributed under the terms of the GNU Lesser General Public License # (LGPL). See LICENSE.TXT that came with this file. """ Random dot stimuli. """ #...
import pickle from sklearn.manifold import TSNE tsne = TSNE(n_components=2, random_state=0) import matplotlib as mpl mpl.use('Agg') import matplotlib.pyplot as plt features = pickle.load(open('features','rb')) labels = pickle.load(open('labels0','rb')) colors = 'r', 'g', 'b', 'c', 'm', 'y', 'k', 'w', 'orange', 'purple'...
import numpy as np import operator from sklearn.cluster import KMeans from sklearn.metrics.pairwise import cosine_similarity from sklearn.metrics import pairwise_distances_argmin_min def print_list(arr): """ Helper function :param arr: A list :return: None """ for item in arr: print(it...
""" Selection Sort """ def find_smallest(arr): smallest = arr[0] smallest_index = 0 for i in range(1, len(arr)): if arr[i] < smallest: smallest = arr[i] smallest_index = i return smallest_index def selection_sort(arr): new_arr = [] for i in range(len(a...
import numpy as np import matplotlib.pyplot as plt from sklearn.preprocessing import normalize import pandas as pd from LogisticRegression import LogisticRegression df = pd.read_csv('data.csv') data = df.to_numpy() # Normalise First 3 Columns X = data[:, 0:-2] X = normalize(X, axis=0) X = np.hstack((X, data[:, 3:-1])...
from flask import Blueprint, jsonify, request from app.education.service import get_teen_pregnancy_by_education education_controller = Blueprint('education', __name__) @education_controller.route('/') def birth_rate_usa_per_year_and_education(): year = request.args.get('year', 1995, int) data = get_teen_pre...
from base64 import b64encode from flask_testing import TestCase from .util import create_empty_flask_app from .test_views import ViewTestCase from ..admin import _init_basic_auth as init_basic_auth class AdminTestCase(ViewTestCase): BASE_APP_CONFIG = ViewTestCase.BASE_APP_CONFIG.copy() BASE_APP_CONFIG['ADMI...
# Generated by Django 3.1.3 on 2020-11-09 04:05 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('words', '0002_auto_20201109_0057'), ] operations = [ migrations.CreateModel( name='Category', fields=[ ...
# -*- coding:utf-8 -*- import sqlalchemy metadata = sqlalchemy.MetaData()
class People: def __init__(self, name, age, say): self.name = name self.say = say self.age = age def hello(self): print(str(self.age) + "岁的" + self.name + "说:", self.say) @staticmethod def tool_max(arg_list): return max(arg_list) wzr = People("卓然", 18, "早安!打工人...
number = int(input('Digite o número: ')) counter = 0 for n in range(1, number + 1): if number % n == 0: counter = counter + 1 if counter == 2: print('É primo') else: print('Não é primo')
class Calculator(): def __init__(self): pass def add(self, val1, val2): try: return val1 + val2 except: raise ValueError("Not int") def subtract(self, val1, val2): val1 = self._checker(val1) val2 = self._checker(val2) if val1 and...
N, M = map( int, input().split()) V = [ [] for _ in range(N)] for _ in range(M): a, b = map( int, input().split()) V[a-1].append(b-1) V[b-1].append(a-1) for i in range(N): print( len(V[i]))
import random # Biblioteca Built In do Python para geração de números aleatórios from prettytable import PrettyTable # Biblioteca Third-Party para formatação de tabelas letra1 = ['q', 'w', 'x', 'z'] # Primeiro vetor de possíveis letras letra2 = ['a', 'i', 'u'] # Segundo vetor de possíveis letras letra3 = ['...
#!env python3 # -*- coding: utf-8 -*- from xmlrpc.server import SimpleXMLRPCServer from datetime import datetime def time(): return(datetime.now()) server = SimpleXMLRPCServer(("localhost", 6789)) server.register_function(time, "time") server.serve_forever()
number = 23 guess = int(input('Enter integer number: ')) if guess == number: print('Congratulation you! That\'s right') print('But you don\'t get any price!') elif guess < number: print('Yor\'r number bigger!') else: print('You\'r number smaller!') print('Finish')
from tridy import Kralicek, Stenatko kralicek1=Kralicek("Karel Marx") kralicek1.zanufej() kralicek1.snez("seno") kralicek1.prejmenuj("pani Karla Marxova") stenatko1=Stenatko("Amalka") stenatko1.zastekej() stenatko1.snez("parek") print(stenatko1.vaha) stenatko1.vaha=30 print(stenatko1.vaha) print(kralicek1.vaha) #po...
import re import threading import time from concurrent.futures import ThreadPoolExecutor import schedule from dotmap import DotMap import commands as cm from access import accessControl import log # Remember to only use single threaded, as we are using global variable for telegram chat_id executor = ThreadPoolExecut...
import africastalking from django.conf import settings from django.contrib import messages from django.contrib.auth.decorators import login_required from django.shortcuts import render, redirect, get_object_or_404 from django.utils.decorators import method_decorator from django.views import View from exams.models impor...
import string def encrypt_message(message, fname): ''' Given `message`, which is a lowercase string without any punctuation, and `fname` which is the name of a text file source for the codebook, generate a sequence of 2-tuples that represents the `(line number, word number)` of each word in the mes...
#!/usr/bin/env python # -*- coding: utf-8 -*- # ˅ # ˄ class Display(object): # ˅ # ˄ def __init__(self, impl): self.__impl = impl # ˅ pass # ˄ def output(self): # ˅ self.open() self.write() self.close() # ˄ def open(sel...
from solvent import config from solvent import run from solvent import label from upseto import gitwrapper import logging import os class Approve: def __init__(self, product, ignoreFailureOnLocalObjectStore=False): self._product = product self._ignoreFailureOnLocalObjectStore = ignoreFailureOnLoca...
import speech_recognition as sr # obtain path to "english.wav" in the same folder as this script import os, glob from os import path #set the folder to be the input os.chdir("E:\\PythonGarbage\\Speechrecog\wavs") directory = os.getcwd() # Make the output file. totalfiles = len(glob.glob("*.wav")) counter = 1...
# https://www.learndatasci.com/tutorials/python-pandas-tutorial-complete-introduction-for-beginners/ from datetime import date import datetime import pandas as pd import re df = pd.read_csv("csv/csv_file_name") # paste your csv in folder named csv #print(df.head()) # TO PRINT FIRST 5 ROWS OF THE DATAFRAME #...
#!/usr/bin/env python """ create_mf_snap.py Created by Mikolaj Szydlarski on 2014-04-29. Copyright (c) 2018, ITA UiO - All rights reserved. """ import numpy as np import pylab as plt import matplotlib.colors as colors from mpl_toolkits.axes_grid1 import make_axes_locatable plt.rcParams['figure.figsize'] = (10, 10) p...
import cv2, numpy as np import torch.nn as nn def rgb2dataset(rgb_data): gray_data = cv2.cvtColor(rgb_data, cv2.COLOR_BGR2GRAY) resized = cv2.resize(gray_data, (84, 84)) downsampled = resized / 255.0 return np.array(downsampled) def initialize(m): if type(m) == nn.Linear: nn.init.kaiming_u...
import pytest import os import sqlite3 import shutil import numpy as np import pandas as pd from sqlalchemy import and_ from ticclat.ticclat_schema import Wordform, Lexicon, Anahash, \ WordformLinkSource, MorphologicalParadigm from ticclat.utils import read_json_lines, read_ticcl_variants_file from ticclat.dbuti...
""" 西门子服务器对应的web端界面封装 """ import os from time import sleep from utils.settings import * from selenium import webdriver from selenium.webdriver.support.select import Select class Simens(object): def __init__(self, url=url, user=username, password=password): self.url = url self.user = user ...
from setuptools import setup setup( name="btcmarkets", packages=["btcmarkets"], version="0.0.2", description="Python wrapper for the BTCMarkets API", author="Bradley McElroy", author_email="bradley.mcelroy@live.com", url="https://github.com/limx0/btcmarkets", install_requires=['request...
# given: string abc # print: # a a # b # c c n = str(input("enter string:")) print(len(n)) index=0 for i in range(len(n)): for j in range(len(n)): if i==j or i+j+1==len(n): print(n[index],end=" ") else: print(" ",end=" ") print() index+=1
#Career Quiz #KW '23 #This asks the person's name and stores it so I am resuse it when I tell them their results print("Hello! Welcome to the Career Aptitude Test!") name = input("Enter your name: ") print("Hi " + name + "!") print("I hope you have a fun time doing this quiz (:") print("If the game breaks it's proba...
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright 2013 fgsoap # All Rights Reserved. # In Python 2.7.5 try: import requests, time from pyquery import PyQuery as pq except ImportError: print "Please make sure the Requests and the PyQuery are installed!" # Please change the ...