text stringlengths 38 1.54M |
|---|
#!C:\Python\Python
#coding=utf-8
'''
PowerSet
Write a function that takes in an array of unique integers and returns its powerset.
The powerset P(x) of a set x is the set of all subsets of x. For example, the powerset
of [1,2] is [[], [1], [2], [1,2]]. Note that the sets in the powerset do not need to be in any par... |
import os
import tempfile
import pytest
from flask import g
from flask import session
from Website.project import app
# data for login:
username = 'Oliver'
password = 'Oliver'
@pytest.fixture
def client():
"""The client can trigger test requests to the application.
Will be called by each test.
The t... |
__author__ = 'Tony'
import requests
#url = 'http://stats.moe.gov.tw/files/school/101/u1_new.csv'
url = 'https://raw.github.com/moskytw/learning-python-from-data-examples/master/sql/schools.csv'
#print requests.get(url).content
print requests.get(url).text |
import networkx as nx
from Utils import *
class ParseGraph:
node_num = 0
succs = []
attribute = {}
methodName = ""
Version = ""
callMethodNameReferTo = {}
g = nx.DiGraph()
def __init__(self, method): # json格式
self.node_num = method["num"]
self.succs = method["succs"]
... |
#!/usr/bin/python
import sys, re, struct
print 'KeepassX file extract from dump'
if len(sys.argv) != 2:
print "%s <procdump>" % sys.argv[0]
f = open(sys.argv[1], 'r')
data = f.read()
f.close()
cpt=1
for m in re.finditer(b"\x03\xd9\xa2\x9a\x65\xfb\x4b\xb5", data):
print '%08x-%08x: %s' % (m.start(), m.end()... |
import os
from unittest import mock
from tornado.testing import AsyncTestCase, gen_test
from tornado_sqlalchemy import as_future, set_max_workers
from ._common import db, User, mysql_url
set_max_workers(10)
os.environ['ASYNC_TEST_TIMEOUT'] = '100'
class ConcurrencyTestCase(AsyncTestCase):
session_count = 10
... |
from django.conf.urls import url
from apps.wechat.views import verify
app_name = 'wechat'
urlpatterns = [
url(r'^verify/$', verify, name='verify'),
]
|
from app import db
import datetime
class Subscriber(db.Model):
__tablename__ = 'subscriber'
id = db.Column(db.Integer, primary_key=True)
email = db.Column(db.String())
name = db.Column(db.String())
is_confirmed = db.Column(db.Boolean())
date_confirmed = db.Column(db.DateTime())
def __init... |
import numpy as np
import pandas as pd
def find_words(y):
"""
Show two words that correspond with the face image taken by webcame
Parameters
----------
y : ndarray
of length 2 (coordinates of face)
returns
-------
words : List[str]
Two words that correspond with a fa... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# @File : 65.py
# @Author: guolei
# @Time : 02/05/2019 5:46 PM
# @Desc :有效数字
# @Ans :如果遍历方式比较麻烦。直接调用系统函数出结果
class Solution(object):
def isNumber(self, s):
"""
:type s: str
:rtype: bool
"""
try:
float(s)
re... |
import os
from pathlib import PurePath, Path
import xraylib as xrl
import shutil
import getpass
import smtplib
from email.message import EmailMessage
from PyMca5.PyMca import McaAdvancedFitBatch
import h5py
from glob import glob
import subprocess
from datetime import datetime
EDGE_MAPPER = {
'K': xrl.K_SHELL,... |
# Copyright (c) 2011 The LevelDB Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file. See the AUTHORS file for names of contributors.
{
'variables': {
'conditions': [
# Define an "os_include" variable that points at the OS-speci... |
import os
import tempfile
from subprocess import check_output
from environments import VRPSolver
from instances import VRPSolution, Route, VRPInstance
from utils.vrp_io import write_vrp, read_solution, read_vrp
class LKHSolver(VRPSolver):
def __init__(self, executable: str):
super().__init__("LKH")
... |
# my_set_2={1,2,3,4,5,6,2,7,9,8}
#
#
# res=my_set_2.discard(2)
# print(res)
#小海龟
#运动命令 forward;向前运动 backward;向后运动
#right向右, left 向左转多少度
#goto 移动到坐标为(x,y)的位置
#speed 向左笔画移动速度
#up 笔画抬起
#down 笔画落下
#pensize()
#pencolor()
#setheading()改变海归的朝向
#绘图窗口的零点在正中间,默认海归方向向右
import turtle
turtle.forward(100)
turtle.right(45)
turt... |
from django.shortcuts import render
from .models import pt
from .serializers import ptSerializer
from rest_framework.response import Response
from rest_framework.views import APIView
class ptView(APIView):
def get(self,request):
data = pt.objects.all()
serializer = ptSerializer(data,many=True)
... |
from django.db import models
from polymorphic.manager import PolymorphicManager
from shop.models.productmodel import Product as ProductShop
from filer.fields.image import FilerImageField
from django.core.urlresolvers import reverse_lazy as reverse
class Category(models.Model):
name = models.CharField(max_leng... |
def main_testing():
'''cd /Users/kentchiu/Night_Graden/Project/2016_MIT/Auto_HOG_SVM/'''
from common_tool_agent.common_func import non_max_suppression
from common_tool_agent.conf import Conf
from common_tool_agent.descriptor_agent.hog import HOG
from common_tool_agent.detect import ObjectDetector
... |
#Q.1- Write a python script to create a databse of students named Students.
import sqlite3
try:
con=sqlite3.connect('student.db')
cursor=con.cursor()
query='create table student(name varchar(10),marks int(3))'
cursor.execute(query)
print('table created')
con.commit()
except sqlite3.DatabaseErro... |
#Circular Photometry
#Libraries
import numpy as np
from astropy.io import fits
from math import sin,cos,tan,atan2,sqrt,pi,radians as rad, degrees as deg, log10
#Inputs
im = "aptest.FIT" #input("Image file name:")
im = fits.getdata(im)
x = 490 #int(input("x:"))
y = 293 #int(input("y:"))
rAperture = 5 #int(input("Apert... |
x = float(input())
y = float(input())
def IsPointInSquare(x, y):
return (-1 <= x <= 1) and (-1 <= y <= 1)
print('YES' if IsPointInSquare(x, y) else 'NO')
|
# -*- coding: UTF-8 -*-
import os
import sys, getopt, getpass
from jira import JIRA
from jira import JIRAError
import logging
from datetime import date, timedelta, datetime
import hashlib
import difflib
import re
import requests
proxies = {
}
cmc_jira_server_url = 'https://jira.sss.com'
log = logging.getLogger... |
import math
def pythonfunction(x):
return (math.sqrt(3-(5*x)+(x**2)+(x**3))/(x-1))
print("from the left")
print("As x -> 1^-")
print(pythonfunction(0))
print(pythonfunction(.5))
print(pythonfunction(.9))
print(pythonfunction(.99))
print(pythonfunction(.999))
print(pythonfunction(.9999))
print(pythonfunction(.99999))... |
from monkey.ast import Program, LetStatement, Identifier
from monkey.token import Token, TokenType
import unittest
class TestAST(unittest.TestCase):
def test_string(self):
program = Program()
statement = LetStatement(Token(TokenType.LET, "let"))
statement.name = Identifier(Token(TokenTyp... |
default_value = '1000'
cache = { 'HP': 56, 'APPLE': 700 }
def get_from_cache(key):
# upon failure to get hit error will be thrown
return cache[key]
def get_from_cache_by_get_api(key):
return cache.get(key)
def get_or_default(key, use_get_api = False):
if use_get_api:
v = get_from_cache_by_ge... |
# --------------------------------------------------- #
# IMPORT STATEMENTS
# --------------------------------------------------- #
import tensorflow as tf
from tensorflow.contrib import rnn
import sys
import os
import numpy as np
import matlab_ops as mo
import utils as u
import features as f
# disable tensorflow log... |
#!/usr/bin/env python
import sys
import os
import rdflib
try:
from termcolor import colored
except:
print "pip install termcolor"
def f(x,y, attrs=[]):
print x
colored = f
def printResults(res):
if len(res) > 0:
color = 'green'
else:
color = 'red'
print colored("->... |
# 其实也是哈希的思想
class Solution:
def reversePrint(self, head: ListNode) -> List[int]:
hashtable = []
while head:
hashtable.append(head.val)
head = head.next
return hashtable[-1::-1]
# 递归,感觉递归的本质就是栈,先进后出
class Solution:
def reversePrint(self, head: ListNode) -> List[... |
#CloseMainWindow.py
from PyQt5.QtWidgets import QMainWindow,QHBoxLayout,QPushButton,QApplication,QWidget
import sys
class WinForm(QMainWindow):
"""docstring for WinForm"""
def __init__(self, parent=None):
super(WinForm, self).__init__(parent)
self.setWindowTitle("CloseMainWindow") #set window title
self.resize... |
import os
import sys
import pdb
import pdb1
import pdb_c
import module
import make_lmode_file
import addKaTopdb
import xtb_lmode
import time
import addC
import addBCP
import addFreq
import addLPCont
import addCharges
import addRing
import addAngle
import addCR
import addBifr
import xlwt
def make_excel(d,filename):
... |
import gensim
import numpy as np
embedder = gensim.models.word2vec.KeyedVectors.load_word2vec_format('../lstm/GoogleNews-vectors-negative300.bin', binary=True)
import re
def calc_w2v_sim(question1,question2):
'''
Calc w2v similarities and diff of centers of query\title
'''
question1=re.sub(r'[... |
import os
import tarfile
from fnmatch import fnmatch
from .exceptions import ValidationException
from .utils import debug
class Workspace:
def __init__(self, workspace_config=None, context=None):
workspace_config = workspace_config or {}
self.path = workspace_config.get('path', os.getcwd())
... |
import numpy as np
def sentence_pre_process(sentence):
return str(sentence).lower()
def get_sentence_embedding(sentence, session, m, fasttext_model, max_word_length, char_vocab, rnn_state):
sentence = sentence_pre_process(sentence)
for word in sentence.split(' '):
words_tf = fasttext_model.wv[wo... |
class Shape(object):
"""Makes shapes!"""
def __init__(self, number_of_sides):
self.number_of_sides = number_of_sides
class Triangle(Shape):
def __init__(self, side1, side2, side3):
pass
|
#!/usr/bin/env python3
import sys
import matplotlib.pyplot as plt
target_start_sites = []
contig_start_sites = []
target_end_sites = []
contig_end_sites = []
list_ = []
contig_dict = {}
for line in open(sys.argv[1]):
if line.startswith("#"):
continue
fields = line.rstrip("\n").split()
# n... |
import copy
import random
# Consider using the modules imported above.
class Hat:
def __init__(self, **kwargs):
ls = [[key]*value for key, value in kwargs.items()]
self.contents = [item for sublist in ls for item in sublist]
def draw(self, n):
if n > len(self.contents):
ret... |
# coding=utf-8
# Copyright (c) 2015 EMC Corporation.
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
#... |
import configparser
from pathlib import Path
from typing import Dict, Union
class Config(object):
"""read/write config.ini"""
def __init__(self, config_path: 'Path'):
"""read configuration from config_path
caller must guarantee that all parents of config_path has been created
"""
... |
# https://www.urionlinejudge.com.br/judge/pt/problems/view/1008
NUMBER = int(raw_input())
HORAS = int(raw_input())
RECEBE = float(raw_input())
SALARY = RECEBE*HORAS
print "NUMBER = %d"%(NUMBER)
print "SALARY = U$ %.2f"%(SALARY)
|
from cloudshell.cli.command_template.command_template import CommandTemplate
from cloudshell.cumulus.linux.command_templates import ERROR_MAP
FIRMWARE_ERROR_MAP = {r"[Ff]ailure|[Ee]rror": "Failed to load firmware"}
FIRMWARE_ERROR_MAP.update(ERROR_MAP)
LOAD_FIRMWARE = CommandTemplate(
"onie-install -fa -i {image... |
from django.contrib import admin
from .models import Page, TextPage, ResourcePage, ResourceListing
# Register your models here.
admin.site.register(Page)
admin.site.register(TextPage)
admin.site.register(ResourcePage)
admin.site.register(ResourceListing) |
import unittest
from unittest.mock import patch
from buzz.corpus import Corpus
from buzz.table import Table
TOTAL_TOKENS = 329
STRUCTURE = dict(first="one", second="second", third="space in name")
BOOK_IX = [("second", 1, 6), ("space in name", 3, 2), ("space in name", 4, 12)]
LOADED = Corpus("tests/testing-parsed... |
# Librerias Django
from django.contrib.auth.models import User
from django.db import models
from django.urls import reverse
from django.utils.translation import ugettext_lazy as _
STATE = (
("draft", "Borrador"),
('posted', 'Validado'),
)
# Tabla de Leads
class PyAccountMove(models.Model):
cod... |
# Copyright (C) 2018 Lecida Inc
# All Rights Reserved.
#
# NOTICE: All information contained herein is, and remains the property of
# Lecida Inc. The intellectual and technical concepts contained herein are
# proprietary to Lecida Inc and may be covered by U.S. and Foreign Patents,
# patents in process, and are protec... |
'''
VM201RelayCard class.
Software representation of the VM201 Ethernet Relay Card.
Author: Timo Halbesma
Date: October 11th, 2014
Version: 2.0: Read TCP responses; send TCP packet to login and request status.
'''
from sys import exit
from socket import socket, AF_INET, SOCK_STREAM, gaierror, error, gethostbyname
f... |
import sys
input = sys.stdin.readline
n = int(input())
lst = []
for _ in range(n):
lst.append(input().split())
lst.sort(key=lambda x:x[0])
lst.sort(key=lambda x:int(x[3]), reverse = True)
lst.sort(key=lambda x:int(x[2]))
lst.sort(key=lambda x:int(x[1]), reverse = True) # 숫자 string가지고 비교할 수 x '3'>'100' and '1'<'3'... |
# -*- coding: utf-8 -*-
"""
Created on Fri Nov 22 22:06:06 2019
@author: kocak
"""
import pandas as pd
f = open("C:/Users/kocak/OneDrive/Masaüstü/reag/oct24.csv","w")
f.write((("`SEQUENCE_ID`, `PACKET_ID`, `ARAC_NO`, `TARIH_SAAT`, `UYDU_SAYISI`, `ENLEM`, `BOYLAM`, `HEADING`, `HIZ`, `HAT_NO`, `SURUCU_NO`, `INSERT_TARIH... |
# 把三国集团的数据,存在Excel表里。
import xlwt
import DBUtils
sql = "select * from t_employees"
param = []
db = DBUtils.select(sql, param)
lt = []
# print(db)
wb = xlwt.Workbook()
st = wb.add_sheet("t_employees")
for t in db:
L = list(t)
lt.append(L)
for i in range(len(lt)):
for j in range(len(lt[i])):
st.wri... |
# Generated by Django 3.1.11 on 2021-05-18 03:28
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('flex', '0011_auto_20201013_1352'),
]
operations = [
migrations.AddField(
model_name='flexpage',
name='keywords',
... |
#!/usr/bin/env python
import python
from const import *
'''
@desc Class for stuff like ladders, ropes, elevators,
vehicles, and such
'''
class Base(pygame.sprite.Sprite):
def __init__(self, pos, imgPath):
self.pos = pos
self.x, self.y = pos
self.image = pygame.image.load(imgPath)
self.r... |
# -*- coding: utf-8 -*-
import os
from . import controllers
from . import models
os.system('babel /home/lalit/odoo-11.0/customaddons/externalapi/static/src/js/source.js --out-file=/home/lalit/odoo-11.0/customaddons/externalapi/static/src/js/app.js --presets=env,react') |
import re
from flask import Flask
from flask_bootstrap import (Bootstrap, get_bootstrap_version,
BOOTSTRAP_VERSION_RE, BOOTSTRAP_VERSION)
import requests
import pytest
@pytest.fixture
def app():
app = Flask(__name__)
Bootstrap(app)
return app
@pytest.fixture
def client(app... |
t = int(input())
while(t!=0):
n,m,s = map(int,input().strip().split())
if(s + m < n):
print(s + m - 1)
elif((s+m-1)%n == 0):
print(n)
else:
print((s+m-1)%n)
t-=1 |
from ptflops import get_model_complexity_info
from model.segmentation.deeplabV3_plus import DeepLabV3_plus
if __name__ == '__main__':
print('================================================================================')
print('DeepLab V3+, ResNet, 513x513')
print('=====================================... |
# Chapter 9. Machine Learning for Time Series
from cesium import datasets
from cesium import featurize
import time
eeg = datasets.fetch_andrzejak()
import matplotlib.pyplot as plt
plt.subplot(3, 1, 1)
plt.plot(eeg["measurements"][0])
plt.legend(eeg['classes'][0])
plt.subplot(3, 1, 2)
plt.plot(eeg["measurements"][300]... |
import json
import pytest
from datetime import datetime, timedelta
from CommonServerPython import EntryType
BASE_URL = 'https://test.cyberint.io/alert'
DATE_FORMAT = '%Y-%m-%dT%H:%M:%SZ'
def load_mock_response(file_name: str) -> str:
"""
Load one of the mock responses to be used for assertion.
... |
# IF Statements
x=5
if (x==5):
print("The X is equal to 5")
elif(x>5):
print("X is greater than 5")
else :print ("NOT APPLICABLE")
#####################################
x=100
if(x>5):
print("The X is greater than 5")
if(x==5):
print("The X is equal to 5")
|
import sys
def song():
while True:
print(
' 1.Alone\n 2.BoneyM_Rasputin\n 3.Beliver\n 4.Dance_Monkey\n 5.Falling\n 6.Memories\n 7.Show_me_the_meaning\n 0.To change the Album\n *.EXIT')
print('-' * 60)
song = input("Please Choose the song:--")
if song == '1':
... |
from selenium import webdriver
from datetime import datetime as d
from datetime import timedelta as td
import argparse
parser = argparse.ArgumentParser(description='look for bargain flights')
parser.add_argument('-d', '--departuredate', metavar='', required=False, help="date of departure | yyyy-mm-dd | default is t... |
# def open_file(file_name):
# try:
# file = open(file_name,'r')
# except IOError:
# print(f"No such file with name {file_name}")
# else:
# print(file.read())
# file.close()
# finally:
# print("Finished block")
#
# open_file('names1.txt')
# -----------------------... |
# a function that will return only the current date
#a function that will return the current year
# a function that will return the timestamp
# a function that will return the current month
# a function that will return me the current day(sunday - saturday) |
filter1 = lambda x: any([x[i] == x[i+2] for i in range(len(x)) if i < len(x)-2])
filter2 = lambda x: any([x[i]+x[i+1] in x[i+2:] for i in range(len(x)) if i + 2 < len(x)])
print(len(list(filter(
filter1,
filter(
filter2,
open("day5.txt", "r").readlines()))))) |
import socket
from io import BytesIO
from flask import Flask, render_template, request
from PIL import Image
app = Flask(__name__)
port = 5000
hostname = socket.gethostbyname(socket.gethostname())
@app.route("/")
@app.route("/index")
def show_index():
return render_template("/index.html")
@app.route("/image",... |
import dash_core_components as dcc
import dash_html_components as html
from dash_frontend.server import app
from dash.dependencies import Input, Output, State
from external_database_connections.neo4j.neo4j import Neo4j
graph_db = Neo4j("ldbcsf1")
def create_neo4j_query_tool():
return html.Div(id = "neo4j-main-que... |
from aiogram.types import Message, CallbackQuery, Update
from aiogram.contrib.middlewares.context import ContextMiddleware
from aiogram.dispatcher import CancelHandler
from core.models import get_user
import datetime
import core.utils.timezone as utils_timezone
import gettext
_ = gettext.gettext
class PrepareMiddlewa... |
# Generated by Django 2.1.2 on 2018-10-02 11:23
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('paytm', '0002_paytmdatabase_checksumhash'),
]
operations = [
migrations.AddField(
model_name='paytmdatabase',
name='... |
import numpy as np
from numba import jit
from projection import cross, norm
@jit(nopython = True)
def _init_seed():
np.random.seed(1234)
_init_seed()
@jit(nopython = True)
def binary_search(a, b):
lo = 0
hi = len(a) - 1
while lo < hi:
m = (lo + hi - 1) // 2
if a[m] < b:
... |
from tkinter import *
from tkinter import ttk
def showinfo(event):
print(cmb.get())
app=Tk()
app.geometry("300x300")
app.title("Simple App")
cmb=ttk.Combobox(app,values=['India','Bangladesh','Srilanka','Pakistan'])
cmb.place(x=0,y=20)
cmb.bind("<<ComboboxSelected>>",showinfo)
app.mainloop()
|
"""
Common Quantiles
One of the most common quantiles is the 2-quantile. This value splits the data into two groups of equal size. Half the data will be above this value, and half the data will be below it. This is also known as the median!
Ten points are below the median and ten points are above the median.
The 4-qua... |
# LINEAR REGRESSION
# Scikit-Learn
# Congratulations! You’ve now built a linear regression algorithm from scratch.
# Luckily, we don’t have to do this every time we want to use linear regression. We can use Python’s scikit-learn library. Scikit-learn, or sklearn, is used specifically for Machine Learning. Inside the l... |
# -*- coding: utf-8 -*-
"""
Created on Thu Jun 14 12:09:52 2018
@author: hp
#"""
#One of the most major forms of chunking in natural language processing is called "Named Entity Recognition."
#The idea is to have the machine immediately be able to pull out "entities" like people, places, things, locations, mone... |
import random
import operator
from itertools import product
from chemtools import gjfwriter
def get_random_layer(components):
layer = []
for component in components:
layer.append(random.choice(component))
return ''.join(layer)
def get_number_of_layers(distributions, max_layers=4):
temp = di... |
from django.conf.urls import patterns, include, url
from rest_framework import routers
from .views import TagViewSet
router = routers.SimpleRouter(trailing_slash=False)
urlpatterns = patterns('',
url(r'^$', TagViewSet.as_view()),
)
|
from Products.Five.browser.pagetemplatefile import ViewPageTemplateFile
from zope.component import getMultiAdapter
from Products.CMFCore.utils import getToolByName
from plone.app.layout.viewlets.common import GlobalSectionsViewlet
class navigationPeu(GlobalSectionsViewlet):
index = ViewPageTemplateFile('viewlets_... |
# This is an exemplary script to run SMUTHI from within python.
#
# It evaluates the scattering response of a single silver NP
# in vacuum. The system is excited by a plane wave.
import numpy as np
import smuthi.simulation
import smuthi.initial_field
import smuthi.layers
import smuthi.particles
import smuthi... |
#coding=utf-8
import numpy as np
import tensorflow as tf
from basic_layer.NN_adam import NN
from util.Printer import TIPrint
from util.batcher.equal_len.batcher_p import batcher
from util.AccCalculater import cau_recall_mrr_org
from util.AccCalculater import cau_samples_recall_mrr
from util.Pooler import pooler
from ba... |
from turtle import *
speed(10)
colors=['red', 'blue', 'brown', 'yellow', 'grey']
n=len(colors)
for j in range(n):
begin_fill()
for i in range (2):
forward(50)
left(90)
forward(100)
left(90)
fillcolor(colors[j])
forward(50)
end_fill()
mainloop() |
DEBUG = True
SQLALCHEMY_DATABASE_URI = 'mysql+pymysql://root:root@127.0.0.1/hmsc_db?charset=utf8'
SQLALCHEMY_TRACK_MODIFICATIONS = False
|
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Sun Mar 21 23:48:28 2021
@author: xies
"""
import numpy as np
import pandas as pd
from skimage import io,draw
import pickle as pkl
import csv
from os import path
dx = 0.25
dirname = '/Users/xies/OneDrive - Stanford/Skin/Mesa et al/W-R2/cropped/'
#%% Loa... |
from random import random
from banking.domain import Account, CheckingAccount
account = None
if random() < 0.5:
print("Head")
account = Account("tr1", 10000)
else:
print("Tail")
account = CheckingAccount("tr2", 20000, 5000)
account.withdraw(10)
print(account) |
from bottle import route,run,static_file,template,post,redirect,request
import time
import json
import os
import RPi.GPIO as GPIO
import threading
time.sleep(300)
assets_path='/home/pi/smart_car/assets'
pin=[05,06,7,8,26,21,16,20]
GPIO.setmode(GPIO.BCM)
for x in pin:
GPIO.setwarnings(False)
GPIO.setup(x,GPIO.OUT)
GP... |
import numpy as np
import cv2
import glob
import matplotlib.pyplot as plt
h, v = 9, 6
# prepare object points, like (0,0,0), (1,0,0), (2,0,0) ....,(6,5,0)
objp = np.zeros((v*h,3), np.float32)
objp[:,:2] = np.mgrid[0:h, 0:v].T.reshape(-1,2)
# Arrays to store object points and image points from all the images.
objpoin... |
from __future__ import division, print_function
from dps.utils.file_utilities import read_data_from_JSON, write_data_to_JSON, deprecated
from dps.utils.Calculation import combine_errors_in_quadrature
from dps.utils.pandas_utilities import dict_to_df, list_to_series, df_to_file, divide_by_series
from copy import deepcop... |
import numpy as np
from scipy.stats import bernoulli
from scipy import stats
from matplotlib import pyplot as plt
def get_sim_score(w):
classifiers = 10*[.6] + [0.75]
weights = [0.1]*10 + [w]
def majority_vote (preds, weights):
#sum of the weights
s = sum(weights)
#score neede... |
from medium import Client
from medium import MediumError
import sys
import os
import copy
ACCOUNT_INFO = "accountsInfo.txt"
SUBMIT_TEXT_FILE = "submitText.txt"
PATH = ""
IMAGES_PATH = "images/"
class Account:
def __init__(self, account_str=None, language=None, token=None, name=None):
self.client = None... |
import numpy as np
from matplotlib import pylab as plt
A = np.fromfile("salida.raw", dtype='int32')
A = A.reshape([2001, 2001])
print(A)
plt.imshow(A)
plt.show() |
import json
from util import byteify
# Class to wrap several things to json, like manage some utf8 things and such things
class JsonMgr(object):
def __init__(self):
pass
def dumps(self, o):
return json.dumps(byteify(o))
def loads(self, s):
return json.loads(s)
... |
# -*- coding: utf-8 -*-
"""
Created on Sun May 6 14:27:47 2018
@author: dms24081999
"""
n=int(input())
a=[]
sum1=0
sum2=0
for i in range(0,n):
a.append(list(map(int, input().split())))
for i in range(0,n):
sum1=sum1+a[i][i]
for i in range(0,n):
sum2=sum2+a[i][n-i-1]
total=sum1-sum2
print(abs(tota... |
import rospy
from geometry_msgs.msg import PoseStamped,TwistStamped
from sensor_msgs.msg import Image
import cv2
from cv_bridge import CvBridge
import numpy as np
class UAV():
def __init__(self):
self.name = "/uav" + "1"
self.control_msg = self.name + '/command/pose'
self.control_vel_msg = ... |
from django.contrib import admin
from .models import Post
# Add Post so we can edit it in the admin page
admin.site.register(Post) |
# Copyright (c) 2015 The University of Manchester
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ... |
import sys
from collections import deque
from copy import deepcopy
from search import Problem,Node
from time import process_time
import numpy as np
from shapely.geometry import Point, Polygon
import heapq
class PathFinder(Problem):
def __init__(self,state,polygons, goal):
super().__init__(stat... |
import jinja2
import json
import logging
import os
import urllib2
import webapp2
import config
JINJA_ENV = jinja2.Environment(
loader=jinja2.FileSystemLoader([
os.path.dirname(__file__) + '/../templates',
os.path.dirname(__file__) + '/../static',
]))
def jinja_include(filename):
return jinja2.M... |
import sys
ncases = int(sys.stdin.readline())
for _c in range(ncases):
n = int(sys.stdin.readline())
if n == 0: print("Case #%d: INSOMNIA" % (_c+1))
else:
seenD = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
seenC = 0
i = 1
while True:
s = str(n*i)
for c in s:
idx = int(c)
if seenD[idx] == 0:
seenD[idx... |
import math
case = int(input())
count = []
for i in range(0,case):
raw = input()
a = raw.split()
math.ceil(int(a[0])/int(a[1])) |
import pandas as pd
import numpy as np
import os
import re
import sys
import matplotlib.pyplot as plt
#import seaborn
from sklearn.linear_model import LogisticRegression
from sklearn import metrics
from sklearn.model_selection import train_test_split
from sklearn.neural_network import MLPClassifier
from sklearn import ... |
#
# 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... |
#coding=utf-8
import json
import re
from django.http import HttpResponse
from django.http import HttpResponseRedirect
from django.http import HttpResponseForbidden
from server import settings
import sys
sys.path.append(settings.JOBPATH)
from dao import onlinedao
from dao import userdao
class AuthMiddleware(object):
o... |
#!/usr/bin/env python
"""
Implement several Git workflows on multiple repos.
# Show the current state of the submodules:
```
> dev_scripts/git/git_submodules.py
```
"""
import argparse
import logging
from typing import List
import helpers.dbg as dbg
import helpers.git as git
import helpers.parser as prsr
impo... |
def taxi(p1, p2, q1, q2):
res =abs((p1-q1)) + abs((p2-q2))
return res
def calc(string1, string2):
mapp1 = []
mapp2 = []
mapp = []
curr_pos = (0, 0)
moven = 0
def moveright(m, org_pos, move):
cur_pos = org_pos
for i in range( move ):
cur_pos = (cur_pos[0] + ... |
# -*- encoding: utf-8 -*-
import PySimpleGUI as sg
# Very basic window. Return values as a list
layout = [
[sg.Text('Please enter your Name, Address, Phone')],
[sg.Text('Name', size=(15, 1)), sg.InputText()],
[sg.Text('Address', size=(15, 1)), sg.InputText()],
[sg.Text('Phone', size=(15, 1)), sg.Inpu... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.