text
stringlengths
8
6.05M
import unittest from PIL import Image import function.check_picture as f_checkPicture import function.cut as f_cut import function.eight as f_eight x = {} x['0.png'] = '0.png' x['1.png'] = '1.png' x['2.png'] = '2.png' x['3.png'] = '3.png' x['4.png'] = '4.png' x['5.png'] = '5.png' x['00.png'] = '00.png' #此处代码与上面大同小异,...
from datasets.pku import load_data import argparse from models.BaselineModel import MyUNet from models.AttentionModel import AttentionUnet import torch from utils.trainer import * from torch import optim from torch.optim import lr_scheduler import pandas as pd def TrainModel(args): print("Training model") dat...
from PIL import Image, ImageFilter img = Image.open('./Pokedex/pikachu.jpg') filtered_img = img.convert('L') filtered_img.save("grey.png", 'png') box = (100,100,400,400) region = filtered_img filtered_img.resize((300,300)).show()
# To add a new cell, type '# %%' # To add a new markdown cell, type '# %% [markdown]' import datetime import math import pathlib import time from typing import * import matplotlib import matplotlib.pyplot as plt import mplfinance as mpf import pandas as pd import plotext.plot as plx from finta import TA import log fr...
import numpy as np import pandas as pd import matplotlib.pyplot as plt # %matplotlib inline from sklearn.linear_model import LinearRegression from sklearn.model_selection import train_test_split from sklearn.metrics import confusion_matrix,r2_score, mean_squared_error x= np.random.randn(10000) # y = np.power(np.sin(x)...
#!/usr/bin/env python ## This script visualizes tha robots position in a map ## It reads values published by the logger #import rospy #from std_msgs.msg import String import matplotlib.pyplot as plt data = [ [0,0,0,0,0,1,1,1,1,0], [0,0,0,0,0,1,0,0,1,0], [0,0,1,0,1,0,1,1,0,0], [0,0,1,0,0,1,1,0,1,0], ...
# Generated by Django 2.2.10 on 2021-04-05 13:03 from django.conf import settings from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('polls', '0002_auto_20210405_1728'), ] operation...
# Generated by Django 2.2.1 on 2019-05-17 19:56 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('moods', '0002_mood_created'), ] operations = [ migrations.AddField( model_name='mood', name='streak', fi...
# Copyright (c) Amber Brown, 2015 # See LICENSE for details. import os try: import configparser except ImportError: import ConfigParser as configparser def load_config(from_dir): config = configparser.ConfigParser( { 'package_dir': '.', 'filename': 'NEWS.rst' } ...
#!/usr/bin/python # -*- coding: utf-8 -*- # @author: caramel def homework2(): dictionary = {'abandon':'to give up to the control or influence of another person or agent', 'abase':'to lower in rank, office, prestige, or esteem', 'abash':'to destroy the self-possession or self-confidence of' } who =...
import logging from PyQt5 import QtCore, QtWidgets, QtGui from switch_case import switch import os import time import threading __author__ = 'Галлям' logger = logging.getLogger(__name__) class FileItem: def __init__(self, file_path: str, is_dir: bool, parent=None, size: int=0, ...
#! /usr/bin/env python3 import maya.cmds as cmds cmds.select(d=True ) cmds.joint(p=(38.994835, 108.019676, 230.40213) ) cmds.select('joint1', r=True ) cmds.joint(p=(39.094835, 108.019676, 230.40213) ) cmds.select('joint2', r=True ) cmds.joint(p=(46.165903, 100.94860800000001, 230.40213) ) cmds.select('joint3', r=Tr...
#!/usr/bin/env python # -*- coding: utf-8 -*- import handin6 test1 = handin6.fasta_to_list("test1.fasta") test2 = handin6.fasta_to_list("test2.fasta") test1.sort() test2.sort() print test1 print test2 for item1 in test1: if not handin6.binary_search(test2, item1): print item1
import unittest,time from HTMLTestRunner import HTMLTestRunner test_dir = "E:/python/test_web/test_case" discover = unittest.defaultTestLoader.discover(test_dir,pattern="test_*.py") if __name__ == "__main__": now = time.strftime("%Y-%m-%d %H-%M-%S") filename = "E:/python/test_web/report" + "/" + now + " res...
#from TaskSet import * class EDFVD: def __init__(self, ts): self.ts = ts def test(self): res = self.ts.getUtilisationOfLevelAtLevel(1,1) if self.ts.getUtilisationOfLevelAtLevel(2,2) < 1: res += min(self.ts.getUtilisationOfLevelAtLevel(2,2), self.ts.getUtilisationOfLevelAtLe...
from game.items import * from game.models import * from game.player import Player from game.gamemanager import * p = Player() p.inventory.add_item(IronHatchet) p.inventory.add_item(TinderBox) p.equip_item(IronHatchet) chop_tree(CommonTree(), p) chop_tree(CommonTree(), p) chop_tree(CommonTree(), p) burn_logs(NormalLo...
from django.db import models from products.models import SizeChart from django.contrib.auth.models import User class Order(models.Model): token = models.CharField(max_length=250, blank=True) user = models.ForeignKey(User, blank=True, null=True, on_delete=models.CASCADE) total = models.DecimalField(max_digi...
#!/usr/bin/python import sys import random from random import randint from random import uniform import time objects = ["People","Platform","RR","GG","YY","RG","RY","GY","SpeedSign","SpeedRegulator"] numObjects = 9 epochTime = 0 lastValue = True while lastValue == True: randNum = randint(0,numObjects) if int...
import numpy as np import time start = time.time() x_train = np.load('./dacon3/data/x_train_merge_1.npy') for i in range(1,10): a = np.load('./dacon3/data/x_train_merge_{}.npy'.format(i+1)) print(a.shape) x_train = np.append(x_train, a, axis=0) print(x_train.shape) x_train = x_train.reshape(50000, 256, 2...
''' ''' SLACK_EVENT = 'event_callback' SLACK_ACTION = 'action_callback' SLACK_COMMAND = 'command_callback' handlers = { SLACK_EVENT: lambda c,i: logging.info(f'E {i}'), SLACK_ACTION: lambda c,i: logging.info(f'A {i}'), SLACK_COMMAND: lambda c,i: logging.info(f'C {i}'),}
# Copyright 2019 The ASReview Authors. All Rights Reserved. # # 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 applicabl...
from function_interface import * # Load Data print("Load Data") allTaskByID = load_data_from_csv('../data/transcribe-2017-07-08.CSV') print("Get group with ID 2048") group = allTaskByID[2048][0] print("Get good transcriptions") good_transcriptions = get_good_transcriptions(group) print("Align group") aligned_graph ...
import arcpy import os pdf_path = input('Where would you like to save the pdf documents? ' )or 'W:\\Research&Development\\Data-Share\\analysis-fin\\TitleVI\\TitleVI\\MR\\' aprx_loc= input('Where is the arcgis pro projecct? ') or r'W:\Research&Development\Data-Share\analysis-dev\TitleVI\MetroReimagined_190917\MR_Ti...
import re import time # import os # print(os.path.abspath(os.path.dirname(__file__))) from Scripts.fastapp.common.regex_config import RegexConfigs from Scripts.fastapp.common.consts import REGEX_FOLDER_PATH class regexDictionaryManager(RegexConfigs): def __init__(self): super().__init__() # new r...
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys import nysol.util.margs as margs import nysol.take as nt args=margs.Margs(sys.argv,"ei=,ef=,ni=,nf=,-all,o=,l=,u=,log=,-rp","ei=,ef=") nt.mclique(**(args.kvmap())).run(msg="on")
""" Code de téléchargement de fichier grib de données de prévision provenant d'ECCC """ import requests import shutil import os.path import datetime import pathlib # example : http://dd.meteo.gc.ca/model_gem_regional/coupled/gulf_st-lawrence/grib2/00/001/CMC_coupled-rdps-stlawrence-ocean_latlon0.02x0.03_2019010300_P...
class Challenger: def __init__(self, name, money): self.name = name self.money = money def getName(self): return self.name def __str__(self): return self.name def getBalance(self): return self.money def deductMoney(self, amount): self.money -= amo...
import attr import matplotlib.pyplot as plt import numpy as np from simulation.module import Module, ModuleState from simulation.state import State MAX_ARRAY_LENGTH = 1000 @attr.s(kw_only=True) class PlotState(ModuleState): step_num: int = attr.ib(default=0) fungal_burdens: np.ndarray = attr.ib(factory=lamb...
import torch.nn as nn from torch import functional class ValueHead(nn.Module): def __init__(self, num_channels, input_size): super(ValueHead, self).__init__() NUM_INTERMIDATE_CHANNELS = 1 self.conv = nn.Conv2d(num_channels, NUM_INTERMIDATE_CHANNELS, kernel_size=1) self.bn = nn.Ba...
# coding: utf-8 import numpy as np from random import shuffle from gensim.models import KeyedVectors from gensim.models import Word2Vec class Corpus(object): def __init__(self, min_length=0, tokenizer=' ', preprocessor=None): self.size = 0 self.min_length = min_length self.tokenizer = token...
class Solution: def characterReplacement(self, s, k): """ :type s: str :type k: int :rtype: int """ if len(s) == 0: return 0 elif len(s) < k: return len(s) store = {} for j in range(len(s)): store[s[j]] = st...
from dataclasses import dataclass import numpy as np import pandas as pd @dataclass(frozen=True) class Candidate: matrix: np.array df: pd.DataFrame # info-theoretic values hxy: float hyx: float ami: float # result of svd s1p: float # proportion of variance explained by s1
from django.conf.urls import patterns, url from datasf import views urlpatterns = patterns('', url(r'^home/$', views.home , name='home'), url(r'^get_datasf_movies/$', views.get_datasf_movies , name='get_datasf_movies'), )
"""This program will figuring out the other luggage weight by given input""" def weightadjusts(): """The function will adjust the average weight first, results in calculatable number""" average_kg = float(input()) * 2 luggage_kg = float(input()) print(average_kg - luggage_kg) weightadjusts()
import mxnet as mx from mxnet.gluon.data import Dataset,DataLoader from mxnet.image import imread from PIL import Image import os import numpy as np import cv2 import math from mxnet import nd import mxnet.gluon.data.vision.transforms as T default_transform = T.Compose(T.ToTensor(),T.Normalize(mean=(),std=(...
from .api_model import APIModel class Rule(APIModel): name: str score: int notes: list[str] | None
from whitelisting.git import Git try: from unittest.mock import patch except ImportError: from mock import patch @patch('subprocess.call') def test_git_called_with_correct_values(mock_call): mock_call.return_value = 999 assert Git("test 1 2 3") == 999 mock_call.assert_called_with(['git', 'test', ...
exp = {'2007 - 2009': 'Entel', '2009 - 2014': 'GMD', '2014 - 2020': 'Toyota'} alumnos = {'10210902': 'Jose', '102109005': 'Marcos'} print(alumnos['102109005'])
# Generated by Django 2.2.1 on 2019-06-07 06:46 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] ope...
from tkinter import * import FC4, FC5, BC, LIC, CA, TR, decimal class FC4Menu: def __init__(self,master): frame = Frame(master) self.question = Label(frame, text="What is the number?") self.entry = Entry(frame, justify=CENTER) self.entry.bind("<Return>",self.calc) self.butto...
from django.contrib.auth.forms import UserChangeForm, UserCreationForm from .models import User class CustomUserRegisterForm(UserCreationForm): class Meta: model = User fields = ['username', 'password1', 'password2'] def save(self, commit=True): user = super(CustomUserRegisterForm, se...
import SimpleITK as sitk import numpy as np import os from .CoordsConverter import CoordsConverter from .Scan import Scan from .PatientInfoProvider import PatientInfoProvider class ScansReader(object): def __init__(self, dir: str, patient_info_provider: PatientInfoProvider): self.dir = dir self.pa...
from normalize import normalize import matplotlib.pyplot as plt from open_csv import open_csv from kalman import Kalman from locals import geodetic_to_enu, enu_to_geodetic import numpy as np from random import uniform origin_lat, origin_lon = 54.386279, 18.590767 park = open_csv("./gps_data_park.csv") init_x, init_y...
import json import pathlib import uuid from collections import OrderedDict from sqlalchemy import Column as SQLColumn, String, Integer, ForeignKey, Table from sqlalchemy import create_engine, func from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import relationship, scoped_session, sessionmak...
from django.urls import path from . import views urlpatterns = [ # path('', views.index, name='index'), path('face/', views.face, name='face'), path('face/upload', views.detect, name='detect'), path('', views.upload, name='upload'), path('display/', views.display, name='display'), ]
import numpy as np import matplotlib.pyplot as plt import torch from torch.autograd import Variable w_target = np.array([0.5, 3, 2.4]) b_target = np.array([0.9]) f = 'y = {:.2f} + {:.2f}*X + {:.2f}*X^2 +{:.2f}*X^3'.format( b_target[0], w_target[0], w_target[1], w_target[2]) print(f) x_sample = np.arange(-3, 3.1, ...
import sphere_module print("Enter the radius :") radius= int(input()) print ("Area is :" + str(sphere_module.area(radius)))
p = {'apple':4,'banana':9,'orange':20,'pineapple':15} for i,j in p.items(): #items are pairs print(i,j) print(p['apple'],p['orange'])
"""add comment in script explaining what its for This is where the scripts to preprocess the data go save files in data/targets/ """ import itertools import json from pathlib import Path from zipfile import ZipFile import numpy as np import pandas as pd import requests from autumn.models.covid_19.constants import COVI...
k = float(input("Input degrees k")) c = k - 273.15 print("Degrees celsius", round( c, 2))
import pygame class Camera(): def __init__(self, width, height, x = 0, y = 0): self.rect = pygame.Rect(x, y, width, height) def update(self, player): scale_x = 32 * 5 scale_y_up = 32 * 5 scale_y_down = 32 * 2 # Player moving right? if (self.rect.right...
""" https://github.com/ageron/handson-ml/blob/master/ """ import matplotlib.pyplot as plt import numpy as np def plot_svc_decision_boundary(svm_clf, xmin, xmax): w = svm_clf.coef_[0] b = svm_clf.intercept_[0] # At the decision boundary, w0*x0 + w1*x1 + b = 0 # => x1 = -w0/w1 * x0 - b/w1 x0 = n...
#!/usr/bin/python3 def remove_char_at(str, n): """ Copy a string and remove a character at n """ return str[:n] + str[(len(str) + n) % len(str) + 1:]
# Generated by Django 2.2 on 2019-04-17 07:54 from django.db import migrations, models import django.db.models.deletion import django.utils.timezone class Migration(migrations.Migration): dependencies = [ ('onlclass', '0029_auto_20190417_1005'), ] operations = [ migrations.CreateModel( ...
""" Global settings for the entire project. """ # Training parameters EPOCHS = 100 LEARNING_RATE = 1e-5 SHUFFLE = True STATE_SAVE_PATH = 'states/semantic_similarity.pt' # Testing parameters THRESHOLD = 0.95 OUTPUT_SAVE_PATH = 'analysis/output.csv' # Glove file path GLOVE_PATH = 'glove/glove.6B.50d.txt'
# Copyright (c) 2011, James Hanlon, All rights reserved # This software is freely distributable under a derivative of the # University of Illinois/NCSA Open Source License posted in # LICENSE.txt and at <http://github.xcore.com/> import math import sys import ast from util import debug from walker import NodeWalker f...
#!/usr/bin/env python import urllib2 import optparse try: import json except ImportError: import simplejson as json UNKNOWN = -1 OK = 0 WARNING = 1 CRITICAL = 2 API_URL = 'https://www.googleapis.com/pagespeedonline/v1/runPagespeed?url=%s&key=%s' API_KEY = '' HOSTNAME = '' WARNING_SCORE = 0 CRITICAL_SCORE = ...
import sys import random import math def pi(n): count = 0 for i in range(n): x = random.random() y = random.random() if x * x + y * y < 1: count += 1 return count * 4 / n print("n:", sys.argv[1]) print("円周率:", pi(int(sys.argv[1]))) print("誤差率:", abs(pi(int(sys.argv[1])) - math.pi) / math.pi ...
import gym import numpy as np import matplotlib import matplotlib.pyplot as plt import matplotlib.ticker as ticker import random import datetime import pandas as pd import os # sigmoid - def sigmoid(x): return 1 / (1 + np.exp(-x)) class NeuralNetwork: # init - Creates 3 weights made from random values betwee...
# Hardcoded plotting for appendix, # which is basically same as in main paper # but over all environments etc. # import os from glob import glob import itertools import re import numpy as np import matplotlib from matplotlib import pyplot from plot_paper import interpolate_and_average, color_linestyle_cycle # Stacko...
import pyglet window = pyglet.window.Window() def zpracuj_text(text): print(text) def tik(t): print(t) #spousti se 30x ya vterinu, pyglet.clock.schedule_interval(tik, 1/30) window.push_handlers(on_text=zpracuj_text) pyglet.app.run() print('Hotovo!')
#Design a HashSet without using any built-in hash table libraries. #To be specific, your design should include these functions: #add(value): Insert a value into the HashSet. #contains(value) : Return whether the value exists in the HashSet or not. #remove(value): Remove a value in the HashSet. If the value does not ...
import cv2 import numpy as np import matplotlib.pyplot as plt def go(path): img = cv2.imread(path) r = 500.0/img.shape[1] dim = (500, int(img.shape[0]*r)) resized = cv2.resize(img, dim, interpolation=cv2.INTER_AREA) gray = cv2.cvtColor(resized,cv2.COLOR_BGR2GRAY) corner = cv2.goodFeaturesToTrac...
#!/usr/bin/env python import sys import numpy as np # linear algebra import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv) import matplotlib as matpl matpl.use('Agg') import matplotlib.pyplot as plt import matplotlib.cm from mpl_toolkits.basemap import Basemap from matplotlib.patches import Polygon f...
#!/usr/bin/env python import threading as th import logging, time import multiprocessing from kafka import KafkaConsumer, KafkaProducer class Producer(th.Thread): # Derives from Threading def __init__(self): th.Thread.__init__(self) self.stop_event = th.Event () # Create event def stop (self)...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ empty.py Purpose: ... Version: 1 First start Date: 2017/**/** @author: pms590 """ ########################################################### ### Imports import numpy as np import pandas as pd import matplotlib.pyplot as plt # import scipy.optimiz...
# -*- coding: utf-8 -*- from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import codecs import pickle import numpy as np from keras.models import load_model from bert4keras.layers import custom_objects from bert4keras.utils import Tokenizer from ..d...
import time print("a") time.sleep(2) print("b")
#!/usr/bin/env python #FUNCTIONS NECESSARY BECAUSE OF DIFFERERENCES IN DISTANCE LENGTH #function to return the distance from a line def grab_distance(line): end_str = "" for ch in line: if ch != ',': end_str += ch elif ch == ',': return end_str #function to return the S...
import math import pylab as pl class harmonic: def __init__(self, w_0 = 0, theta_01=0.2,theta_02=0.2+0.001, time_of_duration = 400, time_step = 0.04,g=9.8,length=9.8,q=1/2,F=1.2,D=2/3): self.n_uranium_A1 = [w_0] self.n_uranium_B1= [theta_01] self.n_uranium_A2 = [w_0] self.n_uranium_B...
import subprocess import io import random def test(cmds, ans): inData = "{n}\n{cmds}\n".format(n=len(cmds), cmds='\n'.join(cmds)) result = subprocess.run("G.exe", input=inData.encode(), stdout=subprocess.PIPE) return result.returncode == 0 and list(map(int, result.stdout.decode().split('\r\n')[:-1])) == a...
#!/usr/bin/python3 from DFS import DFS def isAlreadyVisited(n, cc): for c in cc: if n in c: return True else: return False def connectedComponent(g): nodes = g.keys() cc = [] for n in nodes: if not isAlreadyVisited(n, cc): c = DFS(n, g) cc.append(c) return cc def testConnectedComponent(): ...
import pandas as pd import seaborn as sns import matplotlib.pyplot as plt import numpy as np import os def rmsd_box(df): name = [] for i, row in df.iterrows(): if str(row.rescor_func) == "nan": name.append(row.dock_func) else: name.append(f"{row.dock_func}_...
# Generated by Django 2.0.7 on 2019-01-01 16:52 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('basedata', '0012_auto_20180829_0506'), ] operations = [ migrations.AddField( model_name='device_change', name='chang...
import os import csv import pickle from shutil import copyfile import operator import sys filepaths = ['../../annotations_landmarks/annotation_clean_train.txt','../../annotations_landmarks/annotation_clean_val.txt'] datapaths = ['../../annotations_landmarks_clean_train_crop/','../../annotations_landmarks_clean_validat...
# -*- coding: utf-8 -*- { 'name' : 'Econube Double Currency', 'version' : '1.1', 'category': 'Purchase Management', 'depends' : ['base', 'purchase'], 'author' : 'Econube | José Pinto, Pablo Cabezas', 'description': """ Double currency for purchases. =================================== This mo...
import pygame class AbstractBullet: def __init__(self, x, y): self.speed = 8 # px per frame self.radius = 2 # px self.damage = 8 self.cords = { 'x': x, 'y': y } self.direction = { 'x_cof': 0, 'y_cof': -...
# # House Price Prediction # # This is a simple prediction of house prices based on house size # Implemented in TensorFlow # import tensorflow as tf import numpy as np import math from matplotlib import pyplot as plt import matplotlib.animation as animation # import animation support tf.compat.v1.d...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ __module__的官方定义: `The name of the module the function was defined in, or None if unavailable. <https://docs.python.org/3.3/reference/datamodel.html#the-standard-type-hierarchy>`_。 中文解释: 类/函数 定义所在的模块。 只有 ``function``, ``class`` 对象有这个属性。被实例化的对象是没有这个属性的。 """ import dat...
print ("Questão 1") peso = float(input("Digite seu peso:")) altura = float(input("Digite sua altura:")) imc = (peso/altura**2) if imc < 18.5: print("Você está abaixo do peso!") elif imc >= 18.5 and imc < 25: print("Você está com o peso normal!") elif imc > 25: print("Você está acima do peso!") e...
class Binning: def __init__(self, c, r_ip1, N, N_bins, lags, store_frame_rate=1, uniform_bins = True, min_count = 0, verbose = True): #number of conditional variables N_c = c.shape[1] self.N_c = N_c self.N = N self.r_ip1 = r_ip1 self.c = c ...
import face_recognition import picamera import numpy as np import os import time from datetime import datetime from datetime import date from servo_control import Servo """ Created by Ethan Lyon for ELEC574. Rice University Spring 2020 This script uses the RPi's camera and the facial recognition library to recognize t...
list = [] amount = int(input()) for i in range (1,amount+1): num = int(input()) list.append(num) print(min(list)) print(max(list))
import boto3 import base64 from botocore.exceptions import ClientError import json import pymysql as db import logging import csv from io import StringIO import os logger = logging.getLogger() logger.setLevel(logging.DEBUG) logging.basicConfig(level=logging.DEBUG) # logger.debug(f"Event: {event}") def insert_into(i...
import cronjobs import time from django.db import transaction from yoolotto.settings import AFTER_LOGON_OX, email, password, domain, realm, consumer_key, consumer_secret import urllib2 import json from yoolotto.second_chance.models import AdInventory as InventoryModel, Advertisor as AdvertisorModel @cronjobs.register ...
# -*- coding: utf-8 -*- ''' Created on May 01 2020 @author: kanehekili ''' import sys import re import os from PyQt5 import QtGui,QtWidgets,QtCore from PyQt5.QtWidgets import QApplication, QErrorMessage from PyQt5.Qt import QMainWindow, QSizePolicy, QFont class MediaInfoView(QMainWindow): def __init__(self,f...
import hashlib from typing import Optional from flask import Request from flask import Response from pypi_org.infrastructure.num_convert import try_int auth_cookie_name = 'pypi_demo_user' def set_auth(response: Response, user_id: int): hash_val = __hash_text(str(user_id)) val = "{}:{}".format(user_id, hash...
from flask import Blueprint, jsonify, request from flask import abort videos_bp = Blueprint('videos', __name__) @videos_bp.route('/videos/', methods=['GET', 'PUT']) def lista_videos(): from main import mongo from models.video import Video if request.method == 'PUT': data = request.get_json() ...
import re def prepare_dictionary(path): with open(path) as file: dictionary = {} for line in file.readlines(): words = re.split('[\s,]+', line) if 'NOUN' in words and 'nomn' in words and 'sing' in words: word = words[0].lower() word_set = set...
t = int(input()) for _ in range(t): a,b = input().split() l = min(len(a),len(b)) m = max(len(a),len(b)) for i in range(l): print(a[i],b[i],sep='',end='') if m==len(a): print(a[l:],sep='',end='') else: print(b[l:],sep='',end='') print()
""" #------------------------------------------------------------------------------ # Properly scaled experimental values for a PoleZero Shaper # # This script contains generalized phase and amplitude shifting values for an undamped second order system # # Created: 6/20/17 - Daniel Newman -- dmn3669@louisiana.edu # # ...
#!/usr/bin/python #coding:utf-8 lalphalist = [] halphalist = [] string='' for i in range(26): string += chr(i+97) lalphalist = list(string) halphalist = list(string.upper()) # print lalphalist # print string # print halphalist def cesarencode(text,offset): ''' 凯撒密码: 参数: text:明文 ...
#!/usr/bin/python3 str = "Holberton School" print("\n".join((str * 3, str[:9])))
def genPrimes(): primes = [] x = 2 while True: candidate = True for p in primes: if x % p == 0: candidate = False prime = True if True == candidate: for i in range(2, x/2): if x % i == 0: prime = Fals...
from numpy.core.fromnumeric import shape from silence_tensorflow import silence_tensorflow silence_tensorflow() import tensorflow as tf import pathlib import numpy as np import cv2 def get_input_to_network(img, input_dim=320): img = cv2.resize(img, (input_dim, input_dim), interpolation = cv2.INTER_CUBIC) img...
#!/usr/bin/env python """ _PYDCCPImpl_ Implementation of StageOutImpl interface for DCCP With PyDCAP bindings available """ import os from WMCore.Storage.Registry import registerStageOutImpl from WMCore.Storage.StageOutImpl import StageOutImpl from WMCore.Storage.StageOutError import StageOutError _CheckExitCodeOpti...
""" 1א """ import numpy as np from numpy import random as rn import matplotlib.pyplot as plt S0=1 k=S0 r=0.02 T=1 N=100 h=T/N M=10000 dw=np.sqrt(h)*rn.randn(M,N) s=np.linspace(0,5,50) B=0.8*S0 y=[] z=[] Y=[] for x in s: S=S0*np.ones((M,N+1)) for i in range(0,N): S[:,i+1]=S[:,i]*...
import argparse import itertools from operator import itemgetter from typing import Dict, List, Tuple import networkx as nx import numpy as np def one_of_k_encoding(x: int, allowable_set: List) -> List: if x not in allowable_set: raise Exception("input {0} not in allowable set{1}:".format(x, allowable_se...
import re import numpy as np import scipy.spatial inFile = open('neur/1/sentences.txt') outFile = open('neur/1/outFile.txt', 'w') spisok = [] myDict = {} for line in inFile: stroka = re.split('[^a-z]', line.lower()) while '' in stroka: stroka.remove('') spisok.append(stroka) index = 0 for i in spis...
# Generated by Django 3.1.5 on 2021-01-28 08:29 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('klubok', '0001_initial'), ] operations = [ migrations.AlterField( model_name='place', name='type', field...