text stringlengths 8 6.05M |
|---|
from random import randint
from flask import Flask,render_template,request,redirect
from events import get_events
from search_parse import parse
app = Flask(__name__)
@app.route("/")
def main():
image = "bg/"+str(randint(0,59)+1)+".jpg"
calendar = get_events()
return render_template('index.html', events=ca... |
# Copyright 2021 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
import os
import re
import sys
from textwrap import dedent
import pytest
from pants.backend.python import target_types_rules
from pants.backend.python.goals import export
from pants.backe... |
"""
Setup for simstream module.
Author: Jeff Kinnison (jkinniso@nd.edu)
"""
from setuptools import setup, find_packages
setup(
name="simstream",
version="0.1dev",
author="Jeff Kinnison",
author_email="jkinniso@nd.edu",
packages=find_packages(),
description="",
install_requires=[
... |
import os
import sys
import subprocess
import shutil
import fam
sys.path.insert(0, 'scripts')
sys.path.insert(0, 'tools/raxml/')
import experiments as exp
import time
import saved_metrics
import run_raxml_supportvalues as raxml
import sequence_model
def run_pargenes(datadir, pargenes_dir, subst_model, samples, cores... |
import datetime
import random
import json
from typing import Callable, Iterable, TypeVar
T = TypeVar('T')
RANDOM_BASE = [
'0123456789',
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz',
]
def to_seconds(*, hours=0, minutes=0, seconds=0) -> int:
"""
>>> to_seconds(hours=1, minutes=1)
3660
... |
"""
multiple thread, multiple connections
"""
import threading
import mysql.connector
from random import uniform
from time import sleep
def read_user_from_db():
"""
read user info from db
"""
sleep(uniform(0, 1))
user_db = mysql.connector.connect(
host="localhost",
user="root",
... |
celsius = float(input("Please enter the temperature in Celsius: "))
fahrenheit = (celsius * 1.8) + 32
kelvin = celsius + 273.15
print('''\n%0.1f Celsius is equal to %0.2f degrees Fahrenheit.\n'''%(celsius, fahrenheit))
print('''\n%0.1f Celsius is equal to %0.2f Kelvin.\n'''%(celsius, kelvin)) |
EOF = 3
digits = set(list("0123456789"))
lettersdigitsunderscore = set(
list("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_0123456789")
)
letters = set(list("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"))
ws = set(list(" \t\n\r"))
badidentifiertoken = 1
class StreamReader:
def __init__(self, ... |
import Jetson.GPIO as GPIO
import time
from threading import Thread
def checkSuccess(target_time, output_pin):
global success
start=time.time()
while True:
current_time=time.time()
if (current_time-start>=target_time):
GPIO.output(output_pin,GPIO.LOW)
success = True
# time.sleep(1)
... |
#!/usr/bin/env python
# encoding: utf-8
"""
pageobj.py
Created by yang.zhou on 2012-09-17.
Copyright (c) 2012 zhouyang.me. All rights reserved.
"""
import logging
import time
import hashlib
import urllib
from datetime import datetime
from dateutil import parser
from dateutil import tz
def getMd5(st=''):
md5_st =... |
def substring(string):
if not string:
return ''
length = len(string)
longest_sub = 0
sub_strings = []
for a in xrange(length):
unique = set()
for b in xrange(a, length):
unique.add(string[b])
if len(unique) > 2:
break
if b +... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import _init_paths
from opts import opts
from detectors.detector_factory import detector_factory
if __name__ == '__main__':
opt = opts().init()
image_name = opt.image_name_path
Detector = detector_facto... |
# coding=utf-8
# Copyright 2021 The Google Research 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 applicab... |
from multiprocessing import Pool
import signal, os, time
def f(x):
print('hello',x)
return x*2
if __name__ == '__main__':
original_sigint_handler = signal.signal(signal.SIGINT, signal.SIG_IGN)
p = Pool(5)
signal.signal(signal.SIGINT, original_sigint_handler)
try:
res = p.map_async(f, r... |
# -*- coding: utf-8 -*-
"""
Created on Thu Oct 18 17:40:49 2018
@author: Cole Thompson
"""
import matplotlib.pyplot
from matplotlib.pyplot import *
import numpy
from numpy import *
x=arange(0,200.1,0.1)
y0=arange(0,200.1,0.1)
y1= 125 - x
y2= (200/1.3)-((1.2/1.3)*x)
xB= 20 + 0.0*y0
yB = 20 + 0.0*x
... |
from flask_pagedown.fields import PageDownField
from flask_wtf import FlaskForm
from wtforms import StringField, SubmitField, PasswordField, BooleanField, TextAreaField, SelectField
from wtforms import ValidationError
from wtforms.validators import DataRequired, Length, Email, Regexp, EqualTo
from app.models import Us... |
def chess(tr, tc, pr, pc, size):# 传入左上角的坐标,特殊点坐标,以及size
global mark
global table
mark += 1
count = mark
if size == 1:
return
half = size // 2
# 确认特殊点位置以及子问题大小,并解决另外三个子问题
if pr < tr + half and pc < tc + half:
chess(tr, tc, pr, pc, half)
else:
table[tr + half - ... |
from django.conf.urls import include, url
from django.contrib import admin
from django.conf import settings
from django.conf.urls.static import static
# from .home import views
urlpatterns = [
url(r'^$', include('home.urls', namespace="home")),
url(r'^stories/', 'home.views.verhalen'),
url(r'^overons/', ... |
import matplotlib.pyplot as plt
mes = ["enero","febrero","marzo","abril","mayo","junio","julio","agosto","septiembre","octubre","noviembre","diciembre"]
ingresos = ["350.000","780.00","230.000","650.000","500.00","800.00","150.000","450.000","900.000","750.000","970.00","450.000"]
plt.bar(mes,ingresos, width = 0.8, col... |
# -*- coding: utf-8 -*-
"""
Created on Tue Apr 3 14:17:35 2018
@author: xingxf03
"""
import numpy as np
from sklearn import datasets,model_selection
from sklearn.neighbors import KNeighborsClassifier
from sklearn.metrics import classification_report
mnist = datasets.fetch_mldata('MNIST original')
data,target = mnis... |
"""Main module for testing DecisionTreeClassifier, KNeighborsClassifier,
RandomForestClassifier and GaussianNB on LeafClassification problem from kaggle.
Usage:
python3 words.py <URL>
"""
import sys
from sklearn.preprocessing import StandardScaler
from sklearn.tree import DecisionTreeClassifier
from sklear... |
'''
---------------------------------------------------------------------------
arrayUtilities.py
Kirk D Evans 07/2018 kdevans@fs.fed.us
TetraTech EC for:
USDA Forest Service
Region 5 Remote Sensing Lab
script to: misc array and list function
know limitations: python 3.x
-----------------------... |
import os
import exputils
import shutil
def test_experimentstarter(tmpdir):
dir_path = os.path.dirname(os.path.realpath(__file__))
# change working directory to this path
os.chdir(dir_path)
############################################################################
## test 01 - serial
# c... |
# !/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2018/4/12 19:37
# @Author : Yunhao Cao
# @File : storage.py
from sqlalchemy import Column, Integer, String, DateTime, orm, create_engine
from sqlalchemy.ext.declarative import declarative_base
__author__ = 'Yunhao Cao'
__all__ = [
'Item',
'Column... |
#!/usr/bin/env python
# coding: utf-8
# Copyright (c) Qotto, 2019
""" Contain all StoreBuilder errors
"""
__all__ = [
'UninitializedStore',
'CanNotInitializeStore',
'FailToSendStoreRecord',
]
class UninitializedStore(RuntimeError):
"""UninitializedStore
This error was raised when store is not i... |
#!/usr/bin/env python3
#
# Auxiliary script for obtaining all inaugural speeches of all U.S.
# presidents from Wikipedia.
import re
import requests
from bs4 import BeautifulSoup
from urllib.parse import urljoin
def getName(title):
i = title.index("'")
n = title[:i]
n = n.replace(" ", "_")
return n
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from head import *
import ConfigParser
def read_config():
try:
config_inst = ConfigParser.ConfigParser()
config_inst.read('mushroom.conf')
####################################################
db_conn_info['HOST'] = config_inst.ge... |
#Orientaçao a objeto
class Carro():
#Construtor
def __init__(self, modelo = '', cor = '', velociadade = '', ano = ''): #self é o único parametro obrigatorio
self.modelo = modelo
self.cor = cor
self.velocidade = velocidade
self.ano = ano
def acelerar(self):
... |
# Generated by Django 2.2.2 on 2019-06-25 18:29
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('main', '0002_auto_20190625_2016'),
]
operations = [
migrations.AlterModelOptions(
name='history',
options={'get_latest_by': ... |
import pytest
import numpy as np
from numba import cuda
from libgdf_cffi import ffi, libgdf, GDFError
from .utils import new_column, unwrap_devary, get_dtype, gen_rand, fix_zeros
def test_cuda_error():
dtype = np.float32
col = new_column()
gdf_dtype = get_dtype(dtype)
libgdf.gdf_column_view(col, ... |
import knn
class Process:
def __init__(self,trainDataPath,testDataPath):
self.trainPath=trainDataPath
self.testPath=testDataPath
self.trainData=[]
self.trainDataPredict=[]
self.testData=[]
self.testDataPredict=[]
def process(self,path):
... |
import pickle, cv2, math, timeit, random, time, os
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
from pathlib import Path
from sklearn.neighbors import KNeighborsClassifier
def nothing(x):
pass
# - Find CONTOURS function
def find_contours(filename):
picture... |
from flask import Flask, render_template, request
from flask_googlemaps import GoogleMaps
from flask_googlemaps import Map, icons
import json
import pandas as pd
import requests
import geopandas as gpd
app = Flask(__name__)
markers = [{
"coords":{'lat': 38.694862, 'lng': -122.772130},
'iconImage':'http://maps.goo... |
def fourSum(nums, target) :
#头尾两个k、m的for循环,i、j从两端往中间逼近的双指针
nums.sort()#排序,便于去重
n=len(nums)
res=[]
for k in range(n-3):#k遍历
#print(nums[k])
if k>0 and nums[k]==nums[k-1]:continue #去重,取相等元素的第一个,取过的数不再取
for m in range(n-1,k+2,-1):
#print(nums[m])
if m<n-1... |
import albumentations
class DataTransformManager:
def __init__(self, used_img_size, final_img_size, transform_params, custom_additional_targets=None):
if custom_additional_targets is None:
custom_additional_targets = {"image2": "image", "image3": "image", "image4": "image"}
self._cust... |
"""
Drunken Python
Python got drunk and the built-in functions str() and int() are acting odd:
str(4) ➞ 4
str("4") ➞ 4
int("4") ➞ "4"
int(4) ➞ "4"
You need to create two functions to substitute
str() and int(). A function called int_to_str()
that converts integers into strings and a
function called str_to_int() t... |
from collections import defaultdict
# DFS에 필요한 데이터를 직접 생성하고, DFS를 진행하는 문제
def solution(begin, target, words):
# words 데이터 간의 연결 리스트 생성
Ldic = defaultdict(list)
words.append(begin)
for i in words:
for j in words:
check = 0
for n in range(len(j)):
if i[n] =... |
from __future__ import absolute_import
import glob
import logging
from dialog.configs import DialogConfiguration
from dialog.run_pipeline import create_dialog_agent, load_parsers
from log_analysis.argument_parser import model_on_logs_arguments_parser
from log_analysis.training_data_from_dialog import build_log_summar... |
import pygal
from data_visualization.die import Die
die1 = Die(8)
die2 = Die(8)
die3 = Die(8)
# Make some rolls and store the results in a list
rolls = [die1.roll() + die2.roll() + die3.roll() for roll_num in range(100000)]
# Analyze the results
frequencies = [rolls.count(value) for value in range(3, (die1.num_sides... |
""" Calc code example """
class Calc(object):
""" Calculator Class """
def __init__(self, first, second):
self._first = first
self._second = second
def sum_call(self):
""" Sum Def """
return self._first+self._second
def div_call(self):
""" Div Def """
... |
import sys
import pandas as pd
import util
import numpy as np
def answer(x):
if x is np.nan:
return 0
return 1
def loadorder(f, vali):
order = pd.read_csv(f)
v = set()
a = open(vali).read().split('\n')[:-1]
for line in a:
v.add(line)
order['ts'] = order['time'].apply(util.c... |
import logging
from schedule_matcher_bot import ScheduleMatchingBot
def main():
logging.debug('[start] Schedule-matching bot.')
schedule_matching_bot = ScheduleMatchingBot()
schedule_matching_bot.start()
if __name__ == '__main__':
main() |
num = str(int(input()))
reverse = int(num[::-1])
print(reverse)
|
# -*- CODING: PTYHON V2 -*-
from carizy.items import CarizyItem
from scrapy import Request
import scrapy
class CarizyspiderSpider(scrapy.Spider):
name = 'carizyspider'
#start_urls = ['http://www.carizy.com/voiture-occasion?page={i}'
allowed_domains = ['carizy.com']
custom_settings = {
'LOG_FILE': ... |
# 注意两条链表遍历完后还加出来的进位
# 需要额外补一个点
class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
h1, h2 = l1, l2
b = 0
head = ListNode(0)
pre = head
while h1 and h2:
node = ListNode(0)
node.val = (h1.val + h2.val + b) % 10
b... |
from rest_framework.response import Response
from rest_framework import status
def judger_account_required():
def decorator(func):
def _wrapped_view(request, *args, **kwargs):
if not request.user.is_authenticated:
return Response(
{'detail': 'Login required.... |
import collections
import os
import subprocess
import _pyterminalsize
_sources = ('environment', 'stdin', 'stdout', 'stderr', 'tput', 'fallback')
SizeSource = collections.namedtuple('SizeSource', _sources)(*_sources)
Size = collections.namedtuple('Size', ('columns', 'lines', 'source'))
def _from_tput():
# tput ... |
import math.pi
import numpy
#INPUTS: list of pairable vectors. Obj1 should be a list of vectors
#that you want to match to the corresponding obj2.
def vector_angle(v1, v2):
v1_u = v1 / numpy.linalg.norm(v1)
v2_u = v2 / numpy.linalg.norm(v2)
return numpy.arccos(numpy.clip(numpy.dot(v1_u, v2_u), -1.0, 1.0))
... |
#!/usr/bin/env python2
#
# The MIT License (MIT)
#
# Copyright (c) 2014 Fam Zheng <fam@euphon.net>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of
# this software and associated documentation files (the "Software"), to deal in
# the Software without restriction, including without lim... |
# @created 25-8-2015
# @author MCS
# @description comms.py module for high level communications between ESTR and PC
import serial # for UART hardware abstraction.
class Comms(object):
def __init__(self, COM_port, baudrate): # initialise the COMs port on the PC.
"""initialise the COMs port on the PC, and opens it.... |
#!/usr/bin/env python
import pygame
import mimo
from .BaseScene import SceneBase
from utils import utils
from utils import neopixelmatrix as graphics
from utils.NeoSprite import NeoSprite, AnimatedNeoSprite, TextNeoSprite, SpriteFromFrames
from utils import constants
# Boot Scene
# should reset all button and light... |
# -*- coding: utf-8 -*-
import babel.dates
import re
import werkzeug
import math
from werkzeug.datastructures import OrderedMultiDict
from datetime import datetime, timedelta
from dateutil.relativedelta import relativedelta
from odoo import fields, http, _
from odoo.addons.http_routing.models.ir_http import slug
fro... |
"""
DATASET GENERATION
"""
# IMPORTING LIBRARIES
# * General libraries
import cv2
import os
import glob
import pandas as pd
import numpy as np
import shutil
from shutil import copyfile
import argparse
# * ML specific libraries
import torch
import torchvision
from torch.utils.data import DataLoader
from skle... |
# Generated by Django 3.1.7 on 2021-03-19 21:53
import django.db.models.deletion
from django.db import migrations, models
import delivery.validators
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Courier',
... |
#coding=UTF-8
'''
Created on 2017年3月13日
@author: admin
'''
import os, os.path, datetime, locale
locale.setlocale(locale.LC_CTYPE, 'chinese')
base_dir = "D:\\apache-tomcat-7.0.6\\webapps\\"
l=os.listdir(base_dir)
l.sort(key=lambda fn: os.path.getmtime(base_dir+fn) if not os.path.isdir(base_dir+fn) else 0)
d=datetime.da... |
import collections
class TreeNode(object):
""" Definition of a binary tree node."""
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def levelOrder(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
""... |
import tensorflow as tf
import numpy as np
import os
import scipy.misc
# output_img = graph.get_tensor_by_name("output_img:0")
# x = graph.get_tensor_by_name("x:0")
# batch_size = graph.get_tensor_by_name("batch_size:0")
batch_size_now = 2
values = np.load('celeba_variables.npz')
sess = tf.InteractiveSession()
x... |
import numpy as np
import sys
sys.path.append('..')
from chap11.dubins_params import dubins_params
from message_types.msg_path import msg_path
class path_manager:
def __init__(self):
# message sent to path follower
self.path = msg_path()
# pointers to previous, current, and next waypoints
... |
import yaml
import os
import git
import logging
from .i_repository_parser import IRepositoryParser
class RosdistroRepositoryParser(IRepositoryParser):
"""
Pulls the rosdistro-package and gets all urls from the rosdistro files.
"""
def __init__(self, settings: dict):
"""
Creates a new ... |
'''
Another Lottery
Even in times of an economic crisis, people in Byteland still like
to participate in lotteries. With a bit of luck, they might get rid
of all their sorrows and become rich.
The most popular lottery in Byteland consists of m rounds. In each round,
everyone can purchase as many tickets as he wishes,... |
from selenium import webdriver
import pytest
from selenium.webdriver.common.by import By
sticker_new = "//*[@id='box-%s']//*[@class='product column shadow hover-light']//*[@title='%s']//*[@title='New']"
sticker_sale = "//*[@id='box-%s']//*[@class='product column shadow hover-light']//*[@title='%s']//*[@title='On Sale... |
"""
A simple Point class.
NOTE: This is NOT rosegraphics -- it is your OWN Point class.
Authors: David Mutchler, Valerie Galluzzi, Mark Hays, Amanda Stouder,
their colleagues and SOLUTION by Muqing Zheng. September 2015.
""" # DONE: 1. PUT YOUR NAME IN THE ABOVE LINE.
def main():
""" Calls the T... |
class User:
def __init__(self, name ,email):
self. name=name
self. email=email
self. account_balance=0
def make_deposit(self,amount):
self.account_balance+=amount
return self
def make_withdrawal(self,amount):
self. account_balance-= amount
return s... |
import unittest
from greeting.greeting import hello
class TestGreeting(unittest.TestCase):
def test_hello(self):
testparams = [
["Lilla", "Hello Lilla"],
["Béla", "Hello Béla"],
]
for name, greeting in testparams:
with self.subTest("Testing with data", i... |
from django.contrib.auth import get_user_model
from rest_framework import authentication, exceptions
from rest_framework.generics import *
from rest_framework.response import Response
from rest_framework import status
from rest_framework.views import APIView
from post_app.serializers import *
class PostCreateAPIVie... |
# -*- encoding:utf-8 -*-
# __author__=='Gan'
# Given n, how many structurally unique BST's (binary search trees) that store values 1...n?
# For example,
# Given n = 3, there are a total of 5 unique BST's.
# 1 3 3 2 1
# \ / / / \ \
# 3 2 1 1 3 2... |
x = memoryview(bytes(5))
print(x)
print(type(x)) |
import os
from bsm.util import ensure_list
from bsm.util import safe_rmdir
from bsm.util import safe_mkdir
from bsm.util import call_and_log
def run(param):
source_dir = param['config_package'].get('path', {}).get('source')
if not source_dir:
return {'success': False, 'message': 'Path "source" is not ... |
import random
def score(_goal, _user_input):
bulls_counter = 0
cows_counter = 0
for i in range(0, 4):
if _user_input[i] == _goal[i]:
cows_counter += 1
bulls_counter -= 1
if _user_input[i] in set(_goal):
bulls_counter += 1
return cows_counter, bul... |
#!/usr/bin/python3
'''
contain teardown method
'''
from flask import Flask, jsonify
from models import storage
from api.v1.views import app_views
from flask_cors import CORS
import os
app = Flask(__name__)
CORS(app, resources={r"/*": {"origins": ["0.0.0.0"]}})
app.register_blueprint(app_views)
@app.errorhandler... |
import requests
from requests_toolbelt.multipart.encoder import MultipartEncoder
m = MultipartEncoder(
fields={
'file': ("test.cfg", open('test.cfg', 'rb'), 'text/plain')}
)
#print m.to_string()
r = requests.post('http://localhost:9000/upload', data=m,
headers={'Content-Type': m.c... |
# Copyright 2023 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import annotations
from pants.backend.python.subsystems.python_tool_base import PythonToolBase, get_lockfile_metadata
from pants.backend.python.util_rules.interpreter_cons... |
# -*- coding: utf-8 -*-
import yaml
from django import forms
import msrest
from azure.common.credentials import ServicePrincipalCredentials
from azure.mgmt.resource import ResourceManagementClient
from azure.mgmt.network import NetworkManagementClient
from azure.mgmt.compute import ComputeManagementClient
from azure.... |
import psycopg2
import win32com.client
import pythoncom
import time
#================== Database Connection =================== st
conn_string = "host='localhost' dbname ='Anthouse' user='blue1028' password='ehdghks57'"
try:
conn = psycopg2.connect(conn_string)
except:
print("error database connection"... |
import openpyxl
from openpyxl.chart import PieChart, Reference
wb = openpyxl.load_workbook("..\data\pie_chart.xlsx")
sh = wb.active
#print(sh.max_row)
data = Reference(sh, min_col=2, min_row=1, max_row=sh.max_row)
labels = Reference(sh, min_col=1, min_row=2, max_row=sh.max_row)
chart = PieChart()
chart.titl... |
import matcom.tools.edge_calculators as edg
import numpy as np
from matcom.pipelines.generate_structure_collection import FRAMEWORK_FEATURIZER
from collections import defaultdict
from dataspace.base import Pipe, in_batches
from dataspace.workspaces.remote_db import MongoFrame
from pymatgen.core import Structure
fr... |
if __name__=="__main__":
import pymysql
pymysql.install_as_MySQLdb()
from blog import db
from blog import User
db.create_all()
user1=User(username='Corey',email='c@gmail.com',password='1234')
db.session.add(user1)
db.session.commit()
print(User.query.all())
|
#Challenge: Implement a queue with two stacks.
class stack:
def __init__(self):
self.container = []
def __repr__(self):
return str(self.container)
def push(self, elem):
self.container.append(elem)
def pull(self):
return self.container.pop()
def peek(self):
r... |
from multiprocessing import Process
import time
import traceback
from logging import Logger
from core.schema import S1
from services import poller_worker
from services.service_base import ServiceBase
from utils import config
from core import Data
class Poller(ServiceBase):
def __init__(self, logger, name, data,... |
#!/usr/bin/env python
#
# ssl_sigs.py
# Create Suricata and Snort signatures to detect an inbound SSL Cert for a single domain.
#
# Mega thanks to Darien Huss[1] and his work on a DNS signature script which is where most of this code was ripped from. Another big thanks to Travis Green for assistance.
# [1]https://githu... |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... |
import requests
import bs4
#
# url = 'http://github.com'
# r = requests.get(url)
#
# r_html = r.text #r_html contain HTML
#
# soup = bs4.BeautifulSoup(r_html,features="lxml")
#
# title = soup.find('summary').text
#
# # print(r_html)
# print(title)
#
#
sauce = requests.get("https://niebezpiecznik.pl")
soup = bs4.Beaut... |
import pygame, sys, time, random
from pygame.locals import *
import numpy as np
class Particle:
"""
@summary: Data class to store particle details i.e. Position, Direction and speed of movement, radius, etc
"""
def __init__(self):
self.__version = 0
"""@type: int"""
self.__pos... |
import numpy as np
def is_pos_def(x):
return np.all(np.linalg.eigvals(x) > 0)
# Funcion que crea la matriz de H a utilizar en quadProg
# Q es una matriz cuadrada de (NxN)
# P es una matriz cuadrada de (NxN)
# R_i valor asociado a u
# N es el horizonte de prediccion
def Hqp(Q, P, R_1, R_2, N):
# Se consigue ... |
import os
import sys
path = '/var/django-apps/Mycompanytv'
if path not in sys.path:
sys.path.append(path)
os.environ['DJANGO_SETTINGS_MODULE'] = 'media_server.settings'
from django.core.wsgi import get_wsgi_application
application = get_wsgi_application()
|
from django.db import models
from django.contrib.auth.models import User
import datetime
from django.core.validators import MaxValueValidator, MinValueValidator
class Student(models.Model):
student_id = models.IntegerField(verbose_name='شماره دانش آموزی')
user = models.OneToOneField(User, on_delete=models.CAS... |
import random
from fxengine.event.event import SignalEvent
class TestRandomStrategy(object):
def __init__(self, events):
self.events = events
self.ticks = 0
random.seed(5)
def calculate_signals(self, event):
if event.type == 'TICK':
self.ticks += 1
if ... |
import subprocess as sp
import os
def get_test(id, rank):
sp.call("wget --load-cookies cookies.txt 'http://gpe2.acm-icpc.tw/domjudge2/pctjury/testcase.php?probid=%s&rank=%s&fetch=input' -O '%s/%s.in'"%(id, rank, id, rank), shell=True)
sp.call("wget --load-cookies cookies.txt 'http://gpe2.acm-icpc.tw/domju... |
def convert_hash_to_array(hash):
return sorted([[k,v] for k,v in hash.items()])
'''
Convert a hash into an array. Nothing more, Nothing less.
{name: 'Jeremy', age: 24, role: 'Software Engineer'}
should be converted into
[["name", "Jeremy"], ["age", 24], ["role", "Software Engineer"]]
Note: The output array sho... |
import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
#Loading the dataset
mnist = input_data.read_data_sets("MNIST_data/",one_hot=True)
n_nodes_hl1 = 100
n_nodes_hl2 = 100
n_nodes_hl3 = 100
n_nodes_hl4 = 100
n_classes = 10
batch_size = 100
# PLACEHOLDERS
x = tf.placeholder(tf.float32... |
from kivy.network.urlrequest import UrlRequest
def got_weather(req, results):
for key, value in results['weather'][0].items():
print(key, ': ', value)
if __name__ == '__main__':
ID = 5391811
URL = 'http://api.openweathermap.org/data/2.5/weather?q=San_Diego,CA&APPID='
req = UrlRequest(URL, got_we... |
from django import forms
class QuestionForm(forms.Form):
id=forms.IntegerField()
question=forms.CharField(required=True,max_length=100)
answer=forms.BooleanField(required=False)
comment=forms.CharField(required=True,max_length=100)
class DeleteForm(forms.Form):
id=forms.IntegerField()
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import operator
import os
# Start Functions
def clear():
'''
Clear console
'''
os.system('cls' if os.name=='nt' else 'clear')
def print_words(pos=False):
'''
Print words resolves
Arguments:
pos - View numbers
'''
print_pos = ' '
... |
#!/usr/bin/env python
from assignment1.srv import *
import rospy
def handle_task2(req):
if req.c==1:
return task2Response(req.a + req.b)
elif req.c==2:
return task2Response(req.a - req.b)
elif req.c==3:
return task2Response(req.a * req.b)
elif req.c==4:
return task2Response(req.a / req.b)
else... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import sys
import re
# safe print of possible UTF-8 character strings on ISO-8859 terminal
def cprint(s, end=None):
s = re.sub("◻","-ENSP-", s)
s = re.sub("◻"," ", s)
t = "".join([x if ord(x) < 128 else '?' for x in s])
if end != None:
print(t, end=end)
els... |
from typing import Text
from django.urls import path
from .views import *
urlpatterns = [
path('',home, name='dashboard'),
path('test',test),
path('help',help)
] |
import sys
print(sys.path)
name = "zhan"
age =19
job = "iT"
msg = '''
=============user name %s
yourname is: %s
your age is: %s
your job js: %s
''' % (name,name,age,job)
print(msg)
resArr = ['zhang','chaofu','age']
print(resArr)
print(resArr[0])
print(resArr[2])
print(resArr[1:3])
resArr.append("lai")
print(r... |
ARR = [3, 34, 4, 12, 5, 2]
S = 9
# 选或者不选
# Subset(arr[5], 9)
# ---
# 选 Sunbet(arr[4], 7) 不选 Subset(arr[4], 9)
def rec_subset(arr, i, s):
if s == 0:
return True
elif i == 0:
return arr[0] == s
elif arr[i] > s:
return rec_subset(arr, i-1, s)
else:
A = rec_sub... |
import pickle
class PickleData:
def __init__(self,fil):
self.file = fil
def dump_object(self,obj):
with open(self.file,'wb') as destination:
pickle.dump(obj,destination)
def depickle(self):
with open(self.file,'rb') as f:
Pikl = pickle.load(f)
return P... |
# Copyright 2018 Cable Television Laboratories, Inc.
#
# 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... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.