text
stringlengths
38
1.54M
# -*- coding: utf-8 -*- # Generated by Django 1.11.5 on 2017-10-19 18:52 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('catalog', '0012_auto_20171012_1038'), ] operations = [ migrations.AlterFiel...
import json import requests import random import subprocess import sys from urllib.request import urlopen, URLError from getch import getch red = "\033[91m" green = "\033[92m" reset = "\033[0m" def display(result): """Display images fetched from any subreddit in your terminal. Args: result (list...
""" Exercise 2 More anagrams! Write a program that reads a word list from a file (see Section 9.1) and prints all the sets of words that are anagrams. Here is an example of what the output might look like: ['deltas', 'desalt', 'lasted', 'salted', 'slated', 'staled'] ['retainers', 'ternaries'] ...
"""empty message Revision ID: 515d2606c301 Revises: 1be5b55ecd31 Create Date: 2017-06-09 19:45:19.002828 """ from alembic import op import sqlalchemy as sa from sqlalchemy.dialects import postgresql # revision identifiers, used by Alembic. revision = '515d2606c301' down_revision = '1be5b55ecd31' branch_labels = None...
A = float(input()) B = float(input()) C = float(input()) MEDIA = A*2+B*3+C*5 MEDIA /= 10 print("MEDIA = %.1f"% (MEDIA))
#JSON에 모든 정보가 들어있는데 보안상 문제가 있을 수 있어서 이것을 사용 from rest_framework import serializers #데이터를 보기 좋게 만들기 위함 from django.contrib.auth.models import User class UserShortcutSerializer(serializers.ModelSerializer): class Meta: model = User # Model 등록 fields = ("username", "email", "first_name","last_nam...
''' A quick set of tools for doing stack doping. ''' import logging import vtrace logger = logging.getLogger(__name__) def dopeThreadStack(trace, threadid): curthread = trace.getCurrentThread() try: trace.selectThread(threadid) sp = trace.getStackCounter() mmap = trace.getMemoryMap(s...
x = tf.placeholder(tf.float32) y = tf.placeholder(tf.float32) w = tf.Variable(tf.zeros([1, 1], dtype=tf.float32)) b = tf.Variable(tf.ones([1, 1], dtype=tf.float32)) y_hat = tf.add(b, tf.matmul(x, w)) # ...more setup for optimization and what not... saver = tf.train.Saver() # defaults to saving all variables - in th...
from openmc.filter import * from openmc.filter_expansion import * from openmc import RegularMesh, Tally from tests.testing_harness import HashedPyAPITestHarness def test_tallies(): harness = HashedPyAPITestHarness('statepoint.5.h5') model = harness._model # Set settings explicitly model.settings.bat...
import sys import glob import time import os.path import re import tree import parse ## Input Parameters IN_DIR = sys.argv[1] OUT_DIR = sys.argv[2] IS_INPUT = sys.argv[3] IV_INPUT = sys.argv[4] IV_PUP_DIR = sys.argv[5] ## Key Variables NC_P_FILE = "/data/project/RefStand/gavehan/PIPE/py_pickle/nc.tree...
""" The module for Unbounded Interleaved-State Recurrent Neural Network. An introduction is available at [README.md]. [README.md]: https://github.com/google/uis-rnn/blob/master/README.md Source: https://github.com/google/uis-rnn """ from wildspeech.diarization.uisrnn import arguments, evals, utils, uisrnn #pylint: ...
from collections import Counter as co, deque as dq for _ in range(int(input())): n,k = map(int, input().split()) c = list(map(int, input().split())) ans = 0 mc = max([x for x in co(c).items()], key=lambda x: x[1]) i = 0 while i<n: if c[i]!=mc[0]: ans+=1 i+=k ...
class Computer: def __init__(self): #encapulation #double __ is private #single _ is protected self.__maxprice = 900 def sell(self): print("Selling Price: {}".format(self.__maxprice)) def setMaxPrice(self, price): self.__maxprice = price class Parrot: ...
# -*- coding=utf-8 -*- import math from flask import Flask, current_app, request, \ render_template from xp_mall.mall import mall_module from xp_mall.models.order import Order from xp_mall.extensions import db,csrf from xp_mall.utils import get_pay_obj @csrf.exempt @mall_module.route('/pay/<string:payment>/<string...
b=10 # atribui valor 10 a B a=20 # atribui valor 20 a A b = int(input()) # entrada de valor pra B print(a,b) # Exibi o valor de A e o novo valor de B => 5
# -*- coding: utf-8 -*- # # Copyright (c) 2020, the cclib development team # # This file is part of cclib (http://cclib.github.io) and is distributed under # the terms of the BSD 3-Clause License. """Test the DDEC6 in cclib""" from __future__ import print_function import sys import os import logging import unittest ...
#!/usr/bin/python # labjack.py import u3 d = u3.U3() #d.debug = True spi_conf_temp = { "AutoCS": True, "DisableDirConfig": False, "SPIMode": 'C', "SPIClockFactor": 0, "CSPINNum": 8, "CLKPinNum": 12, "MISOPinNum": 15, "MOSIPinNum": 14 } spi_conf_pga = { "AutoCS": True, "Disabl...
from tkinter import * '''Thank you for coming here... May Dazzler's light shine upon u all..''' root =Tk() root.geometry("350x350+300+300") root.resizable(0,0) root.title("Dazzler's Calculater v1.0") root.wm_iconbitmap("k.ico") #Dazzler's coding def click(event): global sc text=event.widget.cget("text") i...
from quart import Quart import asyncio import uuid import re from app import workers app = Quart(__name__) tasks = {} @app.route('/api/download/text/<path:url>', methods = ['GET']) async def download_text(url): regex = re.compile( r'^(?:http|ftp)s?://' r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])...
import os import logging from flask import Flask, jsonify, request from flask.logging import default_handler import s3 import producer application = Flask(__name__) # noqa # Set up logging ROOT_LOGGER = logging.getLogger() ROOT_LOGGER.setLevel(application.logger.level) ROOT_LOGGER.addHandler(default_handler) # Ka...
from django.conf.urls import patterns, include, url from dashboard import views from payment_gateway_views import * from profile_views import * from store_category_views import * from shipping_views import * urlpatterns = patterns('', url(r'^$', views.IndexView.as_view(), name='index'), url(r'^login$', views....
# Generated by Django 3.1.7 on 2021-03-13 23:50 import datetime from django.db import migrations, models from django.utils.timezone import utc class Migration(migrations.Migration): dependencies = [ ('lost', '0002_auto_20210314_0510'), ] operations = [ migrations.AlterField( ...
import pandas as pd import pymysql import os import sys,csv import argparse import matplotlib.pyplot as plt import numpy as np import plotly.express as px import mysql.connector from mysql.connector import Error mydb = mysql.connector.connect( host="localhost", user="souravkc", passwd="pass123", database="Jd...
# coding: utf-8 import pytest import gridforme @pytest.fixture def app(): gridforme.app.config['TESTING'] = True return gridforme.app.test_client() def test_home_url(app): rv = app.get('/') assert 200 == rv.status_code def test_image_url(app): rv = app.get('/i/12/95/30/15/') assert 200 == ...
from Myro import * from Graphics import * from random import * init("sim") def findColorSpot(picture, color): xPixelSum = 0 totalPixelNum = 0 averageXPixel = 0 show(picture) for pixel in getPixels(picture): if(color == 1 and getRed(pixel) > 220 and getGreen(pixel) == 0 and getBlue(pixel) ...
import main z=main.Meeting dic={1:"1: 9.00-10.00 AM",2:"2: 10.15-11.15am",3:"3: 11.30am-12.30PM",4:"4: 1.00-2.00PM",5:"5: 2.15-3.15"} keys=dic.keys() z.time_view(dic) time=eval(input("enter the slot you want: ")) z.schedule(dic,keys,time)
from random import * base =[1,2,3,4,5,6,7] print(*base,sep=' + ',end="") tong = sum(base) print(" =",tong)
from typing import Type def evaluate_post_fix(string): stack = [] try: for i in string: # if number append to stack if i.isdigit(): stack.append(i) # skip spaces elif i == ' ': continue # if operator is enc...
from django.test import TestCase from .models import Todo # Create your tests here. class TodoModelstCase(TestCase): @classmethod def setUpTestData(cls): Todo.objects.create(title='A new title', body='Whats up danger.') def testTaskTitle(self): todo = Todo.objects.get(id=1) ex...
# Team ID: <TODO: fill up> def schedule2(locations, start_location, capacities, orders): # TODO: replace the code in this function with your algorithm #This dumb model solution does not make use of locations #However, to optimize your total traveling distance, you must use locations' information ...
from django.contrib.auth.models import (AbstractBaseUser, BaseUserManager, PermissionsMixin) from django.core.mail import send_mail from django.db import models from django.conf import settings from django.utils.translation import gettext_lazy as _ class CustomUserManager(BaseU...
from django.contrib import admin from imagekit.admin import AdminThumbnail from common.admin import AutoUserMixin from shapes.models import MaterialShape, SubmittedShape from photos.models import FlickrUser, PhotoSceneCategory, Photo, \ PhotoWhitebalanceLabel, PhotoSceneQualityLabel admin.site.register(FlickrUs...
""" file: test_phone_number_extraction.py brief: author: S. V. Paulauskas date: April 17, 2020 """ SAMPLE_LIST = [ "6464159260", "212 6561437" "123-456-7890" "(919) 612-0710" " 5129657186" ]
#bot details ===================================================================================================== token = "11111111:xxxxxxxxxxxxxxxxxxxxxxxxxxxxx" #Telegram bot token # wapi ===================================================================================================== # register in wapi web...
allS = int(input()) h = allS // 3600 m = allS % 3600 // 60 s = allS % 3600 % 60 print("{}:{}:{}".format(h, m, s))
def get_board_vars(): file = open("board_vars.txt", 'r') text = file.read() file.close() var = [] curr_string = "" for v in text: if v == "\n": var.append(curr_string) curr_string = "" else: curr_string = curr_string + v for i in range(len(var)): var[i] = float(var[i]) return var print(get_boa...
# Crie um programa que leia uma frase qualquer e diga se ela é # um palíndromo, desconsiderando os espaços. (Palindromo) # Exemplo: APOS A SOPA (Ao inverter a frase é mesma frase.) frase = str(input('Digite um frase: ')).strip().upper() # Eliminou os espaços antes e depois, alterei para maiúsculas palavras = frase.spl...
# coding=utf-8 import os import time import datetime import logging import yaml from porter.grads_parser.grads_ctl_parser import GradsCtl, GradsCtlParser from porter.grads_tool.converter.grads_to_micaps import GradsToMicaps logger = logging.getLogger(__name__) class GradsConvert(object): def __init__(self): ...
#!/usr/bin/env python3 """ Long Short Term Memory Cell """ import numpy as np class LSTMCell: """ class LSTMcell that represents a LSTM unit """ def __init__(self, i, h, o): """ Constructor i is the dimensionality of the data h is the dimensionality of the hidden state ...
# Generated by Django 2.0.3 on 2018-03-22 12:01 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('blog', '0008_tag'), ] operations = [ migrations.RemoveField( model_name='tag', name='post', ), migra...
# -*- coding: utf-8 -*- # Define here the models for your scraped items # # See documentation in: # https://docs.scrapy.org/en/latest/topics/items.html import scrapy class HuaxiaItem(scrapy.Item): grab_time = scrapy.Field() brandname = scrapy.Field() brand_id = scrapy.Field() factoryname = scrapy.Fi...
from urllib.request import build_opener, HTTPCookieProcessor import http.cookiejar # 生成cookie 文件 filename = "cookie.txt" # 将文件保存为Mozilla 类型浏览器的 cookie 格式 文件 # 申明一个 cookie 对象 cookie = http.cookiejar.MozillaCookieJar(filename) # 用HTTPCookieProcessor 构建handler handler = HTTPCookieProcessor(cookie) # 用build_opener 构建一个open...
import unittest from app.models import Comment,User,Pitch from app import db class CommentModelTest(unittest.TestCase): def setUp(self): self.user_postgres = User(username = 'kayleen',password = 'password', email = 'kayleen@gmail.com') self.new_comment = Comment(comment='nice work',user =...
import unittest from JustFriends.code.tests.location_test import TestLocationMethods from JustFriends.code.tests.places_test import TestPlacesMethods if __name__ == '__main__': places_test_suite = unittest.TestLoader().loadTestsFromTestCase(TestPlacesMethods) location_test_suite = unittest.TestLoader().loadT...
# -*- coding:utf-8 -*- # 求解一元一次方程 print("This program is for equation Ax + B = C.") print("Please input number A.") numberA = input() print("Please input number B.") numberB = input() print("Please input number C.") numberC = input() print("The equation is: " + str(numberA) + ' * x + ' + str(num...
from os import listdir, path, makedirs from os.path import isfile, join from IPython.display import display, Markdown, Latex import nbformat as nbf import re, string class Migration(object): def parse_path(self, wiki): filename = re.match('.*\+\+\W(.*)', wiki) if filename: ...
import sqlite3 DB_NAME = 'example.db' conn = sqlite3.connect(DB_NAME) conn.cursor().execute(''' CREATE TABLE IF NOT EXISTS posts ( id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL, author TEXT NOT NULL, content TEXT, price REAL, datestamp TEXT, acti...
import cv2, cameraUtils import numpy as np from math import sqrt from more_itertools import sort_together class CoordinateBox: def __init__(self, mins, maxes): """init""" self.x_min = mins[0] self.y_min = mins[1] self.x_max = maxes[0] self.y_max = maxes[1] self.x_center, self.y_center = self.getAbsoluteBo...
import re import datetime def weekday(fulldate): day_dict = { 0: 'Måndag', 1: 'Tisdag', 2: 'Onsdag', 3: 'Torsdag', 4: 'Fredag', 5: 'Lördag', 6: 'Söndag' } return day_dict[datetime.datetime.weekday(fulldate)] def find_poi(dataframe, column): # F...
import time import logging as log import asyncore import threading, collections, queue, os, os.path import deepspeech import numpy as np import scipy import wave import asyncio from pyAudioAnalysis import ShortTermFeatures as sF from pyAudioAnalysis import MidTermFeatures as mF from pyAudioAnalysis import audioTrainTes...
# -*- coding: utf-8 -*- from odoo import api,models,fields class ProductBrand(models.Model): _name='product.brand' name=fields.Char('Brand Name') code=fields.Integer('Brand Code')
import sys def main(): if(len(sys.argv) != 2): print("Pass in one geojson file in the command line") with open("../" + sys.argv[1]) as f: #Add the file that needs to be reformated formattedFile = "../formatted_" + sys.argv[1] with open(formattedFile, "w") as f1: for li...
#!/usr/bin/env python # I will add feedforwardterm later # I will high speed damping term too import rospy import math from sympy import Derivative, symbols from std_msgs.msg import Float32MultiArray from std_msgs.msg import Float32 from nav_msgs.msg import Odometry max_rad=0.523598 #I added margin min_rad=-0.523598 ...
N = int(input()) result = [] for i in range(N): xy = list(map(int, input().split(" "))) result.append(xy) result.sort(key=lambda x: (x[0], x[1])) for i in result: print(str(i[0]) + " " + str(i[1]))
#!/usr/bin/python # -*- coding: utf-8 -*- """ ========================================================================= msproteomicstools -- Mass Spectrometry Proteomics Tools ========================================================================= Copyright (c) 2013, ETH Zurich For a full list of authors, r...
def SumDigit(a): suma=0 while a>0: digit=a%10 suma+=digit a//=10 return suma print(SumDigit(112345))
# -*- coding: utf-8 -*- from git import Repo import os class Git: def __init__(self, oniroku): self.repos = self.get_template_repo() self.directory = oniroku.directory self.name = oniroku.name def get_template_repo(self): return "git@github.com:takaaki-mizuno/oniroku-template...
""" The Data Science Assistant ========================== The Data Science ``Assistant`` provides a collection of methods to address the most typical procedures when analyzing data. Such processes include:: - Profiling data - Filling missing values - Detecting and removing outliers - Feature transformations - Feature...
from scipy.io import arff import numpy as np from sklearn.preprocessing import MinMaxScaler m = MinMaxScaler() #Movement Libras load and formating data, metadata = arff.loadarff('movement_libras.arff') l = [] for d in data: l.append(list(d)) D = np.array([l[0]], dtype = np.float32) for i in range(1,len(l)): D = ...
# Generated by Django 2.2.3 on 2019-07-17 08:58 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('rooms', '0006_auto_20190717_0808'), ] operations = [ migrations.AlterField( model_name='room', name='accuracy_rating...
''' Напиши программу на вход которой в единственной строке поступает вещественное число. Программа должна вывести только целую часть этого числа без незначащих нулей. Stepik001132ITclassPyсh03p01st02TASK01_20200611.py ''' num = input() a, b = num.split('.') print(int(a))
#!/usr/bin/env python3 # -*- coding:utf-8 -*- """ 发送邮件 """ """ 第一种发送邮件的方法 import smtplib from email.mime.text import MIMEText from email.utils import formataddr #通过qq邮箱发送 my_sender='1617265674@qq.com' # 发件人邮箱账号 my_pass = 'vvdyneaymjbbddhf' # 发件人邮箱密码(当时申请smtp给的口令) my_user='rongzepei@gosuncn.com' ...
#!/usr/bin/python3 # -*- coding: utf-8 -*- # @Author : Kun Luo # @Email : olooook@outlook.com # @File : transformer.py # @Date : 2021/06/28 # @Time : 17:05:19 import torch from torch import nn def pad_mask(q, k=None) -> torch.BoolTensor: """ Args: q: [batch_size, seq_len] k: [bat...
# -*- coding: utf-8 -*- # Generated by Django 1.11.18 on 2019-05-06 16:56 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('student', '0016_stock_details'), ] operations = [ migrations.CreateModel( ...
# adapted from https://twistedmatrix.com/documents/current/_downloads/stdiodemo.py from twisted.internet import stdio, reactor from twisted.protocols import basic """ A basic user console """ class Console(basic.LineReceiver): delimiter = '\n' # unix terminal style newlines. remove this line # for use wit...
import bhi160 import display import leds import os import utime try: accel = bhi160.BHI160Accelerometer() except: os.reset() leds.clear() with display.open() as d: d.clear() d.update() for i in range(3): leds.set_rocket(i, 0) # Characters are encoded in columns per 11 bits in an integer. # LSB =...
from django.urls import path, include from . import views urlpatterns = [ path('add_book/', views.add_book), path('show_books/', views.show_books), ]
from mamba import description, context, it from expects import expect, equal, contain, end_with from fractions import Fraction from ly2abc.lilypond_music import LilypondMusic from ly2abc.output_buffer import OutputBuffer from spec.ly2abc_spec_helper import * class LyCommand: def __init__(self,text,siblings=[]): ...
############################################################### # Image Feature classification using Random Forest classifier # # Input: Training and Test feature file in *.csv format # # Output: Accuracy # ############################################################### import pandas as pd import numpy...
import inspect import requests from deepviz.result import * try: import json except: import simplejson as json URL_INTEL_REPORT = "https://api.deepviz.com/intel/report" URL_INTEL_SEARCH = "https://api.deepviz.com/intel/search" URL_INTEL_IP = "https://api.deepviz.com/intel...
import csv import sys import math import operator import numpy as np #open and read file depending on file # Reads in data with open('movies.csv') as f: lines = csv.reader(f, delimiter=',') movies={} for row in lines: movieID= row[0] movieTitle= row[1] movies[movieID] = str(movieTitle) f.close() #op...
''' David Lettier (C) 2013. http://www.lettier.com/ This script plots the 3D path/trajectory of the ball. ''' import os; import sys; from os import listdir; from os.path import isfile, join; import matplotlib.pyplot as plt; from mpl_toolkits.mplot3d import Axes3D; # Ball path experiment data directory. directory...
''' Highly divisible triangular number The sequence of triangle numbers is generated by adding the natural numbers. So the 7th triangle number would be 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28. The first ten terms would be: 1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ... Let us list the factors of the first seven triangle nu...
class Solution: def multiply(self, num1: str, num2: str) -> str: if num1 == '0' or num2 == '0': return '0' product = [0] * (len(num1) + len(num2)) for i in range(len(num1) - 1, -1, -1): for j in range(len(num2) - 1, -1, -1): product[i + j + 1] += int...
import mediapipe as mp import cv2 import numpy as np import uuid import os import time #import serial #ser = serial.Serial('com3', 9600) pTime = 0 mp_drawing = mp.solutions.drawing_utils mp_hands = mp.solutions.hands cap = cv2.VideoCapture(0) #val = (143.0/640) with mp_hands.Hands(max_num_hands=1, ...
import requests import pandas as pd from collections import OrderedDict import os from collections import OrderedDict #global api_key,sim_id_dict,stock_price_dict # here you have to enter your actual API key from SimFin api_key = "*" sim_ids = [] stock_price_dict={} #tickers = ['AAPL', 'MSFT'] df2 = pd.read_csv('stoc...
#!/usr/bin/python import trello as trellomodule import plistlib import subprocess import os import sys from datetime import date, datetime, timedelta import requests import json import optparse from string import atoi from ConfigParser import RawConfigParser # Default settings (overridden by config file and command l...
from item_info import ITEM_INFO class Menu: MAX_MENU_LENGTH = 5 def __init__(self, items, return_option): self.items = items self.item_info = ITEM_INFO self.menu_length = 0 self.menu_number = 0 self.max_menus = 0 self.command = "" self.return_option = re...
"""change column Revision ID: e3eda40c3d84 Revises: e1376d6927c0 Create Date: 2021-02-21 12:43:05.385518 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = 'e3eda40c3d84' down_revision = 'e1376d6927c0' branch_labels = None depends_on = None def upgrade(): # ...
import os import librosa import soundfile as sf for filename in os.listdir("ft_wav"): if filename.endswith(".wav"): y, s = librosa.load(f"ft_wav/{filename}", sr=22050) sf.write(f"ft_wav2205/{filename}", y, s)
import requests from datetime import datetime from flask import Blueprint, render_template, request, redirect, jsonify, url_for from mod_data_receiver.tasks import DataReceiverTask data_receiver_blueprint = Blueprint('data_receiver', __name__, url_prefix="/data-receiver") # BASE_URL_LTA = "https://portal.labtestingapi...
from django import forms from . import models class ToDoForm(forms.ModelForm): class Meta(): model = models.ToDo fields = ('task',) widgets = { 'task':forms.TextInput(attrs={'autocomplete':'off', 'class':'form-control'}) } ...
from ingestor.ingestor import Ingestor from apiclient.errors import HttpError from oauth2client.tools import argparser if __name__ == "__main__": argparser.add_argument("--q", help="Search term", default="Google") argparser.add_argument("--location", help="Location", default="37.42307,-122.08427") argparser.add...
import pdb from math import sin, pi K = 6#外推次数,即k的最大值 g = [[None for t in range(K-k)] for k in range(K)]#表 h_0 = 2 for t in range(K):#初始化第一列 g[0][t] = (2**t/h_0)*sin(h_0*pi/(2**t)) for k in range(1, K): for t in range(K-k): temp = 2**(2*k) g[k][t] = (temp*g[k-1][t+1]-g[k-1][t...
import numpy as np class KalmanFilterEq(): ''' Initialize the required terms used in the Extended Kalman Filter equations. Set P - Uncertainity covariance matrix of state(x) Q - Covariance matrix of noise F - Update matrix n - Number states to estimate x - s...
import json import multiprocessing as mp import os import time from pathlib import Path from typing import List import numpy as np import shutil from file_handling import write_simulations_to_disk from noise import NoiseType from stats import delayed_ou_processes_ensemble, SimulationResults T = 1 # delay T_cycles =...
# Daniel Garcia # SBU ID: 111157499 # Homework 1 # Question 6, Part 3 def cff_three(stringList): createTuple = lambda word: (word, len(word)) newList = list(map(createTuple, stringList)) return newList print(cff_three(['part', 'three', 'example']))
from django.shortcuts import render,redirect; from django.contrib.auth.forms import UserCreationForm; from django.contrib.auth.models import User; from django.contrib import messages; # Create your views here. from users.forms import CustomRegister; from django.contrib.auth.decorators import login_required; def registe...
N, M = map(int, input().split()) E1 = set() EN = set() for n in range(M): a, b = map(int, input().split()) if a == 1: E1.add(b) if b == 1: E1.add(a) if a == N: EN.add(b) if b == N: EN.add(a) for a in E1: if a in EN: print("POSSIBLE") break else: ...
#!/usr/bin/python ''' Deep neural networks for regression using chainer. ''' from base_util import * from base_ml import * from base_chn import loss_for_error2 from chainer import cuda, Variable, FunctionSet, optimizers import chainer.functions as F import six.moves.cPickle as pickle #Tools for NNs #ReLU whose inp...
#!/usr/bin/python import time from geopy.geocoders import Nominatim geolocator = Nominatim() def getGPS(place): #location = geolocator.geocode("Acquafredda di Maratea, Italia") location = geolocator.geocode(place) if not location: return 'NOT FOUND' #print(str(place).encode("utf-8")) #pr...
from django.contrib import admin from .models import ProfileUpload,MyDetails, Author, Document,Cars # Register your models here. admin.site.register(ProfileUpload) admin.site.register(MyDetails) admin.site.register(Author) admin.site.register(Document) admin.site.register(Cars)
from SearchProblem import Problem from SearchProblem import Node MAX_DEPTH = 20 class SearchProblemSolver: """This class performs an iterative deepening DFS search on a given graph. """ def __init__(self, problem: Problem.ProblemSearch): self.problem = problem self.start_node = Node....
from django.shortcuts import render from django.views import View from django.contrib.auth.decorators import login_required from django.utils.decorators import method_decorator from .models import OrderReceiving from .forms import * from customers.models import Customer # Create your views here. @method_decorator(l...
import time import glob import random import psutil import curses import msgpack import inotify.adapters from threading import Thread, Lock from common.util import read_binary_file from kafl_fuzz import PAYQ WORKDIR = '' SVCNAME = '' # current payload PAYLOAD = '' # screen width WIDTH = 80 # color pair code WHITE ...
# Copyright 2018 David Matthews # # 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 writin...
from BeautifulSoup import BeautifulSoup import pandas as pd data = open('predictwise.html').read() bs = BeautifulSoup(data) obama = {} romney = {} votes = {} for state in bs.findAll('div', 'state_info'): name = state.find('h5').contents[0] v = state.find('dl', 'votes').find('dt').contents[0] o, r = state...
from cnn.Setup import Setup import sys import keras.backend as K import numpy as np import os from keras.utils import to_categorical from sklearn.model_selection import train_test_split rel_filepath = sys.argv[1] XTest_directory = sys.argv[2] continue_setup = Setup('') continue_setup.load(rel_filepath=rel_filepath) ...
from flask import render_template, jsonify, redirect, url_for, request, render_template import app from app import db, app from models import node from forms import auth_form from flask_login import login_user, login_required, logout_user, LoginManager, current_user from werkzeug.security import generate_password_hash...
from django.apps import AppConfig class FirmwareUploadsConfig(AppConfig): name = "firmware_uploads" verbose_name = "Firmware Uploads"