text stringlengths 38 1.54M |
|---|
#!/usr/bin/env python
# get [log key, delta time] as input for deeplog
#log_structured_file = output_dir + log_file + "_structured.csv"
#log_templates_file = output_dir + log_file + "_templates.csv"
#log_structured_df = pd.read_csv(log_structured_file)
#hdfs_input = []
#prev_time = None
#fmt = "%y%m%d %H%M%S"
#for i... |
from freenit import create_app
from config import configs
config = configs['development']
app = create_app(config)
|
inputFile = open("i1.txt", "r")
def same_word_in_list(str_list):
if len(str_list) == 0:
return False
for i in range(0, len(str_list)):
for j in range(i + 1, len(str_list)):
if str_list[i] == str_list[j]:
return True
return False
def find_valid_in_file(inputFil... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Time : 18/1/6 10:36
# Author : Eric.Zhang
import paramiko
import logging
import logging.config
import argparse
import datetime
import sys, os
import smtplib
from email.mime.text import MIMEText
from email.utils import formataddr
EMAIL_ADDR = ['neteric@126.com', 'tc_... |
LOGS_CONFIG = 'logging.conf'
CRONTAB_PATH = 'jobs.tab'
TIME_ZONE = 'Europe/Kiev'
HIBERNATION_PERIOD = 30
|
from copy import deepcopy
N = int(input())
X = input()
def popcount(n: int) -> int:
return bin(n)[2:].count("1")
def f(n: int) -> int:
i = 0
while n > 0:
n = n % popcount(n)
i += 1
return i
for i in range(N):
rev = "0" if X[i] == "1" else "1"
_X = X[:i] + rev + X[i+1:]
... |
# Argument Mutability
friends_last_seen = {
'Rolf': 31,
'Jen': 1,
'Anne': 7
}
def see_friend(friends, name):
print(friends is friends_last_seen)
print(id(friends))
friends[name] = 0
print(id(friends_last_seen))
see_friend(friends_last_seen, 'Rolf')
print(friends_last_seen)
print(id(frien... |
bil = int(input("Masukan Bilangan : "))
if (bil % 2 == 0):
print(bil, "Bilangan genap")
else:
print(bil, "Bilangan Ganjil")
|
# %% codecell
import os
import numpy as np
import matplotlib.pyplot as plt
import keras
import tensorflow as tf
from sklearn.metrics import confusion_matrix
from sklearn.metrics import precision_recall_curve
import random
import time
from sklearn.model_selection import train_test_split
import datetime
from scipy.... |
# -*- coding: utf-8 -*-
'''
Basic pie plot.
'''
import matplotlib.pyplot as plt
class Pie(object):
'''
Wrapper used to draw a plot containing basic pie chart.
'''
def __init__(self, figure, title, axis_size_rectangle=None):
if title is not None:
figure.suptitle(title)
if... |
class DataReader(object):
def __init__(self, lines, test_proportion, required_inputs, required_outputs):
inputs = []
outputs = []
rejected = []
ok_count = 0
def split_to_floats(txt):
return map(float, txt.split(','))
def is_comment(line):
... |
# -*- coding: utf-8 -*-
"""
<DefineSource>
@Date : Fri Nov 14 13:20:38 2014 \n
@Author : Erwan Ledoux \n\n
</DefineSource>
A Figurer
"""
#<DefineAugmentation>
import ShareYourSystem as SYS
BaseModuleStr="ShareYourSystem.Standards.Viewers.Viewer"
DecorationModuleStr="ShareYourSystem.Standards.Classors.Classer"
SYS... |
from flask import Flask
from app.models import db
def create_app():
app = Flask(__name__)
app.config.from_pyfile('config/dev.py')
app.config['SQLALCHEMY_DATABASE_URI'] = app.config['DB_CONN']
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
from app.routes import about, home, contact, api
... |
# Author Fakhir Khan
from dict_config_parser import ConfigParser
def test():
default_values = {'Datasets': ['VOC', 'COCO'],
'Model': ['MODEL_PATH'],
'RESULT': ['RESULT_FOLDER_PATH', 'DATASET_TRAIN_CSV', 'DATASET_TEST_CSV']}
config = ConfigParser(config_file='confi... |
#!/usr/bin/env python
"""Tests for SequentialCollection and related subclasses."""
from grr.lib import aff4
from grr.lib import rdfvalue
from grr.lib import test_lib
from grr.lib.aff4_objects import sequential_collection
class TestSequentialCollection(sequential_collection.SequentialCollection):
RDF_TYPE = rdfvalu... |
#!/usr/bin/env python
#
# LSST Data Management System
# Copyright 2014 LSST Corporation.
#
# This product includes software developed by the
# LSST Project (http://www.lsst.org/).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as publis... |
from django.urls import path
from . import views
urlpatterns = [
path('session/create/', views.createToyNetSession, name='toynetsession-create'),
path('session/show/<int:pk>/', views.showToyNetSession, name='toynetsession-show'),
path('session/visualize/<int:pk>', views.visualizeToyNetSession, name='toynet... |
from torch import nn, Tensor
class Net(nn.Module):
def __init__(self):
super(Net, self).__init__()
self.layers = nn.Sequential(
nn.Linear(1, 10),
# nn.Tanh(),
nn.Linear(10, 10),
nn.Tanh(),
# nn.Dropout(p=0.2),
nn.Linear(10, ... |
#################################################################################################
#Jonathan Medina Morales #
#This program is part of a the challenge programs for CODE2040's applications in November 2014 #
#It receives a string from the CODE2040 coding challenge API and then reverses t... |
D_month = {1: '01', 2: '02', 3:'03', 4: '04', 5: '05', 6: '06', \
7: '07', 8: '08', 9: '09', 10:'10', 11: '11', 12: '12'}
D_days = {1: 31, 2: 28, 3: 31, 4: 30, 5: 31, 6: 30, \
7: 31, 8: 31, 9: 30, 10: 31, 11: 30, 12: 31}
class DaysInYear:
def __init__(self, year):
self._year = year
... |
from shutil import copy2
import os, errno
subjects = []
folders = []
with open("folders.txt") as folders_file:
for folder in folders_file:
folders.append(folder.strip('\r\n'))
with open("subjects.txt") as subject_file:
for subject in subject_file:
subjects.append(subject.strip("\r\n"))
def ... |
#!/usr/bin/python
import sys
import random
import math
from Crypto.Cipher import DES,AES
import time
import hashlib
########## Otworzenie pliku ############
plain = open(sys.argv[1])
haslo = sys.argv[2]
random.seed(time.time())
import sys, re, string
import math
def histogram(data):
total = 0.0;
stat = {}
for line... |
from flask import (
Blueprint,
render_template,
redirect,
url_for,
request,
)
import json
from flask_login import login_required, current_user
from nokkhum import models
module = Blueprint("maps", __name__, url_prefix="/maps")
@module.route("/", methods=["GET"])
@login_required
def index():
r... |
import tkinter as tk
from tkinter import ttk
from discus_convert import *
def discus_rad_menu(parent, nwave, radiation, wvle, ener, ElementNumber,
adp, ano, pos_row, pos_col):
parent.label_rad = ttk.Label(parent, text='Radiation:')
parent.rad_type = tk.IntVar()
par... |
#!/usr/bin/python
#
# This script reads continuosly the log file
# and if the read line matches one of the pattern in
# matching_pattern then a mail is sent to the recipient.
#
# Script written by Antonio Aloisio <gnuton@gnuton.org>
# Copyright 2014 - License GPL
#
import os, sys, time
import smtplib
import re
logfi... |
class Solution(object):
def checkSubarraySum(self, nums, k):
res = {0: -1}
sum = 0
for i in range(0,len(nums)):
sum += nums[i]
if k != 0:
sum = sum % k
if sum in res:
if i - res[sum] > 1:
return ... |
__author__ = 'Javier & Manuel C. D.'
"""
1, 2, fizz, 4, buzz, fizz, 7, 8, fizz,....., fizzbuzz
0 -> []
1 -> [1]
2 -> [1, 2]
3 -> [1, 2, Fizz]
Escribir prueba y ver que falla -> Escribir mínimo código y ver que TODAS las pruebas pasan -> Refactorizar
Babystep
"""
"""
EJERCICIO SOBRE LA KATA DEL HANGOUT
Solución... |
from django.conf.urls.defaults import *
from app1.views import archive,show_404
urlpatterns = patterns('',
url(r'^$',archive),
url(r'^404$',show_404),
)
|
table1 = {2: [1, 2, False, 0, 0], 6: [5, 6, False, 0, 0], 7: [8, 7, False, 0, 0]}
table2 = {1: [1, 1, False, 0, 0], 3: [3, 3, False, 0, 0]}
table3 = {2: [3, 2, False, 0, 0], 4: [4, 4, False, 0, 0]}
table4 = {3: [4, 3, False, 0, 0], 5: [2, 5, False, 0, 0], 7: [6, 7, False, 0, 0]}
table5 = {4: [2, 4, False, 0, 0], 6: [1,... |
a = int(input())
b = int(input())
c = int(input())
n = 0
lst = [a, b, c]
lst.sort()
for count in range(3):
if lst[n] == a:
a = str(3-n)
elif lst[n] == b:
b = str(3-n)
elif lst[n] == c:
c = str(3-n)
n += 1
print(a+"\n"+b+"\n"+c) |
from ..fractions.fractionClass import fraction
def am(l):
if len(l) == 0:
raise ValueError("There is no average of an empty list")
s = 0
for i in l:
s += i
return fraction(s, len(l))
def gm(l):
if len(l) == 0:
raise ValueError("There is no average of an empty list")
p =... |
""" Graph.Algorithms
Various algorithms which work themselves upon the appropriate
GraphRepresentations to make them fast(ish)
*DFS and topoSort implementations originally Copyright (C)*
*the Python Mission Control Kit team*
"""
from Combinatoric import BayesAdjacency
from Data import AdjacencyList, EdgeList, Ve... |
from random import *
print("TESTE")
from numpy import *
print("TESTE")
num_de_pontos = input("Digitar o número de pares de pontos aleatórios que deverão ser gerados: ")
num_de_pontos = int(num_de_pontos)
print("n | " + "x(1) | " + "x(2) | ")
n = 0
distancia = zeros(num_de_pontos)
while n <= num_de_pontos - 1:
... |
#1041. Robot Bounded In Circle
#On an infinite plane, a robot initially stands at (0, 0) and faces north. The robot can receive one of three instructions:
#"G": go straight 1 unit;
#"L": turn 90 degrees to the left;
#"R": turn 90 degrees to the right.
#The robot performs the instructions given in order, and repeats th... |
import copy
from math import floor
from graphics import *
from time import sleep
Board = []
xCount = 0
oCount = 0
def printBoard(Board):
global xCount, oCount
xCount = 0
oCount = 0
#print("\n "),
for i in xrange(len(Board)):
pass
#print(i),
#print
for i in xrange(len(B... |
import random
# Task
# The provided code stub reads two integers from STDIN, a and b. Add code to print three lines where:
# The first line contains the sum of the two numbers.
# The second line contains the difference of the two numbers (first - second).
# The third line contains the product of the two numbers.
# Ex... |
def u(x):
if x<0 :
return 0
return 1
def pulse(x):
cnt = len(t)
y = np.zeros(cnt)
for i,v in np.ndenumerate(t):
if v < 0:
y[i] = 0
elif v > 2:
y[i] = 0
else:
y[i] = 2
return y
def negx(t):
cnt = len(t)
y = np.zeros(cnt)
for i,v in np.ndenumerate(t):
if v < 0:
y[i] = 0
elif v > 2:
... |
import os
os.environ['CUDA_DEVICE_ORDER'] = 'PCI_BUS_ID'
import sys
import argparse
import numpy as np
import torch
import torch.nn as nn
from autoencoders import myUpSamplingAE
from data_io import read_image_list
from func import train
### データセットに応じてこの部分を書き換える必要あり ###
# 使用するデータセット
DATA_DIR = './datas... |
# -*- coding: utf-8 -*-
# @Time : 2018/10/23 17:21
# @Author : G.Hope
# @Email : 1638327522@qq.com
# @File : Spider_anjukeOldHouse.py
# @Software: PyCharm
import json
import requests
from bs4 import BeautifulSoup
# 获取网页
def get_html(url):
headers = {
"User-Agent": "Mozilla/4.0 (compatible; MSIE ... |
import unittest
import ddt
import requests
data1 = [{'assert': '成功'}, {'pageNo': 0, 'assert': 'success'},
{'pageNo': 1, 'assert': 'success'},
{'pagesize': 0, 'assert': 'success'},
{'pageSize': 3,'assert': 'success'}]
data2 = [{'pageSize': 'a','assert': 'Invalid parameter'},
{'pageNo'... |
import redis
# HostAddress=str(input())
# Port=int(input())#输入测试
# 建立连接
HostAddress = "127.0.0.1"
Port = 6379
r = redis.Redis(host=HostAddress, port=Port, db=0) # 指定0号数据库
# redis-py 使用 connection pool 来管理对一个 redis server 的所有连接,避免每次建立、释放连接的开销。
# 默认,每个Redis实例都会维护一个自己的连接池。
# 可以直接建立一个连接池,然后作为参数 Redis,这样就可以实现多个 Redis 实例共享... |
import sqlite3
connect = sqlite3.connect('dbase1') # подключение к БД или создание новой
cursor = connect.cursor() # курсор для создания SQL-инструкций
tblcmd = 'CREATE TABLE contacts (name char(30), phone int(12))' # SQL-инструкция: Создани... |
import uos
import uio
import ujson
import pyb
import lighting
usb_pyboard = pyb.USB_VCP()
SensorList = ['TOF0', 'TOF1', 'TOF2']
sw_send_to_terminal = True
def YoN_in_list(senser_name):
return senser_name in SensorList
def send_to_terminal(sensor_name, time, value):
# the form of the data sent to terminal... |
#import socks
#import socket
import time
import urllib2
import feedparser
import re
import csv
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from bs4 import BeautifulSoup
class scrape():
def scrapeapp(self, urls):
self.urls = urls
print "hello"
for url in urls:
print "Scrapi... |
from genderize import Genderize, GenderizeException
def test_integration():
"""
Integration test from the readme. Calls the real Genderize.io API server.
"""
expected_genders = {
'James': 'male',
'Eva': 'female',
'Thunderhorse': None,
}
actual_genders = dict((elem['name... |
import collections
def find_mis(ar1,ar2):
d=collections.defaultdict(int)
for num in ar2:
if num in d:
d[num]+=1
#else: #works if comment removed also
#d[num]=1 #not required as default dictionary works as it adds auto
for num in ar1:
if d[num]==0:
... |
"""
BSD 3-Clause License
Copyright (c) 2016-2019 Russ 'trdwll' Treadwell. All rights reserved.
"""
from django.db import models
from django.core.urlresolvers import reverse
class Post(models.Model):
title = models.CharField(max_length=128, unique=True)
slug = models.SlugField(max_length=128, unique=True)
body = mo... |
#!/usr/bin/env python3.6
# -*- Coding: UTF-8 -*-
"""
Translate logml file to database.
By: E. S. Pereira
Version: 0.0.1
Date: 22/08/2017
"""
from numpy import array
from .parser import Parser
class Compiler:
"""
Translate the logml file to prolog program
"""
def __init__(self, logml_file, pl_file):... |
import json # формат хранения данных
import os # работа с ОС (проход по файловой системе)
import re # работа с регулярными выражениями (для поиска ключевых слов в распознанном тексте)
import sys # работа с ОС на уровне командной строки
import logging # журнал работы (надо бы доделать)
from datetime import datetime ... |
class Solution(object):
def subarraysWithKDistinct(self, A, K):
"""
:type A: List[int]
:type K: int
:rtype: int
"""
class Window:
def __init__(self, A):
self.A = A
self.count = [0] * (len(A) + 1)
self.present = set()
self.left = 0
self.right = 0
... |
#!/usr/bin/env python3
"""
This script checksums, signs, and compresses malvarma-<version>.img, and
creates malvarma-<version>.tar.bz2.
The author's GPG signature is hardcoded below.
"""
import os
import shutil
import sys
import subprocess
if __name__ == "__main__":
if len(sys.argv) == 1:
print("Usage: ... |
from django.shortcuts import render
from rest_framework.generics import ListAPIView
from rest_framework.permissions import IsAuthenticated
from accounts.authentication import TokenAuthentication
from .models import TvShow
from .serializers import TvShowSerializer
# dev Token: 9e29971eebfdd1e7180eabb3f4b1545333a78f... |
from data.base_combined import combinedDict as combined
from data.base_tagged import tagDict as tagged
from data.base_words import wordDict as words
import operator
import itertools
ENTS = ["PER", "LOC", "ORG", "MISC", "O"]
def get_baseline_predictions(tests):
results = {
"PER": [],
"LOC": [],
"ORG": [],
"M... |
command = ''
while command != 'QUIT':
command = input(">").upper()
if command == 'HELP':
print("start - to start the car")
print("stop - to stop the car")
print("quit - to exit")
elif command == 'START':
print("Car started. Ready to go..!")
elif command == 'STOP'... |
from dqn.city import create_city
import time
from datetime import datetime
def random_dispatch(s):
"""
State input given by get_observation_verbose
"""
action = [] # action as the form driver's grid id, driver id, order's grid id, order id, order (for virtual)
for grid_id, state in s.items():
... |
# Problem #106
# Given an integer list where each number represents the number of hops you can make,
# determine whether you can reach to the last index starting at index 0.
#
# For example, [2, 0, 1, 0] returns true while [1, 1, 0, 1] returns false.
def is_end_reached(numbers):
index = 0
last_index ... |
import sys
import math
def isPalindrome(val):
if val // 100000 == val % 10 and \
val // 10000 % 10 == val % 100 // 10 and \
val // 1000 % 10 == val % 1000 // 100:
return True
else:
return False
def generatePalindromeList():
rtn = [101101]
for i in range(100, 1000):
... |
# importing required libraries
from bluetooth import *
import RPi.GPIO as GPIO
import threading
GPIO.setwarnings(False) # Ignore warning for now
GPIO.setmode(GPIO.BOARD) # Use physical pin numbering
# Set pin 8 to be an output pin and set initial value to low (off)
GPIO.setup(8, GPIO.OUT, initial=GPIO.LOW)
server_... |
# Make an array of dictionaries. Each dictionary should have keys:
#
# lat: the latitude
# lon: the longitude
# name: the waypoint name
#
# Make up three entries of various values.
waypoints = [
{
"lat": "40,7128 N",
"lon": "74.006 W",
"name": "New York City"
},
{
"lat": "48.8566 N",
"lon": "... |
import logging
import ply.yacc as yacc
from functools import partial
from rita.lexer import RitaLexer
from rita import macros
logger = logging.getLogger(__name__)
def stub(*args, **kwargs):
return None
def either(a, b):
yield a
yield b
def load_macro(name, config):
try:
return partial(... |
from django.contrib import admin
from . import views
from django.urls import path,include
urlpatterns = [
path('', views.front),
path('home/', views.home),
path('algo/', views.algo),
#path('live/',views.live),
path('live/liveres/',views.liveres),
path('home/bjp_inc/', views.bjp_inc),
path('... |
from django.contrib import admin
from django.urls import path, include
from django.conf.urls.static import static
from classification_of_manuscripts_v2 import settings
urlpatterns = [
path('admin/', admin.site.urls),
path('api/v1/', include('backend.api.v1.urls')),
path('about/', include('frontend.about.ur... |
import cv2
import numpy as np
from matplotlib import pyplot as plt
#membaca gambar
img = cv2.imread('contoh.png',0)
#konversi biner dengan threshold apabila minValue 127 dan MaxValue 255 pada sebuah pixel maka nilainya 1
ret, thresh = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY)
#membuat sebuah kernel 3x3 tipe 8bit... |
#!/usr/bin/python
from subprocess import Popen, PIPE
from time import sleep
import sys
import json
#Section for arguments
if len (sys.argv) != 2:
print
print "Usage: new-virtualmachine <vmType>"
print
sys.exit(1)
arg = sys.argv[1]
if arg.lower() == "linux":
blueprint = "a01d4fb8-27f3-4f41-8756-8dbb2167c8b8"
... |
# import a specific class
import HTMLTestRunner
# import multiple libs from specified folder
from sikuli import *
# import list of libs
import unittest, os, sys
# a small 'hack' to add to the classpath the one level up folder- optional, but useful
bdLibPath=os.path.abspath(sys.argv[0]+"..")
if not bdLibPath in sys.path... |
# Generated by Django 3.2 on 2021-05-08 03:39
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('hrms', '0010_alter_employee_emp_id'),
]
operations = [
migrations.AlterField(
model... |
#!/usr/bin/env python
#
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this file,
# You can obtain one at http://mozilla.org/MPL/2.0/.
import ctypes
import errno
import os
import platform
import re
import shutil
import stat
import ... |
import os
import shutil
import glob
import subprocess
import re
import io
import math
from tqdm import tqdm
from shutil import copy, copyfile, rmtree, make_archive, unpack_archive
from contextlib import redirect_stdout
from aligner.models import IvectorExtractor
from random import shuffle
from ..helper import thirdpar... |
import os
from flask import Flask
from flask_restful import Api
from flask_jwt import JWT
from security import authenticate, identity
from resources.user import UserRegister
from resources.item import Item, ItemsList
from resources.store import Store,StoreList
from db import db
app = Flask(__name__)
app.config['SQL... |
"""
All nuitka functions associated for TA
"""
import os
import sys
from setuptools import find_packages
from pkgutil import iter_modules
import dataclasses as dc
import importlib
import pathlib
import re
PACKAGES_DIRS = [
os.getcwd(),
'/opt/venvdm/lib64/python3.8/site-packages/',
'/opt/venvdm/src',
'/usr/lib/... |
import random
import levels as lvl
def computer_number(level):
number = random.randint( lvl.levels[level][1], lvl.levels[level][2] )
tries = lvl.levels[level][0]
return (number, tries)
|
from typing import Optional, Tuple
import httpx
from httpx import Response
from models.validation_error import ValidationError
api_key: Optional[str] = None
async def get_geo_ip_info(ip: str) -> dict:
url = f'http://ip-api.com/json/{ip}'
async with httpx.AsyncClient() as client:
resp: Response = awa... |
# Create your views here.
from django.views.generic import FormView, TemplateView
from .forms import RegistrationForm
from django.core.urlresolvers import reverse_lazy
from django.contrib.auth import get_user_model
User = get_user_model()
class RegistrationView(FormView):
template_name = "registration_form.html"
... |
from parser import news_parse
from tweet_parse import tweet_parse
news_parse.delay()
tweet_parse.delay()
|
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'rigidoBotonesConexion.ui'
#
# Created by: PyQt5 UI code generator 5.5.1
#
# WARNING! All changes made in this file will be lost!
import socket
import sys
import binascii
import threading
import numpy as np
import socket
import scipy.ndimag... |
import bs4
import requests
import pickle
import time
import redis
from random import choice
from celery.contrib import rdb
import string
TASK_CONFIGS = {
'themuse_entry_level_job_url' : 'https://api-v2.themuse.com/jobs?level=Internship&level=Entry Level&company=',
'themuse_all_level_job_url' : 'https://api-v2.the... |
from bs4 import BeautifulSoup
import requests
import json
import random
import time
from spider import myipAgent
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; rv:52.0) Gecko/20100101 Firefox/52.0',
}
cookie = {}
def choiceIP(ip_pool):
ip=random.choice(ip_pool)
proxy={'http':ip,'https':ip}
re... |
"""
--- Day 25: Combo Breaker ---
You finally reach the check-in desk.
Unfortunately, their registration systems are currently offline, and they cannot check you in.
Noticing the look on your face, they quickly add that tech support is already on the way!
They even created all the room keys this morning; you can take ... |
import pika
import os
credentials = pika.PlainCredentials('guest', 'guest')
connection = pika.BlockingConnection(pika.ConnectionParameters(host = '39.98.170.203',port = 5772,virtual_host = '/',credentials = credentials))
channel = connection.channel()
# 申明消息队列,消息在这个队列传递,如果不存在,则创建队列
channel.queue_declare(queue='hello')
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Mar 5 09:16:25 2019
@author: rutvik
"""
#Data Preprocessing
from keras.preprocessing.text import Tokenizer
from keras.preprocessing.sequence import pad_sequences
from keras.layers import Embedding,Input
from keras.models import Model
from keras.opti... |
import os
from flask import Flask, render_template, url_for, redirect
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
from forms import AddForm, DelForm # მოგვიანებით ამ ფორმებს შევქმნით და შემოვიტანთ forms.py-დან
app = Flask(__name__)
# Key for Forms
app.config['SECRET_KEY'] = 'mysecretkey... |
#------------------------------------------------------------------------------
# test_dm_parser.py - Test for the -dm parser module
#
# November 2015, Antony Wallace
#------------------------------------------------------------------------------
"""dm parser tests tests."""
__all__ = ()
import unittest
from .. im... |
from django import template
from blogdjango.apps.posts.models import Post
register = template.Library() #Para ser uma biblioteca de tags válida, o módulo deve conter uma variável do nível do módulo chamado register que é uma instância de template.Library, na qual todas as tags e filtros são registrados.
@register.i... |
from datetime import datetime, timedelta
from django.db import models
from shop.models import Product
# Create your models here.
ORDER_STATUSES=(
('NEW', "NEW"),
('CONFIRMED', "CONFIRMED"),
('EXPIRED', "EXPIRED"),
)
class Order(models.Model):
first_name = models.CharField(max_length=50)
last_name... |
from random import choice
class RandomWalk():
"""
Versão 2 do módulo random_walk, com modificações.
Exercício 15.4, Faça Vocẽ Mesmo, p.437
"""
def __init__(self, num_points=5_000):
"""Inicializa os atributos de um passeio."""
self.num_points = num_points
# Todos os passeio... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#from __future__ import division, with_statement
'''
Copyright 2013, 陈同 (chentong_biology@163.com).
===========================================================
'''
__author__ = 'chentong & ct586[9]'
__author_email__ = 'chentong_biology@163.com'
#==========================... |
import os
import sys
def menuMain():
plataforma = sys.platform
if plataforma == 'linux':
os.system('clear')
elif plataforma == 'win32':
os.system('cls')
else: # Para otros sistemas y variantes de Unix
print('ERROR AL LIMPIAR LA PANTALLA')
print("+------------... |
import sys
sys.stdin = open('공책구매.txt')
t = int(input())
for test_case in range(1, t+1):
N, M = map(int,input().split())
lst = [list(map(int,input().split())) for __ in range(M)]
print(lst)
lst.sort(key= lambda x: (x[1], x[2]))
print(lst)
|
from tkinter import *
from Employee.E_Movies import AddMovie
from Employee.E_Scheduling import Scheduling
from Customer.UserProfile import User
import os
class Home:
"""Home class: A Employee window.
- You can go to a different window:
* Home
* Movie
* Scheduling
... |
from classify import *
import math
##
## CSP portion of lab 4.
##
from csp import BinaryConstraint, CSP, CSPState, Variable,\
basic_constraint_checker, solve_csp_problem
# Implement basic forward checking on the CSPState see csp.py
def forward_checking(state, verbose=False):
# Before running Forward checking ... |
import os
import re
import click
from PyInquirer import (Token,ValidationError,Validator,print_json,prompt,style_from_dict)
import six
from pyfiglet import figlet_format
from utils.CreateTemplate import *
from core.Renderer.FileRenderer import *
try:
import colorama
colorama.init()
except ImportError:
co... |
"""Tools to extract sub-ontologies and reasoner tasks."""
import base64
import logging
import random
import re
import sys
import uuid
from collections import defaultdict
from dataclasses import dataclass, field
from enum import Enum
from pathlib import Path
from typing import (
Any,
ClassVar,
Iterable,
... |
import numpy as np
import matplotlib.pyplot as plt
class grid:
def __init__(self, dim, obstacles, additional_obstacles = []):
''' Initialize the components of grid '''
self.dim = dim
self.obstacles = np.array(obstacles)
self.additional_obstacles = np.array(additional_obstacles)
... |
COMPASS = [(0, 1), (1, 0), (0, -1), (-1, 0)]
with open('day01.txt') as f:
data = f.read().strip()
# data = "R2, L3"
# data = "R2, R2, R2"
# data = "R5, L5, R5, R3"
instructions = data.split(", ")
x, y = 0, 0
dir = 0
for instruction in instructions:
turn, steps = instruction[0], int(instruction[1:])
d = ... |
import requests
import datetime
class Video:
def __init__(self, url="http://localhost:5000", selected_video=None):
self.url = url
self.selected_video = selected_video
def create_video(self, title, release_date, total_inventory):
query_params = {
"title": title,
... |
# Copyright 2017-2019 Nativepython Authors
#
# 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... |
#!/usr/bin/python
import cgi,cgitb
import json
cgitb.enable()
print "Content-Type: text/html\n"
import urllib2
fs=cgi.FieldStorage()
location=fs.getvalue("location")
data=json.loads(urllib2.urlopen("http://maps.googleapis.com/maps/api/geocode/json?address="+location+"&sensor=true").read())
print json.dumps(data)
|
def login(context, username='test', password='test123'):
context.browser.get(context.server_address + "/login")
uname = context.browser.find_element_by_name('username')
passwd = context.browser.find_element_by_name('password')
login_button = context.browser.find_element_by_id('btn_login')
uname.clea... |
import imageio
import os
from os import listdir
from os.path import isfile, isdir, join
import sys
def main(argv):
if len(argv) == 2:
dir = argv[1]
title = os.path.splitext(os.path.basename(dir))[0]
else:
print ('usage:\n python images_2gif.py <pasta com imagens>')
... |
from bs4 import BeautifulSoup as bs
import requests
import csv
from csv import writer
import datetime
import schedule
import time
url = "https://www.carousell.sg/categories/cars-32/car-rental-singapore-1181/?sc=1202081422120a0c74696d655f63726561746564120208002a150a0b636f6c6c656374696f6e7322060a04313138313a0408bbe17242... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.