text
stringlengths
38
1.54M
from django.shortcuts import render, get_object_or_404, redirect from disks.models import Album, Artist, Track from django.http import Http404 # Create your views here. def home(request, album_id=1): if ("titre" in request.GET): titre = request.GET['titre'] albums = Album.objects.using('chinook').f...
from random import sample def random_numbers(scope,num = 10): if type(scope) != int and type(num) != int: return "Input must be Integers" if num <= 0 or scope <= 0: return "Input must bigger than 0" elif scope < num: return "Scope must bigger than the randonly genera...
from sqlalchemy import MetaData from sqlalchemy import Table, Column from sqlalchemy import Integer, String from sqlalchemy import ForeignKey def get_meta(): metadata = MetaData() node_table = Table('node', metadata, Column('id', Integer, primary_key=True), Colum...
# -*- coding: utf-8 -*- """Main module.""" import math class Vector: """A basic class that enables vector calculations. """ def __init__(self, identifier, value): """ Init method for Vector. Args: identifier: (mixed) This can be any value. Not used, can hold identi...
import threading from crawl import my_craw import os import json class MyThread(threading.Thread): def __init__(self, threadID, name, type, url): super(MyThread, self).__init__() self.threadID = threadID self.name = name self.type = type self.url = url def run(self): ...
# write clear when using as params for @abi_entry_point and @abi_method ByteArray = 'ByteArray' Integer = 'Integer' Boolean = 'Boolean' String = 'String' Array = 'Array' Struct = 'Struct' Map = 'Map' Interface = 'Interface' Any = 'Any' Void = 'Void' types = { 'ByteArray': 'ByteArray', 'Integer': 'Integer', ...
# Generated by Django 2.0 on 2018-01-05 01:47 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Pic', fields=[ ('id', models.AutoField(auto_c...
import time from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.webdriver import ActionChains import requests import json jsonPath = 'credentials.json' jo = open(jsonPath, 'r') r_credentials = jo.read() credentials = json.loads(r_credentials) email = credentials['email'] pas...
import os import json import nltk import sys import cchardet import tensorflow as tf import numpy as np import pandas as pd from tensorflow.python.layers import core as core_layers from sklearn.cross_validation import train_test_split from LSTM_model import model # read data from json file and text file d...
# -*- coding: utf-8 -*- from __future__ import division from django.contrib.auth.decorators import login_required from django.shortcuts import render from django.http import HttpResponse from django.http import HttpResponseRedirect from django.db.models import Count from cmdb.models import * import json from django.vi...
from django.http import HttpResponse from django.template import Context from django.template.loader import render_to_string, get_template from django.core.mail import EmailMessage def email_one(request): subject = "I am a text email" to = ['buddy@buddylindsey.com'] from_email = 'test@example.com' ctx...
#!/usr/bin/python3 import sys import rospy import dlib import cv2 import numpy as np import tf2_geometry_msgs import tf2_ros from sensor_msgs.msg import Image from geometry_msgs.msg import PointStamped, Vector3, Pose from cv_bridge import CvBridge, CvBridgeError import message_filters from face_detector.msg import ...
from datetime import tzinfo, timedelta, datetime import pytz from plugins.bender.paxes import PAXES from plugins.bender.pax import Pax def next_pax(paxes=None): """Return the next Pax""" if not paxes: paxes = _all_paxes() paxes = _sort_paxes(paxes) for pax in paxes: if pax.date < datetime.utcnow().rep...
def is_bouncy(n): inc, dec, s = False, False, str(n) for i in range(len(s)-1): if s[i+1] > s[i]: inc = True elif s[i+1] < s[i]: dec = True if inc and dec: return True return False def binomial(n, k): """ Calculate C(n,k), the number of ways can k be chosen from n. Example: >>>binomia...
# Import scrapy library import scrapy # Create the spider class class YourSpider( scrapy.Spider ): name = "your_spider" # start_requests method def start_requests( self ): urls = ["https://www.datacamp.com" , "https://scrapy.org"] for url in urls: yield url # parse method def parse( self, respo...
import jinja2 # should be assigned to prod, not dev/tests from dummy import script01 import pyquery # dev-bound
import unittest from binary_tree_longest_consecutive_sequence import Solution, TreeNode class TestSolution(unittest.TestCase): def test_Calculate_Solution(self): sol = Solution() root = TreeNode(1) node3 = TreeNode(3) node2 = TreeNode(2) node4 = TreeNode(4) node5 = ...
import os import sys from gcintsinlib import are_tools_existed from gcintsinlib import get_list_from_current_tsin32 from gcintsinlib import get_list_from_remote from gcintsinlib import write_back_merged_tsin from gcintsinlib import USER_TSIN32 def pull_and_merge( remote_filename ): """ Merge the tsin32.txt in ...
import os print('======================') print() def main(): print('=== Operaciones adicionales sobre archivos ===\n') print('=== Renombrar archivos ===\n') nombre_archivo = '014_Manipulacion_de_Archivos/mi_nuevo_archivo.txt' if os.path.isfile(nombre_archivo): print(f'El archi...
from datetime import date from django import template from django.conf import settings import re from ctdata.models import BlogPage, EventPage, Page register = template.Library() # settings value @register.assignment_tag def get_google_maps_key(): return getattr(settings, 'GOOGLE_MAPS_KEY', "") @register.assi...
#!/usr/bin/python # -*- coding:UTF-8 -*- import numpy as np import re import jieba import json import itertools from collections import Counter def init(): f = open('law.txt', 'r', encoding = 'utf8') law = {} lawname = {} line = f.readline() while line: lawname[len(law)] = line.strip() law[line.strip()] = len...
""" Tests for the NURBS-Python package Released under The MIT License. See LICENSE file for details. Copyright (c) 2018 Onur Rauf Bingol Tests geomdl.linalg module. Requires "pytest" to run. """ import pytest from geomdl import linalg GEOMDL_DELTA = 10e-6 def test_linspace(): start = 5 stop...
#encoding='utf-8' import requests import lxml.html from lxml import etree import codecs import re import sys print sys.stdout.encoding sys.stdout = codecs.getwriter('UTF-8')(sys.stdout) def get_novelid(): pat=re.compile('novelid=(.+?)&chapterid') a=list() #file=open('4.txt')#old file with...
from django.views.generic import ListView,DetailView,CreateView from django.views.generic.edit import UpdateView from django.urls import reverse_lazy from .models import StudentFeePayment class StudentFeePaymentCreateView(CreateView): model = StudentFeePayment fields = ("student", "learning_year", "learning_s...
""" *Condicional if resultado = 50 # resultado = resultado > 10 if resultado > 10 and resultado <20: print('La varialbe cumple con la condiciòn.') else: print(f'error la condición no se cumplió: {resultado}')""" """ * Condiciola elif calificacion = 5 if calificacion == 10: print('Felicidades, aprobaste...
from django.conf.urls import patterns, include, url from django.contrib import admin from whatever import views admin.autodiscover() urlpatterns = patterns('', url(r'^admin/', include(admin.site.urls)), url(r'^$', 'whatever.views.whatever'), url(r'^add/$', 'whatever.views.add'), )
from selenium import webdriver import time def getPwd(): with open ('d:\\pw.txt') as f: pw = f.readline() return pw.strip() url = 'https://logins.daum.net/accounts/signinform.do?url=https%3A%2F%2Fwww.daum.net%2F' driver = webdriver.PhantomJS('data\\phantomjs.exe') driver.get(url) time.sleep(1) idbox ...
from data_manager import data_manager as data from display_in_console import show from novation_launchpad_mini import show_on_launchpad as lights def game(): # INTRO lights.reset_board() show.language = data.ask_language_version() n = 'cxfdks728%@&*^^' while n == 'cxfdks728%@&*^^': n = sho...
from django.db import models class Event(models.Model): name = models.CharField(max_length=20) picture = models.ImageField() address = models.CharField(max_length=100) postcode = models.CharField(max_length=10) link = models.URLField(max_length=100) schedule = models.DateTimeField()
""" Algorithm used to generate a data set to train and test with. """ import random import numpy as np class DataSetGenerator(): def __init__(self, start, end, number_of_points, ratio): """ Instantiation of generator object. :param start: smallest possible value for data point <int...
import logging import pickle from model_pools.model_utils.copy_mechanism import copy_mechanism_preprocess class SummarizeKQProcessor(object): def __init__(self, config=None): self.config = config def get_train_examples(self, data_dir, train_file): """Gets a collection of `Inp...
import matplotlib.pyplot as plt import sys from matplotlib.patches import Rectangle objects = [] with open("assignment", "r") as file: matrix_size = float(file.readline()) for line in file: objects.append(line.rstrip().split(",")) plt.axis([0, matrix_size, 0, matrix_size]) ax = plt.gca() for object i...
def factorial(num: int) -> int: if num <= 1: return 1 return num * factorial(num - 1) N = int(input()) if 0 <= N and N <= 12: print(factorial(N))
from odoo import models, fields, api class QRCodeWizard(models.TransientModel): _name = 'qr.code.wizard' qr_code = fields.Many2one('qr.code', string="QR code", required=True) res_reference = fields.Reference(selection='_select_target_model', string="Source Document") @api.model def _select_target...
from __future__ import (absolute_import, division) __metaclass__ = type from ansible.errors import AnsibleError from ansible.plugins.lookup import LookupBase from ansible.utils.listify import listify_lookup_plugin_terms from lxml import etree # https://gist.github.com/andyjsharp/501f79e8c56577d07fa77f040939714e#file...
""" Sub-package containing breadth first routines """ from aizynthfinder.search.breadth_first.search_tree import SearchTree
from sklearn.metrics import mean_absolute_error from sklearn.metrics import mean_squared_error from sklearn.metrics import mean_squared_log_error from sklearn.metrics import median_absolute_error import feature_transformation as ft import math import pandas as pd # A customer rolling k-fold implementation, which is ca...
# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! """Client and server classes corresponding to protobuf-defined services.""" import grpc import common_pb2 as common__pb2 import master_to_worker_pb2 as master__to__worker__pb2 class MasterToWorkerStub(object): """Missing associated documentati...
f = open("word.txt",'r').read() print f x = open("word.txt",'w').write("hiii") print x s = open("string.txt").readline() print s
""" openapi: 3.0.3 info: title: Python Cookbook Chapter 12, recipe 2. description: Parsing the query string in a request version: "1.0" servers: - url: "http://127.0.0.1:5000/dealer" paths: /hands: get: parameters: - name: cards in: query style: form explode: true ...
import zmq import sys import PySimpleGUI as sg import time sg.theme('LightBlue') balance_size = (20, 1) balance_frame = [ [ sg.Text('Shares', size=balance_size), sg.Text('Cash', size=balance_size) ], [ sg.Text("Please start server", key='shares', size=balance_size, background_color...
# # Standardization/Normalization # Mean = 0, Std_dev = 1 # from sklearn import preprocessing.StandardScaler names = df.columns # Create the Scaler object scaler = StandardScaler() # Fit your data on the scaler object scaled_df = scaler.fit_transform(df) scaled_df = pd.DataFrame(scaled_df, columns=names) # # Maximu...
import operator import re f = open("input.txt", "r") records = [] for l in f.readlines(): records.append(l.strip().split("] ", 1)) records.sort(key=lambda i: i[0]) cur_guard = 0 guard_counts = {} sleep_time = 0 for r in records: m = re.match("Guard #(\d+)|(falls asleep)|(wakes up)", r[1]) m2 = re.match("\[...
import os '''存放框架类的 日志,报告,配置文件的路径,保证项目的可移植性,尽量不要使用os.getcwd()去获取路径 ,此方法在其他方法调用时,路径会发生变化,会产生错误''' '''获取项目路径''' file_path=os.path.abspath(__file__) project_path=os.path.dirname(os.path.dirname(file_path)) """配置文件路径""" conf_path=project_path+os.sep+"conf/" '''测试用例路径''' test_case_path=project_path+os.sep+"test_case" ""...
# Quiz: Average Electricity Bill # It's time to try a calculation in Python! # Write an expression that calculates the average of 23, 32 and 64 # Place the expression in this print statement num_1 = 23 num_2 = 32 num_3 = 64 nums_aveg = ((num_1 + num_2 + num_3)/3) print("\n The Average of the Numbers is = %.2f" % nu...
import xml.etree.ElementTree as ET import cv2 import numpy import os.path from os import walk file_count = 6608 chapter_name = "HarukaRefrain" tree = ET.parse('data_set/xml/'+chapter_name+'.xml') root = tree.getroot() for pages in root.findall('pages'): for page in pages: page_number = page.get('index') ...
# Generated by Django 3.2.4 on 2021-06-17 13:53 import datetime from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('pros', '0021_alter_acceptoffer_meeting_time'), ] operations = [ migrations.AlterField( model_name='acceptoffer',...
from PIL import Image import face_recognition import turtle # Load the jpg file into a numpy array image = face_recognition.load_image_file("received_picture_1522877227.6772435.jpeg") # Find all the faces in the image using the default HOG-based model. # This method is fairly accurate, but not as accurate as the CNN ...
# -*- coding: utf-8 -*- # # Copyright (c) 2020 Open Source Robotics Foundation # All rights reserved. # # Software License Agreement (BSD License 2.0) # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # * Redistribut...
import subprocess from bar import barhandler import re from util import * class BspcControl: def __init__(self, bar): self.bar = bar self.bspc = subprocess.Popen(('bspc', 'subscribe', 'report'), stdout=subprocess.PIPE) self.monitors = [] def inputhandler(self, colors): with sub...
from turtle import Turtle, Screen import random screen = Screen() is_game_on = False screen.setup(width=500, height=400) user_bet = screen.textinput(title="Make a bet!", prompt="Which turtle is likely to win the race?" "Enter a colour: ") colours = ["red", "ora...
class Config(object): def __init__(self): # panoptes self.project = 0 self.workflow = 0 # data paths self.swap_path = './' self.data_path = './data/' self.db_name = self.data_path + 'kswap_daniels_online.db' self.db_path = './' self.classes = ['0', '1', '2', '3'] self.label_...
import sys,os from gtts import gTTS # mytext = sys.argv[1] mytext = "hello" os.system(' say {mytext} ') language = 'en' myobj = gTTS(text=mytext, lang=language, slow=False) myobj.save("welcome.wav")
# import pylab # import networkx as nx from brian2 import * from scipy.stats import norm as normDistribution def plotTracesFromStatemon(statemon, *args): N = len(getattr(statemon, args[0])) N_lines = ceil(N/4) plt.ion() plt.figure() plots=[] for i in range(N): plt.subplot(N_lines, 4, i+1) for attribute in ...
from django.contrib import admin from .models import * # Register your models here. class RegionAdmin(admin.ModelAdmin): list_display = ['id', 'name', 'parent','level','longitude','latitude',"is_province",'display','is_municipality'] # list_editable = ['name', 'parent'] admin.site.register(Region, RegionAdm...
from services import func_timer A = [25, 1, 19, 22, 9, 18, 30, 24, 34, 25, 49, 15, 13, 10, 1, 0, 32, 6, 40, 34] @func_timer def selection_sort(sort_list: list) -> list: for i in range(len(sort_list)): min_value = i for j in range(i, len(sort_list)): if sort_list[j] < sort_list[min_val...
#!/usr/bin/env python from __future__ import unicode_literals import sys import datetime import time import getopt # import codecs import pprint import lxml.html import mechanize import cookielib # some utils pp = pprint.PrettyPrinter() debug = 0 ######################### # variables ######################### START...
import pytest from openshift_checks.ovs_version import OvsVersion from openshift_checks import OpenShiftCheckException def test_invalid_openshift_release_format(): def execute_module(*_): return {} task_vars = dict( openshift=dict(common=dict()), openshift_image_tag='v0', ope...
import math from helpers.Debug import Debug """ This class defines some handy functions for various mathematic operations. @version 0.1 @author Nikolay Pulev, Dimitar Dimitrov """ class Math: def __init__(): abstract """ Given a vector as a tuple and an angle in radians, this function calculates and returns t...
#!/usr/bin/env python3 # # blurring.py """ Documentation: """ # from __future__ import print_function # use python 3 syntax but make it compatible with python 2 # from __future__ import division # '' import sys try: sys.path.append('/home/pi/Carl/plib') import speak impor...
"""eduSystem URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/2.1/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') C...
''' # 문제 1. 문자열을 입력받아 문자열의 첫 글자와 마지막 글자를 출력하는 프로그램을 작성하시오. ''' string = input('문자를 입력하세요: ') # 파이썬 코드 print(string[0]) print(string[-1]) # -1 인덱스 접근은 가장 마지막이다. ###### str은 할당이 안된다 -> string = apple; string[0] = b -> 이거 에러남 ''' 문제 2. 자연수 N이 주어졌을 때, 1부터 N까지 한 줄에 하나씩 출력하는 프로그램을 작성하시오. ''' numbers = int(input('숫자를 입력...
# status.py by Dannil import time import dm.cmd.player.player_cmd as player_cmd class Cmd(player_cmd.PlayerCmd): def __init__(self): player_cmd.PlayerCmd.__init__(self) self.add_rule("status") def rule_status(self, body, args): disp = "Wizard : " if body.query("is_wiz"): ...
# # Author: # Date: # Description: # # # Single string containing CSV formatted song data # "artist,album,title,duration" # Note: Duration is specified in seconds # singleSongCSV = "Jimmy Buffett,Songs You Know by Heart,Cheeseburger in Paradise,172" # # List of strings containing CSV formatted song data # songList...
import json ''' Define top-level configuration for WH analysis. ''' # Data source parameters INT_LUMI = 4960 #JOBID = '2012-01-28-v1-WHAnalyze' JOBID = '2012-04-14-v1-WHAnalyze' # Setup function which retrieves fake rate weights fake_rates_file = open('fake_rates.json') fake_rates_info = json.load(fake_rates_file)...
#参考:https://takeg.hatenadiary.jp/entry/2019/09/14/132409 S = input() N = len(S) ans = [0] * N #R count = 0 for i in range(N): if S[i] == "R": count += 1 else: ans[i] += count // 2 ans[i-1] += count - (count // 2) count = 0 #L count = 0 for i in reversed(range(0,N)): if S[i]...
import tkinter as tk import subprocess import os root= tk.Tk() mainCanvas = tk.Canvas(root, width = 400, height = 300) mainCanvas.pack() inputEntry = tk.Entry (root) mainCanvas.create_window(200, 140, window=inputEntry) def getSquareRoot (): try: app_id = inputEntry.get() #Replace with own p...
# from polyglot.text import Text # # from polyglot.detect import Detector # pol = Text("отвратительно и унизительно", hint_language_code="ru").polarity # print(pol) ########### Python 3.2 ############# import http.client, urllib.request, urllib.parse, urllib.error, base64 import csv import sys import json from time im...
# -*- coding: utf-8 -*- # Copyright (c) 2016-2023 by University of Kassel and Fraunhofer Institute for Energy Economics # and Energy System Technology (IEE), Kassel. All rights reserved. from numpy import int64 from pandapower.timeseries.data_source import DataSource try: import pandaplan.core.pplog as pplog exce...
# -*- coding: utf-8 -*- u"""\ FlexiNS/MME Cause code mapping Checking - NS/MME软件版本为NS15或者更高版本 - 已开启功能开关PRFILE002:2244-MME_CC_MAPPING_ENABLED - 有新建CAUSE CODE SETS,如:EPCEMM和EPCESM(各项目名称可能不相同). - EPCEMM,TYPE=EMM,PROC=ATTREJ,INTCAUSE=142 To EXTERNAL CAUSE=15 - EPCEMM,TYPE=EMM,PROC=ATTREJ,INTCAUSE=9...
from . import db import uuid import sqlalchemy import json import ast from sqlalchemy import TypeDecorator, types from sqlalchemy.dialects.postgresql import JSONB # sqlalchemyのgithubを見ると、sqliteのjsonを追加したものが最新ソースに上がっているが # 最新版のsqlalchemy(2018/10/23現在:ver1.2.12)にはまだ更新されていない模様(Pyplのpkgが更新されていない?) # 下記importがエラーになる # from...
import requests # 这里面的http://47.75.32.210:1080加不加http://都可以 proxies = {"http":"http://47.75.32.210:1080"} headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.130 Safari/537.36"} "这里一开始我尝试连接百度,结果出错了, 我觉得应该是百度判断出了爬虫行为,所以我随便连接了一个网站" r = requests.ge...
#!/urs/bin/env python # -*- coding: utf-8 -*- # # hint: line 245 # import sys, re, time, argparse, os, json from urllib.request import Request, urlopen from urllib.error import URLError from bs4 import BeautifulSoup, Comment import logging import logging.config import bibtexparser from bibtexparser.bwriter import BibT...
import os, random, time, copy import sys from skimage import io, transform import numpy as np import os.path as path import scipy.io as sio import matplotlib.pyplot as plt import torch from torch.utils.data import Dataset, DataLoader import torch.nn as nn import torch.optim as optim from torch.optim import lr_schedule...
# coding: utf-8 # # Filter Bank # Implement 1 branch, subband k=1, of the analysis and synthesis filter bank with N=16 subbands with 32kHz sampling rate (hence the passband is between 1 kHz and 2 kHz), in **direct implementation**. # Start with designing a bandpass filter using the scipy.signal.remez function, which ...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from decouple import config created_at_field_text = 'fecha de creación' deleted_at_field_text = 'fecha de eliminación' jwt_key = config('JWT_KEY')
from django.db import models from django.core.exceptions import ValidationError from django.contrib.auth.models import AbstractUser # Create your models here. class UserProfile(AbstractUser): genders = [('s', "Male"), ("F", "Female")] cell = models.CharField (max_length=10) gender = models.CharField (choice...
# -*- coding: utf-8 -*- from __future__ import unicode_literals import django from django.db import migrations, models class Migration(migrations.Migration): dependencies = [("msgs", "0011_auto_20160222_1422")] operations = [ migrations.CreateModel( name="Labelling", fields=...
# slowniki upraszczajace testowanie wielu modeli import numpy as np import tensorflow as tf from tensorflow.keras import layers from tensorflow.keras.models import Sequential from tensorflow.keras.applications import VGG16, MobileNet, MobileNetV2, NASNetMobile, EfficientNetB0 from tensorflow.keras.applications import ...
# coding: utf-8 """ Xero Payroll UK This is the Xero Payroll API for orgs in the UK region. # noqa: E501 Contact: api@xero.com Generated by: https://openapi-generator.tech """ import re # noqa: F401 from xero_python.models import BaseModel class EmployeeLeaveType(BaseModel): """NOTE: This ...
#!/usr/bin/python import threading class ClientThread(threading.Thread): def __init__(self, socket, ip, port): threading.Thread.__init__(self) self.ip = ip self.port = port self.socket = socket ## implement the run functionality of thread def run(self): # do the work here
from __future__ import division import pygame import random from os import path directorioImagenes = path.join(path.dirname(__file__), 'assets') directorioSonidos = path.join(path.dirname(__file__), 'sounds') ANCHO = 480 ALTO = 500 FPS = 60 POWERUP_TIME = 5000 BAR_LENGTH = 100 BAR_ALTO = 10 WHITE = (255, 255, 255) B...
from a10sdk.common.A10BaseClass import A10BaseClass class DevVipPortList(A10BaseClass): """This class does not support CRUD Operations please use parent. :param dev_vip_port_num: {"type": "number", "format": "number"} :param dev_vip_port_state: {"type": "string", "format": "string"} :param Devic...
from django.contrib import admin from django.urls import include, path # urls urlpatterns = [ path('admin/', admin.site.urls), path('api/v1/contest/', include('contest.urls')), ]
#!/usr/bin/python3 import jwt rockyou = open("/usr/share/wordlists/rockyou.txt","r",encoding = "ISO-8859-1").read().split("\n") jwtTrue = b'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyIjoiUm9vdEh1bnRlciJ9.Wg_9qTDnZEVVLzq3anzAD2SXWI_nBYu_RO9L2QVEW3s' for secret in rockyou: secret = b"ilovepico" encoded = jwt.e...
import scipy.misc import numpy as np def merge_image(images, size=(10, 10)): h, w = images.shape[1], images.shape[2] img = np.zeros((h*size[0], w*size[1], 3)) for idx in range(min(size[0] * size[1], len(images))): i = idx % size[1] j = idx // size[1] img[j*h:(j+1)*h, i*w:(i+1)*w, :]...
#!/usr/bin/python # # C++ version Copyright (c) 2006-2007 Erin Catto http://www.gphysics.com # Python version Copyright (c) 2008 kne / sirkne at gmail dot com # # Implemented using the pybox2d SWIG interface for Box2D (pybox2d.googlepages.com) # # This software is provided 'as-is', without any express or impli...
class Line: def __init__(self, point_a, point_b): """ Make a new line from two points. :param point_a: one of the points on the line :type point_a: tuple(float, float) :param point_b: one of the points on the line :type point_b: tuple(float, float) """ ...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13. What is the 10001-st prime number? 104743 """ import math def is_prime(n): if n <= 1: return False if n <= 3: return False if n % 2 == 0 or n % 3 == 0: ret...
# coding:utf-8 import os import pickle import datetime import logging import json import argparse import sys import random import numpy as np from pprint import pprint, pformat import torch from torch.utils.data import DataLoader import models import models.loss as module_loss import models.metrics as module_metrics ...
import datetime from app import db from werkzeug.security import check_password_hash, generate_password_hash class User(db.Model): __tablename__ = 'users' id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(100), index=True) email = db.Column(db.String(140), index=True, unique=...
from celery import Celery from ..core.config import CELERY_BROKER_URL, CELERY_RESULT_BACKEND celery = Celery("worker", backend=CELERY_BROKER_URL, broker=CELERY_RESULT_BACKEND)
from urllib.request import urlopen import re def crawl(url, maxurls): """Starting from this URL, crawl the web until you have collected maxurls URLS, then return them as a set""" urls = set([url]) while(len(urls) < maxurls): # remove a URL at random url = urls.pop() print("URL: ", url) links = get_l...
"""Test for app.py.""" from aiohttp import web from app import init_app async def test_app(): """Test init_app return web.Application instance.""" isinstance(init_app, web.Application)
print("welcome to Python Era \n") # for i in range(0,10): # print(i) # if(i==5): # print("point to stpo " , i) # break # # end for # x=0 # while(x<=10): # print(x) # if(x==5): # print("point to stpo " , x) # break # x+=1 list1=[1,2,3,4,5] f...
import numpy as np import os.path import sys import torch import torch.nn.functional as F from annoy import AnnoyIndex def twod_map(array, mapping): new_array = [[mapping[j] for j in i] for i in array] return new_array def create_index(X, index_type='annoy'): if index_type == 'faiss': X_cont = np...
from selenium import webdriver import time, csv driver = webdriver.Chrome('./chromedriver') driver.get('https://www.hrjohnsonindia.com/dealers') time.sleep(2) csv_file = open('hrjohnsonindia.csv', 'w') csv_writer = csv.writer(csv_file) csv_writer.writerow(['Dealer', 'Address', 'City', 'State', 'Phone', 'Deals_In']) ...
""" 1. sublist count starts at length//2 2. have two functions: one to break the list into sublists and one to sort the sublists 3. for sublist sort function: 4. current value = """
from model import Model, lazy_property from multiclass_model import MulticlassModel import tensorflow as tf class ResNet(Model): def __init__(self, model_config): Model.__init__(self, model_config) @lazy_property def prediction(self): conv_init = tf.layers.conv2d( ...
# -*- coding: utf-8 -*- from django.core.exceptions import ValidationError import abc def parse_matcher(text): MATCHERS = [Composition, Choice, Multiplier, Constant] text = text.strip() if '(' in text or ')' in text: raise ValidationError('Nested relation matchers are not supported.') for matc...