text stringlengths 38 1.54M |
|---|
from DS.TreeNode import TreeNode
class Solution:
def isBalanced(self, root: TreeNode) -> bool:
def height(root):
if root is None:
return 0
l = height(root.left)
r = height(root.right)
if l == -1 or r == -1:
return -1
... |
# Generated by Django 3.1.7 on 2021-03-25 03:38
from django.db import migrations, models
import datetime
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Scores',
fields=[
('id', mod... |
from django.db import models
from django.contrib.auth.models import User
class UserProfile(models.Model):
user = models.OneToOneField(User,null=True)
email = models.CharField(max_length = 200, null = False)
spotify_user_id = models.CharField(blank = False, max_length = 500)
spotify_token = models.Char... |
with open("input.txt", "r") as boardingpass:
plane = [0 for _ in range(1024)]
for boarding in boardingpass:
bin = boarding.replace('F','0').replace('B','1').replace('L','0').replace('R','1')
plane[int(bin[:7],2)* 8+int(bin[7:],2)] = 1
for i in range(1024):
if plane[i] == 0 and plane[i - 1 % 128] == 1 and plane... |
import winsound
import time
import sys
CODE = {'A': '.-', 'B': '-...', 'C': '-.-.',
'D': '-..', 'E': '.', 'F': '..-.',
'G': '--.', 'H': '....', 'I': '..',
'J': '.---', 'K': '-.-', 'L': '.-..',
'M': '--', 'N': '-.', 'O': '---',
'P': '.--.', 'Q': '--.-', 'R': '.-.',
'S': '...', ... |
#!/usr/bin/env python
# coding: utf-8
# In[12]:
def fahr_to_celsius(fahr):
a = float(fahr) - 32.0
b = 5.0 / 9
return a * b
def fahr_to_kelvin(fahr):
a = float(fahr)
b = 459.67
c = 5.0 / 9
return (a + b) * c
def celsius_to_fahr(celsius):
a = float(celsius)
b = 9.0 / 5
c = 3... |
"""
Utility class for build ui files.
This script will just compile all ui files into python class
author: Minu
"""
import os
import sys
import glob
from PyQt5 import uic
def run():
sys.path.append(os.path.dirname(__file__))
dirname = os.path.dirname(__file__)
for root, dirs, files in os.walk(dirnam... |
#使用输入函数input()
#变量=input('输入的内容')
#使用int()整型函数来接收数字
#输出ASCII码值
#了解ord()函数
tip=input('请输入内容:') #无论输入时数字还是字符串,统一按照字符串处理
num=int(input('请输入数字:')) #使用int()整型函数来接受数字,是数字为真,否则报错
name=input('请输入内容:') #只能输入字母和数字,不能输入汉字
print (name+"的ASCII码值为:",ord(name)) #ord()函数,返回对应字符的十进制整数 |
from django.db import models
from django.contrib.auth.models import AbstractUser, BaseUserManager
from django.db.models.signals import post_save
from django.contrib.auth import get_user_model
from taggit.managers import TaggableManager
from django.db.models import Q
class UserManager(BaseUserManager):
... |
from __future__ import division,print_function
import holopy as hp
import numpy as np
import matplotlib.pyplot as plt
def myHolo():
''' my holographic setup, which I think works since we use plane waves '''
optics = hp.core.Optics(wavelen=635e-9, index=1.33, polarization=[1.0, 0.0])
#obj = hp.load('tryit... |
# Generated by Django 3.0.8 on 2020-10-31 16:18
from django.db import migrations, models
import django.utils.timezone
class Migration(migrations.Migration):
dependencies = [
('zoopark', '0005_auto_20201031_1543'),
]
operations = [
migrations.RemoveField(
model_name='animal',... |
import os
import numpy as np
import cv2
Map_DIR="/home/songzhuoran/video/video-frame-based-acc/data/baseline_result/"
Bench_DIR="/home/songzhuoran/video/video-frame-based-acc/data/benchmark_result/"
record_file = open("/home/songzhuoran/video/video-frame-based-acc/result_baseline.csv", "w")
def main():
videofile... |
from django.contrib import admin
from .models import SmallData, BigData, CryAudio
admin.site.register(SmallData)
admin.site.register(BigData)
admin.site.register(CryAudio)
|
'''BaseLinter version 0.1
Base Linter is a command-line interface app checks for sets of words in a text by order.
Each time the app encounters a word belonging to a set, it prompts you to choose which
of the words in the set. The app will replace the word in that position in the word
order in the text you are check... |
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import models, api, _
from odoo.exceptions import Warning
class SaleOrder(models.Model):
_inherit = 'sale.order'
@api.multi
def action_confirm(self):
zero_price = [x.product_id.name
... |
# Generated by Django 3.0.8 on 2021-01-16 18:57
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('patient', '0005_auto_20210116_1848'),
]
operations = [
migrations.AddField(
model_name='patient',
name='temperature'... |
# coding: utf-8
from flask import Flask, request
import vmware.interface_scan as VMware_scan
import vmware.interface_check as VMware_check
import kvm.interface_check as KVM_check
import openstack.interface_check as Openstack_check
import kubernetes.interface_check as Kubernetes_check
import docker.interface_ch... |
"""Quick sort"""
from typing import List
from base import Sort
class Quick(Sort):
"""
Quick sort class
"""
# pylint:disable=too-few-public-methods
def sort(self) -> List[int]:
if len(self.array) < 2:
return self.array
middle_index = int((len(self.array) - 1) / 2)
... |
"""
Setup of webdriver using wrapper uses spec import for the args,
so this provides a path where they can be imported from
"""
# Current tests don't care about spinning up a real webdriver so
# no need to have real webriver objects like a Proxy
# setting all to True for now
file_detector = True
proxy = True
browser_... |
from collections import deque
n = int(input())
arr = []
for i in range(n):
arr.append(list(map(int, input().split())))
dx = [-1,1,0,0]
dy = [0,0,-1,1]
def bfs(x,y):
de = deque()
de.append([x,y])
visit[x][y] = 1
while de:
current_node = de.popleft()
for k in range(4):
n... |
# -*- coding: utf-8 -*-'
import csv
import pickle
import numpy as np
data_dir='../../temp/sougou/extract_data/'
train_text=[]
train_label=[]
with open('/home/yan/my_datasets/sogou_news_csv/train.csv') as f:
for row in f:
train_label.append(int(row[1])-1)
train_text.append(row[4:])
# print... |
# -*- coding: utf-8 -*-
"""
Extension that generates configuration files for Yelp `pre-commit`_.
.. _pre-commit: http://pre-commit.com
"""
from __future__ import absolute_import
from ..templates import pre_commit_config
def augment_cli(parser):
"""Add an option to parser that enables the `pre-commit`_ extension... |
"""
This module has functions associated with analyzing the geometry of a molecule.
It can be run as a script with an xyz file.
"""
# COLLECT ALL CODE IN ONE BOX
# start with imports
import numpy
import os
import argparse
# next: functions
def open_xyz(file_path):
"""
This function opens an xyz fi... |
from rest_framework import serializers
from .models import Anime
from django.conf import settings
class AnimeSerializer(serializers.ModelSerializer):
class Meta:
model = Anime
fields = ( 'id','title','type','episodes','image_url','url','synopsis','score','author')
|
import pytest
from solutions.HLO import hello_solution
def test_hello():
assert hello_solution.hello("Thomas") == "Hello, Thomas!"
def test_invalid_input():
with pytest.raises(ValueError):
hello_solution.hello(1)
|
#!/home/rvalenzuela/miniconda/bin/python
# Extends a geotiff DTM file with flat terrain (e.g. ocean)
# (inspired in http://www.gdal.org/gdal_tutorial.html)
#
# Raul Valenzuela
# April, 2015
#
import gdal
from gdalconst import *
import subprocess
import numpy as np
import sys
def Usage():
print 'Usage:\n'
print '... |
import json
from multiprocessing import cpu_count
import pandas as pd
cores = cpu_count()
def import_statistics(file_path, to_set=False):
lines = open(f"{file_path}.tsv").readlines()
meta = import_meta(f"{file_path}_meta.tsv")
counts = [(set(json.loads(left)) if to_set == True else json.loads(left), int... |
from models.db_models.models import ClientInfo
from db.db import session
from flask import Flask, jsonify, request
from flask_restful import Resource, fields, marshal_with, abort, reqparse
client_type_fields = {
'id': fields.Integer(attribute="id"),
'name': fields.String(attribute="name")
}
client_fields = {
... |
# -*- encoding: utf-8 -*-
import asyncio
import logging
from django import forms
from core import const
NAME = 'Телеграм'
REQUIREMENTS = ['python-telegram-bot', 'PySocks']
SERVICE = {
'notify': 'send_message',
}
logger = logging.getLogger(__name__)
# config = dict(
# token = '618430543:AAHagGT853T1v_x1Tl... |
__author__ = 'Udara'
from bst import BinarySearchTree, EmptyValue
def extract_max(T):
if T.right.is_empty():
t1 = T.root
T.root = T.left.root
T.right = T.left.right
newL = T.left.left
T.left = newL
return t1
else:
return extract_max(T.right)
def delete_ro... |
#!/usr/bin/env python
# -*- coding:UTF-8 -*-
# File Name : node_person_recognition.py
# Purpose :
# Creation Date : 21-07-2017
# Last Modified : Sat 22 Jul 2017 05:00:11 PM
# Created By : Jeasine Ma [jeasinema[at]gmail[dot]com]
from __future__ import print_function
from __future__ import division
from __future__ impor... |
import flask
from flask import Flask
from flask import request
import math
import cv2
import urllib
import focal_length
import radial_distortion
app = Flask(__name__, static_url_path='')
# stats for logit model
coeffs = [550.0269, 3.4448, 0.0003, 2.8752]
def calculate_distortion_score(image_url):
rad = float(r... |
def LoadParamValue(module, tbl, pname):
if not pname in ['invert']:
return
fullname = module.ModName + ':' + pname
val = tbl[fullname, 1]
if val is None or val == '':
return
if pname == 'invert':
op('invert_toggle/button').panel.state = 1 if float(val) > 0.5 else 0
return True
def SaveParamValue(module, t... |
from django.db import models
# models.Model allows us to create a Job class along with some background django code we need
class Job(models.Model):
# upload_to="" -> inside the media folder, we can create additional folders to upload our images to.
image = models.ImageField(upload_to='images/')
descriptio... |
from django.template.defaultfilters import register
@register.filter(name='dict_key')
def dict_key(d, k):
return d[k]
@register.filter(name='in')
def inside(key, dict_):
return key in dict_
@register.filter(name='range')
def filter_range(start, end):
return range(start, end + 1)
|
# -*- coding: utf-8 -*-
# wenuanalyser_conf.py
# Nicholas Wardle - Imperial College
# Configuration file for use with WenuAnalyser.py
# --------------------------------------------------------------------------//
<<<<<<< analyser_conf.py
#nTupleDir_ = '/vols/cms01/nw709/VBTFNtuples/Nov4ReReco/'
#nTupleDir_ = '/vols/... |
class ConfigBase:
DB_DRIVER = ''
DB_HOST = ''
DB_DATABASE = ''
DB_USER = ''
DB_PASS = ''
SECRET_KEY = None
SERVER_NAME = None
@classmethod
def db_uri(cls):
if cls.DB_DRIVER == 'mysql':
return f'mysql://{cls.DB_USER}:{cls.DB_PASS}@{cls.DB_HOST}/{cls.DB_DATABASE}... |
'''
Handler for tickerlist
'''
import d6tflow
import d6tflow
from datetime import date
from tasks.task_getTickers import Task_getTickers
def get_runDate():
return date.today()
def read():
runDate = get_runDate()
d6tflow.run(Task_getTickers(runDate=runDate))
out = Task_getTickers(runDate=runDate).ou... |
def largestRange(array):
numberList={x:True for x in array}
checkList={x:True for x in array}
nextNumber={}
prevNumber={}
x=0
y=0
maxLen=0
for i in array:
try:
if numberList[i+1]:
nextNumber[i]=i+1
except:
nextNumber[i]=i
try:
if numberList[i-1]:
prevNumber[i]=i-1
except:
prevN... |
#!/usr/bin/env python
"""
This module handles Processing PinPayments information
The parent module should expect to call the following two methods:
1) testSystem() - Ensure the system is reachable and passes basic tests
2) getSubscribers() - Return a payment-system Independent JSON structure consisting of account dat... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Power by Zongsheng Yue 2019-09-02 15:51:11
import torch
import glob
import random
import scipy.io as sio
import os
import numpy as np
import cv2
from .data_tools import random_augmentation
from . import BaseDataSetH5
# Benchmardk Datasets: Renoir and SIDD
class Benchmar... |
# coding=<coding=utf-8>
from pyspark import SparkContext
sc = SparkContext()
rdd1 = sc.parallelize([1, 2, 3])
rdd2 = sc.parallelize([3, 4, 5])
rdd = rdd1.intersection(rdd2)
print rdd.collect()
# intersection() 在运行时也会去掉所有重复的元素(单个 RDD 内的重复元素也会一起移除)。
# 尽管 intersection() 与 union() 的概念相似,intersection() 的性能却要差很多,因为它需要 通... |
from django.shortcuts import render
from django.template.loader import get_template
# Create your views here.
def index(request):
ctx = {}
#ctx['active_page'] = 'home'
return render(request, 'home/index.html', ctx)
|
#!/usr/bin/python3
## \file AQI.py EPA Air Quality Index calculations
from bisect import bisect_left
# EPA Air Quality Index category breakpoints
EPA_AQI_Y = [0., 50., 100., 150., 200., 300., 400., 500.]
# EPA PM2.5 ug/m^3 -> AQI breakpoints
EPA_PM25_AQI_X = [0., 12., 35.5, 55.5, 150.5, ... |
"""Generators for Spinnaker Applications."""
import logging
from . import spinnaker_client
LOG = logging.getLogger(__name__)
def applications():
"""Generate Spinnaker Applications."""
_applications = spinnaker_client.get('/applications')
for application in _applications:
name = application['name... |
import pandas as pd
import argparse
# import sqlalchemy
db_user = 'user'
db_pass = 'password'
db_name = 'lending_solutions_data'
cloud_sql_connection_name = 'lbg-reboot-feb2020-team-11:europe-west2:lending-solutions-db'
# The SQLAlchemy engine will help manage interactions, including automatically
# managing a pool ... |
'''
msgLogger.py
Valentin Pelloin - 15/10/2016
MIT License
Version 0.1
====
Terminal colors, using ANSI escape sequences and logging
'''
from time import gmtime, strftime
HEADER = '\033[95m'
SUCCESS = '\033[36m'
WARNING = '\033[93m'
FAIL = '\033[91m'
RESET = '\033[0m'
WHITE = '\033[3... |
import random
def stuff():
a = open('occupations.csv')
a.readline()
name = []
perc = []
for line in a:
b = line.rfind(",")
name.append(line[0:b])
perc.append((line.replace("\n",""))[b+1:])
del name[-1]
del perc[-1]
mess = []
d = 0
while d < len(name):
c = float(perc[d]) * 10... |
##
# This software was developed and / or modified by Raytheon Company,
# pursuant to Contract DG133W-05-CQ-1067 with the US Government.
#
# U.S. EXPORT CONTROLLED TECHNICAL DATA
# This software product contains export-restricted data whose
# export/transfer/disclosure is restricted by U.S. law. Dissemination
# to ... |
from datetime import datetime
from typing import Optional
from integration_tests.utils import populate_mock_db
from src.models.notifications.milestone import Milestone
from src.utils.config import shared_config
from src.utils.db_session import get_db
REDIS_URL = shared_config["redis"]["url"]
DEFAULT_EVENT = ""
miles... |
import cv2
from PIL import Image
import numpy as np
def image_count(mask, *crop) :
for a in range(0,256):#遍历所有长度的点
for b in range(0,4):#遍历所有宽度的点
crop[a][b] = mask[a][b]
|
from .._constants import SKIP_ATTRIBUTE
def Skip(reason: str, condition: bool = True):
"""
Decorator which marks a test as skipped.
:param reason: The reason the test was skipped.
:param condition: The condition under which to skip the test.
"""
def applicator(method):
if condi... |
import sys
import gi
gi.require_version('Gtk', '3.0')
from Claver.interface.ProgramLoader import *
from Claver.assistant.avatar.renderEngine.GLCanvas import *
from Claver.interface.Settings import res_dir
class MainWindow(Gtk.Application):
# Default Window Size
WIDTH = 1280
HEIGHT = 720
def __init__... |
from django.db import models
# Create your models here.
from django.db import models
from django.contrib.auth.models import User
from datetime import datetime,date
# Create your models here.
class Sheet_model(models.Model):
id= models.IntegerField(default=1,primary_key=True)
sheet = models.FileField(upload_to=... |
n1 = int(input('Digite o valor da tabuada que você deseja: '))
i = 1
for c in range(1, 11):
print('{} X {:2} = {:2}'.format(n1, i, n1 * i))
i = i + 1 |
import sys
import textwrap
from okonomiyaki.errors import OkonomiyakiError
from ..misc import parse_assignments, substitute_variables, substitute_variable
from ..py3compat import StringIO
if sys.version_info < (2, 7):
import unittest2 as unittest
else:
import unittest
class TestParseAssignments(unittest.Tes... |
import numpy as np
def compose_soln(x, n, V):
A = np.zeros((n, n))
A[0, :] = V * np.ones(n)
A[-1, :] = -V * np.ones(n)
A[1 : -1, 1 : -1] = x.reshape((n - 2, n - 2))
return A |
"""video_project URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.2/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home'... |
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)
# Relay 1
GPIO.setup(21, GPIO.OUT)
# Relay 2
GPIO.setup(26, GPIO.OUT)
try:
while True:
GPIO.output(21, GPIO.HIGH)
print('Relay 1 ON')
time.sleep(1)
GPIO.output(26, GPIO.HIGH)
print('Relay 2 ON')
... |
import numpy as np
import faiss
import os
import pandas as pd
import pickle
from tqdm import tqdm
import time
from chunks_fb_search import doRetrieval_chunk
def doRetrieval_chunk_num(Q, X, num_chunks=5, k=100, verbose=True):
# X shape: n * d
# split into 2 chunks
X_length = X.shape[0]
chunk_length = X... |
# импортируем метод перенаправления
from django.shortcuts import redirect
# импортируем метод запросов к веб-серверам
import requests
# импортируем регулярные выражения, для поиска блоков на странице
import re
# импортируем фреймворк "Замечательного супа"
from bs4 import BeautifulSoup
# импортируем объекты модели данны... |
#! /usr/bin/env python3
import docx
doc = docx.Document()
doc.add_paragraph('Hello world!')
paraObj1 = doc.add_paragraph('This is a second paragraph')
paraObj2 = doc.add_paragraph('This is yet another paragraph.')
paraObj1.add_run(' This text is being added to the second paragraph')
# Optional 2nd parameter for styli... |
from .objective import *
__all__=['SimplexOptimizer']
class SimplexOptimizer(Optimizer):
"""Nelder-Mead Simplex"""
def __init__(self, model, data, optfunc=opt_func_deviance, optfunc_pars=(), xtol=1.0, ftol=1.0, **kwargs):
self.set_general_opts(**kwargs)
self.opttype=self.__class__.__name__
... |
from typing import Dict
import keras
import numpy
class MNIST:
height = 28
width = 28
classes = 10
train_images = 60000
test_images = 10000
def __init__(self) -> None:
(x_train, y_train), (x_test, y_test) = keras.datasets.mnist.load_data()
self.x_train = self.flatten_and_nor... |
import string
def rot13(mess):
# Your code here
newChar = ""
ciphered = ""
for char in mess:
if str.isupper(char):
index = string.ascii_uppercase.find(char)
newChar = string.ascii_uppercase[(index + 13) % 26]
elif str.islower(char):
index = string... |
import datetime
import json
import libs.helpers
import requests
def farsightip(indicator):
con = libs.helpers.db_connection()
with con:
cur = con.cursor()
cur.execute("SELECT * from settings")
settings = cur.fetchall()
settings = settings[0]
apikey = settings['farsight... |
umur = 22
if umur == 22:
print('masih muda')
elif umur == 25:
print('dewasa')
else:
print('tua')
|
"""
This is Lesson 22: Advanced operations with functions
Get Programming: Learn to Code With Python
The following is practice for passing a function object as a paramter to another function
Based on Listing 22.8
"""
# Practice 1
def pasta(kind_of_pasta): # kind_of_pasta is a parameter for pasta()
print("-*-*-... |
#Author_yaobozhang
from bs4 import BeautifulSoup
import requests
url_host = "http://bj.ganji.com"
url_start = "http://bj.ganji.com/wu"
def get_item_urls(url):
item_url_lists=[]
yao_data = requests.get(url)
yao_data.encoding = 'utf8'
soup = BeautifulSoup(yao_data.text,'lxml')
items = soup.select(... |
import time
from src.utils import clear_screen
from src.product_mgmt import product_menu
from src.courier_mgmt import courier_menu
from src.order_mgmt import orders_menu
from src.customer_mgmt import customer_menu
from src.file_handler import save_data
# Main Function
def main():
# products_list = load_data('pro... |
from aiohttp import web
import aiohttp_jinja2
import logging
import db
from aiohttp_session import get_session
import tokens_db
from config import Config
logger = logging.getLogger(__name__)
config = Config()
class EditCaseView(web.View):
@aiohttp_jinja2.template('cases/edit_case.html')
async def get(self):... |
from collections import deque
def solution(priorities, location):
cnt=0
q=deque([(value,i) for i,value in enumerate(priorities)])
while q:
cur=q.popleft()
if q and cur[0]<max(q)[0]:
q.append(cur)
else:
cnt+=1 #인쇄
if location==cur[1]:
... |
class Solution:
def findTargetSumWays(self, nums, S):
"""
:type nums: List[int]
:type S: int
:rtype: int
"""
## DP & math 98%
if sum(nums)<S:
return 0
if (S+sum(nums))%2==1:
return 0
target = (S+sum(nums))//2
... |
from cmath import exp, pi
import sys
sys.path.append("../")
import random
import math
import sys
def miller_rabin(p,s=11):
#computes p-1 decomposition in 2**u*r
r = p-1
u = 0
while r&1 == 0:#true while the last bit of r is zero
u += 1
r = r/2
# apply miller_rabin primality test
... |
class Solution:
def threeSumClosest(self, nums: List[int], target: int) -> int:
nums.sort()
res = sum(nums[:3])
for i in range(len(nums) -2):
l, r = i+1, len(nums)-1
while l<r:
sumhere = nums[i] +nums[l]+nums[r]
if abs(sumhere-target) <... |
def calc_fuel(mass, recurse=True):
n = mass/3-2
if n <= 0:
return 0
elif recurse:
return n + calc_fuel(n)
else:
return n
def solve(recurse=True):
total = 0
with open('input.txt') as f:
for li in f:
total += calc_fuel(int(li), recurse)
print(total)... |
#!/usr/bin/python3
#Crime.py
#The Crime object has the fields shared by both known crimes (from train.csv)
#and mystery crimes (from test.csv). They are:
# -dates
# -dayofweek
# -pddistrict
# -address
# -x (longitude)
# -y (latitude)
class Crime:
def __init__(self,Id,dates,category,dayofwee... |
# Copyright 2021 The TensorFlow Authors. 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
#
# Unless required by applica... |
# -*- coding: utf-8 -*-
import json
import os
import requests
class CSDNCheckIn:
def __init__(self, check_item):
self.check_item = check_item
self.headers = {
"user-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 11_2_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.182 Safa... |
import time
import pygame
import SimpleGUICS2Pygame.simpleguics2pygame as simplegui
import socket
pygame.init()
joy = pygame.joystick.Joystick(0)
joy.init()
s = socket.socket() # Create a socket object
host = '192.168.32.167' # Get local machine IP
port = 12345 # Reserve a port for your ser... |
#!/usr/bin/env python
#ros libraries
import rospy
from std_msgs.msg import String, Float64MultiArray
from sensor_msgs.msg import Image
from geometry_msgs.msg import Point
from nav_msgs.msg import OccupancyGrid
#common python libraries
import cv2
import numpy as np
from cv_bridge import CvBridge, CvBridgeError
from ti... |
from __future__ import division
import os
import time
import cv2
import numpy as np
import sys
import pickle
from keras import backend as K
from keras.layers import Input
from keras.models import Model
from keras_frcnn import roi_helpers
import keras_frcnn.vgg as nn
sys.setrecursionlimit(40000)
######################... |
'''Iterator is an object that represents a stream of data. Repeaded calls to the iterators __next__ method
return successive items in the stream. When no objects are found a StopIteration Exception is raised.'''
#Iterable
nums = [1,2,3,4,5,6,7,8,9,10]
## an object needs the __iter__ method to be an iterable
#for l... |
from main import db
from main.errors import ValidationError
from flask import url_for
from main.engines.utils import split_url
from main.models.products import Product
class Item(db.Model):
__tablename__ = 'items'
id = db.Column(db.Integer, primary_key=True)
order_id = db.Column(db.Integer, db.ForeignKey('orders... |
from django import template
FORM_GROUP_CLASSES = "govuk-form-group"
FORM_GROUP_ERROR_CLASSES = "govuk-form-group--error"
register = template.Library()
@register.simple_tag()
def form_group_classes(*args):
"""Used to set CSS classes for a form group"""
classes = [FORM_GROUP_CLASSES]
for arg in args:
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import requests, random, re
from app.bot import bot
from bs4 import BeautifulSoup
class Noticias(object):
def __init__(self, instance, conversation, tipo):
self.instance = instance
self.conversation = conversation
self.noticia = {}
self.... |
import os, random
from sqlalchemy import create_engine, MetaData, Table, Column, Integer, String, func
from flask import Flask, render_template
app = Flask(__name__)
app.secret_key = 'test'
#Make current dir working directory
os.chdir(os.path.dirname(os.path.realpath(__file__)))
engine = create_engine('sqlite:///name... |
import argparse
import csv
import os
import random
import shutil
from shutil import copyfile
from misc import printProgressBar
def rm_mkdir(dir_path):
if os.path.exists(dir_path):
shutil.rmtree(dir_path)
print('Remove path - %s'%dir_path)
os.makedirs(dir_path)
print('Create... |
# def add(a, b):
# result = a + b
# print(result)
# a = int(input())
# b = int(input())
# add(a,b)
import random
a = int(input())
b = int(input())
c = int(input())
lotto = random.sample(range(a,b),c)
print(lotto)
|
#Problem ID: WATSCORE
#Problem Name: That Is My Score!
for _ in range(int(input())):
n = int(input())
p = [0] * 12
for i in range(n):
x, y = list(map(int, input().split()))
p[x] = max(p[x], y)
print(sum(p[0:9]))
|
import math
def func(i):
print(i)
if len(set(i))==1 or len(set(i))==0:
return i
a=list(i)
for j in range(len(i)):
if i[j]!=i[j+1]:
if i[j:j+2]=="ab":
a[j:j+2]="c"
return func("".join(a))
elif i[j:j+2]=="ba":
a[j:j+2... |
#-*- coding: utf-8 -*-
# http://matplotlib.sourceforge.net/examples/api/legend_demo.html
#
import pylab as p, numpy as n
p.figure(figsize=(10.,5.))
p.subplots_adjust(left=0.09,bottom=0.15,right=0.96,top=0.96, hspace=0.4)
T=30
#T=1024
l=n.linspace(0,2*n.pi,T,endpoint=False)
senoide=n.sin(l)
dente=n.linspace (-1,1,T... |
import os
import xarray
import numpy as np
import bokeh as bk
import holoviews as hv
import geopandas as gpd
import rioxarray as rxr
from typing import NoReturn, Tuple
from shapely import geometry as sg
from holoviews.element import Geometry
from seedpod_ground_risk.layers.data_layer import DataLayer
from ... |
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)
GPIO_TRIGGER = 14
GPIO_ECHO = 15
GPIO.setup(GPIO_TRIGGER,GPIO.OUT)
GPIO.setup(GPIO_ECHO, GPIO.IN)
def Distance():
GPIO.output(GPIO_TRIGGER,True)
time.sleep(0.00001)
GPIO.output(GPIO_TRIGGER,False)
StartTime = time.time()
StopT... |
#############################################################################################
# Final CSC 217-040 Project
# Due Monday 05-07-2018
# Tessa Taylor*, Laura Techentin, Jacob Travers, Justine Forrest, Michael Nguyen, Shae Cloud
# Last edit/maintenance: 05-07-2018
# Classes: Login
######################... |
# coding: utf-8
# In[11]:
import tweepy #another popular twitter API wrapper
import json
import config #twitter OAuth configuration
import datetime
import pylib
import utils
import python_utils
from datetime import datetime
from dateutil import tz
import numpy as np
import pandas as pd
import matplotlib.pyplot as... |
import conpy, mne # Import required Python modules
# Define source space on average brain, morph to subject
src_avg = mne.setup_source_space('fsaverage', spacing='ico4')
src_sub = mne.morph_source_spaces(src_avg, subject='sub002')
# Discard deep sources
info = mne.io.read_info('sub002-epo.fif') # Read information a... |
from django.contrib import admin
from django.db import transaction, DatabaseError
from polymorphic.admin import PolymorphicInlineSupportMixin, StackedPolymorphicInline
from flexible.models import *
from flexible.choices import *
from flexible.instances import *
from flexible.expressions_admin import *
from flexible.a... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2018-06-05 09:15
from __future__ import unicode_literals
import django.utils.timezone
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('blog', '0016_auto_20180605_1207'),
]
operations = [
... |
from Bio import SeqIO
import gzip
import os
num_genomes = 0
genbank_file = gzip.open('GCF_000005845.2_ASM584v2_genomic.gbff.gz',mode='rt')
num_genomes = num_genomes + 1
num_replicons = 0
global_CDS = 0
local_CDS = 0
num_genes_in_rep = 0
replicon_structure = ''
exon = 0
genes_table = open('genes_table.txt','w')
geno... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.