text stringlengths 38 1.54M |
|---|
#!/bin/python
#getting weather of major cities around the world using OpenWeather API
import requests
import json
#API key from OpenWeather map
api_key = "26c7d541b9d4a453df49d961bf746589"
#base url from OpenWeathermap
base_url = "http://api.openweathermap.org/data/2.5/weather?"
city = input("Please enter your fav... |
def check_test_type(var, tests):
if var != None:
assert type(var) == str, 'not a string'
assert var in tests.keys(), 'unknown test type {}'.format(var)
return var
class Testing():
def __init__(self, model, diagnostic_test_type,
preventive_screening_test_type, follow_up_testing_interval,
screening_interva... |
import os
from flask import Flask, render_template, redirect, url_for, session
from datetime import datetime
from flask import Flask, render_template, request
from flask_migrate import Migrate
from flask_sqlalchemy import SQLAlchemy
# import for mails
# python linting now enable
# admin mai
from View.configuration i... |
from app1.models import *
from app1.util.utils import *
def retriveTeachPlan(request):
'''
URL:
http://127.0.0.1:8000/app4/retriveTeachPlan?tpno=001
'''
try:
tpno=request.GET.get("tpno")
result=TeachPlan.objects.values().get(tpno=tpno)
response={}
respon... |
#coding:utf-8
class Solution(object):
def myPow(self, x, n):
if n == 0:
return 1
if n < 0:
return 1.0 / self.myPow(x, -n)
v = self.myPow(x, n / 2)
if n % 2 == 1:
return x * v * v
else:
return v * v
|
#номер элемента ряда Фибоначчи
# 1 1 2 3 5 8 13 21
# def fibo(n):
# if n <= 2:
# return 1
# return fibo(n - 2) + fibo(n - 1)
#
#
# print(fibo(1))
# print(fibo(2))
# print(fibo(3))
# print(fibo(4))
# print(fibo(5))
# print(fibo(6))
# print(fibo(7))
# print(fibo(8))
# 5! = 5 * 4 * 3 * 2 * 1
def fact(num)... |
"""Scrapes powerschool to return grades and info about specific classes
Usage:
power-scraper <classes> <grades> [--name|--room|--teacher|--teacher-email] [-h]
"""
__version__ = "0.0.1" |
# -*- coding:utf-8 -*-
from .models import Brand,Serie,Version,Car
def cars_url(self):
return [{
'title': u'汽车管理', 'perm': self.get_model_perm(Brand, 'view'),
'icon':'fa fa-cloud',
'menus':(
{
'title': u'品牌',
'url': self.get_model_url(Brand, 'changelist'),
'perm': self.get_model_perm(Brand, 'vie... |
class Caneta:
def __init__(self,cor,marca,numero_ponta,volume_tinta):
self.cor = cor
self.marca = marca
self.numero_ponta = numero_ponta
self.volume_tinta = volume_tinta
def encher_caneta(self):
self.volume_tinta = 50
def escrever(self,palavra):
... |
class MySingleton:
# Here will be the instance stored.
__instance = None
@staticmethod
def getInstance():
""" Static access method. """
if MySingleton.__instance == None:
MySingleton()
return MySingleton.__instance
def __init__(self, val1, val2):
""" ... |
# -*- coding: utf-8 -*-
#
# Cipher/blockalgo.py
#
# ===================================================================
# The contents of this file are dedicated to the public domain. To
# the extent that dedication to the public domain is not available,
# everyone is granted a worldwide, perpetual, royalty-free,
# n... |
import os
import xml.etree.ElementTree as ET
import warnings
from scopus import config
from scopus.utils import get_content, get_encoded_text
SCOPUS_AFFILIATION_DIR = os.path.expanduser('~/.scopus/affiliation')
if not os.path.exists(SCOPUS_AFFILIATION_DIR):
os.makedirs(SCOPUS_AFFILIATION_DIR)
class ScopusAffil... |
#! /usr/bin/env python
# coding:utf-8
# 判断输入的九宫格的格数是否为奇数
def if_odd(n):
if n % 2 == 1:
return True
else:
return False
# 九宫格填写数的法则
"""
按照下面的方式排列
-------------->x(从1到n)
|
|
|y方向(从1到n)
1、第一个数放在X方向的中间位置
2、其它数顺次放置各个位置,并依据如下原则:(假设第一个数是a,第二个数是b)
以a为中心的位置关系分别为:
左上|上|右上
左 |a |右
左下|下|右下
(1)b放在a的右上位... |
import pygame
from utility import *
import variables
from constants import *
def place_brick(idx):
brick_idx = coord2idx(variables.HAND_BRICK[idx][0],variables.HAND_BRICK[idx][1])
brick_display = variables.HAND_BRICK[idx][0]*10+variables.HAND_BRICK[idx][1]
variables.BRICK_COLOR[brick_idx]=-2
variables.... |
from flask.ext.wtf import Form
from wtforms.fields import BooleanField, DateField, HiddenField, \
PasswordField, SelectField, TextField
from wtforms.validators import InputRequired, Length, Required, Email, \
EqualTo, Optional
class LoginForm(Form):
email = TextField('Email Address', validators=[Required()... |
def zig_zag(arr):
flag = False
n = len(arr)
i = 0
while i < n-1:
if (not flag and not arr[i] < arr[i+1]) or (flag and not arr[i] > arr[i+1]):
swap = True
else:
swap = False
if swap:
arr[i], arr[i + 1] = arr[i + 1], arr[i]
flag = not... |
import numpy as np
import cv2
import sys
import os
import pylab
from poisson_tools import image_to_poisson_trains
from util_functions import *
def img_to_spike_array( img_file_name, save_as_pickle=True ):
img = cv2.imread( img_file_name, cv2.IMREAD_GRAYSCALE )
if img is not None:
height, width = im... |
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def removeNthFromEnd(self, head, n):
"""
:type head: ListNode
:type n: int
:rtype: ListNode
"""
# Need t... |
from keras.preprocessing.image import ImageDataGenerator
import logging
import pickle
import numpy as np
from keras.utils import np_utils
from ibmfl.data.data_handler import DataHandler
logger = logging.getLogger(__name__)
class MnistTFDataHandler(DataHandler):
"""
Data handler for MNIST dataset.
"""
... |
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
from datetime import datetime
import os
import time
image_extensions = ('.png', '.jpg', '.jpeg', '.svg', '.tiff')
video_extensions = ('.mov', '.mp4', '.mkv', '.avi', '.webm', '.mpeg', '.mpg', '.mpe',
'.mp2',... |
import struct
def spliter(format, buffer):
data = buffer[:struct.calcsize(format)]
buffer = buffer[struct.calcsize(format):]
ret = struct.unpack(format, data)
if len(ret) == 1: ret = ret[0]
return ret, buffer |
from datetime import datetime
from flask import (
abort,
Blueprint,
jsonify,
request,
Response,
send_from_directory,
)
import config
from models import (
Comment,
db,
Post,
)
api = Blueprint('api', __name__, url_prefix="")
@api.route('/')
def home():
return "You are in my ho... |
import functools
import inspect
import os
from glob import glob
from random import shuffle
from types import GeneratorType
from typing import TextIO
from _pytest.python import Metafunc
from loguru import logger
from pytest_cleanup.common import (
get_class_that_defined_method,
mergeFunctionMetadata,
is_as... |
from django.urls import include
from django.conf.urls import url
from rest_framework import routers
from .views import UserViewSet
router = routers.DefaultRouter()
router.register(r"user", UserViewSet, basename='user')
urlpatterns = router.urls
|
from django.shortcuts import render, get_object_or_404
from .forms import EntryForm
from .models import Trades
from user.models import Profile
from django.http import HttpResponseRedirect, HttpResponse, JsonResponse
from django.views.generic.edit import UpdateView
import datetime
from django.urls import reverse
import ... |
import os
from django.db import models
class Media(models.Model):
media_name = models.CharField(max_length=100)
media_url = models.FileField(upload_to='media/')
media_description = models.CharField(max_length=150, default="Napisz tu coś")
def extension(self):
name, extension = os.path.splite... |
# Licensed to Modin Development Team under one or more contributor license agreements.
# See the NOTICE file distributed with this work for additional information regarding
# copyright ownership. The Modin Development Team licenses this file to you under the
# Apache License, Version 2.0 (the "License"); you may not u... |
from django import forms
from .models import ProductoImagen
class ProductoImagenForm(forms.ModelForm):
class Meta:
model = ProductoImagen
fields = ['producto', 'nombre','descripcion', 'imagen']
|
def on_init(t):
# DO ON INITIALIZATION STUFF HERE
return True
def on_commit(t):
# GLOBAL ON COMMIT ie every solution
# http://docs.gridlabd.us/_page.html?owner=slacgismo&project=gridlabd&branch=develop&folder=/Module&doc=/Module/Python.md
print("Time: ", t)
power_val_A = gridlabd.get_value("load_1","constant... |
from selenium import webdriver
from Utils.folder_structure_builder import FolderStructureBuilder
class Helpers:
@classmethod
def take_screenshot(cls, browser, filename):
location = f'{FolderStructureBuilder.failed_screenshot_folder}/{filename}.png'
browser.get_screenshot_as_file(location)
|
#!/usr/bin/env python3
import sys, re, os
sys.path.append("../../../utils/")
from segmaker import segmaker
segmk = segmaker("design.bits")
# Can fit 4 per CLB
# BELable
multi_bels_by = [
'SRL16E',
'SRLC32E',
]
# Not BELable
multi_bels_bn = [
'RAM32X1S',
'RAM64X1S',
]
# Those requiring special resou... |
#random module 불러오기
import random
#1~100 사이 임의의 정수를 불러와 answer에 지정
answer = random.randint(1,100)
print(answer)
# 사용자로부터 이름과 답 입력받기
username = input("What is your name? ")
guess = eval(input("Hi, " + username + " guess the number: "))
# if 조건문을 활용해 정답 판단하기
if guess == answer:
print("Correct! Answer was " + str(a... |
#!/usr/bin/env python
# coding: utf-8
# In[ ]:
---HOMEWORK 3----
#Name: Ayşegül
#Surname: Hülagü
#mail: hulaguaysegul@gmail.com
# In[123]:
def prime_numbers(lower,upper):
for i in range(lower,upper+1):
for num in range(2,i):
if(i%num)==0:
break
... |
import os
import pytest
import ucp.exceptions
from ucp._libs import ucx_api
from ucp._libs.arr import Array
def test_get_config():
ctx = ucx_api.UCXContext()
config = ctx.get_config()
assert isinstance(config, dict)
assert config["MEMTYPE_CACHE"] == "n"
def test_set_env():
os.environ["UCX_SEG_... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# remote_ssh.py
import pexpect
def remote_ssh(ip, password, cmd, username='root'):
ssh = pexpect.spawn('ssh ' + username + '@' + ip + ' ' + cmd, timeout=None)
try:
i = ssh.expect(['password:', 'yes/no'], timeout=5)
if i == 0:
ssh.sendline(... |
import csv
import textwrap
from datetime import datetime
from typing import Optional
import pyomo.environ as pyo
import yaml
from pysperf import _JobResult
from pysperf.config import outputdir, time_format
from pysperf.model_library import models
from pysperf.solver_library import solvers
from pysperf.paver_utils.jul... |
import spacy
nlp = spacy.load('en_core_web_sm')
from spacy import displacy
doc = nlp("Over the last quarter, Apple sold nearly twenty thousand iPods for a profit of $6 million." "By contrast, Sony only sold 8000 Walkman music players.")
#doc = displacy.render(doc, style = 'ent', jupyter = True)
for sentence in doc.s... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed t... |
def repeatedStringMatch(A, B):
"""
:type A: str
:type B: str
:rtype: int
"""
count = 1
length = len(A)
copyA = A
while (len(copyA) < len(B)):
count += 1
copyA += A
if len(copyA) >= len(B) and B not in copyA:
count += 1
copyA += A
return coun... |
from umachine import SPI, Pin
from utime import sleep_ms
class MPL115A1:
"""Read pressure and temperature from MPL115A1 SPI sensor.
Adapted from https://github.com/FaBoPlatform/FaBoBarometer-MPL115-Python
Sources:
http://www.nxp.com/assets/documents/data/en/data-sheets/MPL115A1.pdf
https://learn.... |
from django.test import TestCase
from blog import models
from blog import forms
# Create your tests here.
class BlogModelTest(TestCase):
def test_valid(self):
"""正常な入力を行えばエラーにならないことを検証"""
params = dict(content="test", photo="", anime_id="", anime="", tag="tag,tag、tag", user=1)
... |
import random
import json
from celery import shared_task
from backend.celery import celery_app
from celery.utils.log import get_logger
@shared_task
def test_task():
data = random.randint(0, 100)
return {'data': data}
|
class Solution:
## Iterative Solution
def generate(self, numRows: int) -> List[List[int]]:
ans = []
for i in range(numRows):
if i == 0:
ans.append([1])
if i == 1:
ans.append([1,1])
if i > 1:
prev = ans[-1]
... |
##############################################################
# This main file contains an overview of functions that were
# run to do simulations in the thesis of Koen Emmer
# Uncomment functions to run them
# For questions, contact me via LinkedIn
# https://www.linkedin.com/in/koenemmer/
############################... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.contrib import admin
from django.urls import reverse
from django.utils.html import format_html
from .models.Person import Person
from .models.Affiliation import Affiliation
from .models.Organization import Organization,OrgRelationship
from .m... |
'''
@Author: Sankar
@Date: 2021-04-08 13:37:25
@Last Modified by: Sankar
@Last Modified time: 2021-04-08 13:38:09
@Title : Basic_Python-28
'''
'''
Write a Python program to clear the screen or terminal.
'''
import os, sys
os.system("cls") |
#!/usr/bin/python3
import argparse
import numpy as np
import matplotlib.pyplot as plt
from math import floor, ceil
from decimal import Decimal
def read_file(ifile: object, ofile: object, bin_size: float) -> object:
size = (2, 3)
coords = np.zeros(size, dtype=float)
d = []
with open(ifile... |
"""
Module to read alerts from the Kafka topic ("alerts_topic") where Flink applications post alerts and then put them in MongoDB.
"""
from kafka import KafkaConsumer, TopicPartition
import json, pymongo, datetime
from pymongo import MongoClient
def insert_records(records):
for record in records:
# No need to disp... |
import pandas as pd
import numpy as np
import xgboost as xgb
from sklearn.model_selection import train_test_split
from sklearn.impute import SimpleImputer
from matplotlib import pyplot as plt
import seaborn as sns
import os
from pycomp.viz.insights import *
# Project variables
DATA_PATH = 'C:/Work/HP/dataset'
TRAIN_FI... |
'''
super simple vector class and vector functionality. i wrote this simply because i couldn't find
anything that was easily accessible and quick to write. this may just go away if something more
comprehensive/mature is found
'''
import math
class MatrixException(Exception):
pass
class Vector(objec... |
class Solution:
def sortColors(self, nums: List[int]) -> None:
"""
Algorithm : merge-sort (divide and conqure)
"""
if len(nums) >1:
mid = len(nums)//2
L = nums[:mid]
R = nums[mid:]
self.sortColors(L)
self.sortColors(R)
i = j = k = 0
while... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Mar 1 12:42:31 2019
@author: rebeccafang
"""
""" This program applies a linear regression model with L1 regularization to
the cleaned DeepSolar dataset. This model predicts residential solar system
count per 1000 households.
"""
import matplotlib.pyp... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import sys
import math
import pandas as pd
import numpy as np
from optparse import OptionParser
from xlsxwriter.utility import xl_rowcol_to_cell
class Report:
def __init__(self, filename):
self.all_top_box = None
self.all_average = None
... |
import paver
import paver.misctasks
from paver.path import path
from paver.easy import *
import paver.setuputils
paver.setuputils.install_distutils_tasks()
import os, sys
from sphinxcontrib import paverutils
sys.path.append(os.getcwd())
# You will want to change these for your own environment in .gitignored pavercon... |
import os
import secrets
from PIL import Image
from sqlalchemy.sql.functions import user
from shopping import app,db,bcrypt
from flask import render_template, url_for, flash, redirect,request, session
from shopping.forms import ContactForm, RegistrationForm,LoginForm, UpdateProfileForm
from shopping.models import User,... |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.1 on 2016-01-08 17:55
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('app', '0023_remove_userprofile_active'),
]
operations = [
migrations.CreateM... |
#!/usr/bin/env python3
"""
Photo Folder renamer - renames folders to a standardized format
Ed Salisbury <ed.salisbury@gmail.com>
Last Modified: 2020-03-23
"""
import os
import os.path
import argparse
import re
class Renamer:
def __init__(self, **kwargs):
self.path = kwargs['path']
def get_month_num(s... |
"""Tests for the helpers.
Do not cover a lot of (very few actually) corner cases.
But it's going to be useful for maintaining the app.
"""
import numpy as np
from numpy.testing import assert_array_equal, assert_almost_equal
from screen2table import helpers
def test_functional_culvert():
sd = helpers.ScreenData(... |
## Ocultador de arquivo
import ctypes
# pasta = input('Digite o caminho da pasta a ser ocultada, exemplo: (C:/pasta)')
atributo_ocultar = 0x02
# Ocultar pasta
# retorno = ctypes.windll.kernel32.SetFileAttributesW(pasta, atributo_ocultar)
# Ocultar arquivo
retorno = ctypes.windll.kernel32.SetFileAttribu... |
from pyclesperanto_prototype._tier0 import Image
from pyclesperanto_prototype._tier0 import plugin_function
@plugin_function(categories=['label measurement', 'mesh'])
def draw_angle_mesh_between_touching_labels(labels : Image, angle_mesh_destination : Image = None) -> Image:
"""Starting from a label map, draw line... |
#!/usr/bin/env python3
"""
SYNOPSIS: Automatically updates every found source code repository in the
current tree, or the specified path.
"""
import argparse
import os
import subprocess
import sys
from sync_repositories.credentials import Backends
from sync_repositories.credentials import keyring as kr
from... |
"""
Lendro Arquivos CSV
CSV = Comma Separeted Values = Valores Separados por Virgula
# Possivel de se trabalhar, mas não é o ideal ( muito trabalho )
with open('original.csv', encoding='utf-8') as arquivo:
dados = arquivo.read()
dados = dados.split(',')[2:]
print(dados)
A linguagem Python possui 2 forma... |
#!/home/ubuntu/archiconda3/envs/streaming/bin/python3.7
#%%
import asyncio
from binance import AsyncClient, BinanceSocketManager
from confluent_kafka import Producer
import configparser
import socket
import ast
async def main(producer):
client = await AsyncClient.create()
bm = BinanceSocketManager(client)
... |
#!/usr/bin/env python3
# Copyright (c) 2021 by Apex.AI Inc. 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... |
import time
def spin():
for _ in range( 100 ):
for ch in '-\\|/':
print(ch, end='', flush=True)
time.sleep(0.1)
print('\b', end='', flush=True)
if __name__ == '__main__':
spin()
|
# import webdriver
from selenium import webdriver
# create webdriver object
driver = webdriver.Firefox()
# get geeksforgeeks.org
driver.get("http://192.168.4.1")
# get element
element = driver.find_element_by_id("turnleft")
while True:
# click the element
element.click()
|
# -*- coding:utf-8 -*-
import numpy as np
from matplotlib.font_manager import FontProperties
import matplotlib.lines as mlines
import matplotlib.pyplot as plt
from IPython.core.pylabtools import figsize
import operator
"""
函数说明:kNN算法,分类器
Parameters:
inX-用于分类的数据(测试集)
dataSet-用于训练的数据(训练集)
... |
class PersistenceConfiguration(JdbcConfiguration):
# @Bean
# NamedParameterJdbcOperations operations() {
# return new NamedParameterJdbcTemplate(dataSource());
# }
#
# @Bean
# PlatformTransactionManager transactionManager() {
# return new DataSourceTransactionManager(dataSource());
# }
... |
f = open("poker.txt", 'r')
rounds = f.read().split('\n')
cards = [a.split(' ') for a in rounds]
player1 = [c[0:5] for c in cards]
player2 = [c[5:10] for c in cards]
def cardsplit(card):
values = {'2':2, '3':3, '4':4, '5':5, '6':6, '7':7, '8':8, '9':9, 'T':10, 'J':11, 'Q':12, 'K':13, 'A':14}
suits = {'C... |
# import this
print("file works")
print("2 * 2 =", 2*2)
year = 2020
birthyear = 2000
month = "July"
print(month, year)
print("you are", year-birthyear)
my_float = 2.4
print(str(8) + str(int('7')))
num = 2
if num < 4:
print("smaller")
a_list = ["item1", "item2", 60]
b_list = [60, 62, 61]... |
import unittest
from varlink import (Client, VarlinkError)
address = "unix:/run/podman/io.projectatomic.podman"
client = Client(address=address)
def runErrorTest(tfunc):
try:
tfunc()
except VarlinkError as e:
return e.error() == "org.varlink.service.MethodNotImplemented"
return False
c... |
import os
import numpy as np
import glob
import echo_canc_lib as ec
label = 'us/'
path_label = "./data/" + label + "label/"
path_mfcc = "./data/" + label + "feature/"
path_feature = "./data/" + label + "feature/final/"
left_context = 3
right_context = 3
feature_train = np.empty((0, 39*(left_context + right_context + ... |
from pwn import *
#p=process("./level3")
p=remote('111.200.241.244',48932)
elf=ELF("./level3")
libc=ELF('./libc_32.so.6')
sys_r_write=libc.sym['write']-libc.sym['system']
bash_r_write=libc.sym['write']-0x0015902b
payload='a'*0x8c+p32(elf.plt['write'])+p32(elf.sym['main'])+p32(1)+p32(elf.got['write'])+p32(10)
p.s... |
from django.db import models
# 类: DailyMemo
class DailyMemo(models.Model):
date = models.DateField(verbose_name='日期')
time = models.TimeField(verbose_name='时间')
title = models.CharField(verbose_name='标题', max_length=100)
content = models.TextField(verbose_name='内容')
value = models.IntegerField(verbose_name='价值'... |
from walrus_system_configuration.util import *
from catkin.find_in_workspaces import find_in_workspaces
import os
UDEV_RULES_DIR = '/etc/udev/rules.d'
def enumerate_udev_files():
udev_path_list = find_in_workspaces(project='walrus_system_configuration', path='udev', first_matching_workspace_only=True)
if len(... |
import os
import os.path
from flask import Flask
from flask_autoindex import AutoIndex
class cdn :
app = Flask(__name__)
AutoIndex(app, browse_root=os.path.curdir)
@app.route('/list')
def list():
r=[]
f=[os.path.join(dirpath, f)
for dirpath, dirnames, files in os.w... |
def isPalindrome(self, array: List[int]) -> bool:
middle_value = len(array) // 2
array_length = len(array)
for i in range(middle_value + 1):
if array[i] != array[array_length - i - 1]:
return False
return True
|
# -*- encoding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
import io
import logging
import logging.config
import sys
from collections import OrderedDict
from armory.environ import Environment
from armory.serialize import jsonexpand, jsonify
from dateutil.parser import parse
from .comm import... |
# https://codeforces.com/group/XWOeQO4RLM/contest/206799/problem/G
studens=int(input())
abilities=input()
abilities=abilities[::2]
abilities=list(abilities)
for i in range(len(abilities)):
abilities[i]=int(abilities[i])
comands=[]
diff = 1
while abilities!=[]:
for i in abilities:
print(111)
if len(comands)<4:
... |
from bokeh.core.properties import Override, List, String
from bokeh.models import CompositeTicker, AdaptiveTicker, TickFormatter, LinearAxis
# Globals
ONE_NANO = 1e-9
ONE_MILLI = 1e-3
ONE_SECOND = 1.0
ONE_MINUTE = 60.0 * ONE_SECOND
ONE_HOUR = 60 * ONE_MINUTE
def _TIME_TICK_FORMATTER_HELP(field):
return """
... |
from parsing.parser import *
from actions.question import *
from parsing.parse_interaction import interactable_object_name, guard_noun
def see_verb() -> Parser:
"""
:return: a parser for words that mean 'to see'. This only consumes the parsed words.
"""
can_see = maybe(word_match('can', consume=Consum... |
from util.search_equ import search_by_token, search_by_id
from util.alter_label_text import alter_label
data_list = search_by_token("\prime", mode=0)
#data_list2 = search_by_token("'", mode= 0)
# check if prime following "^"
def get_all_index_of_a_token(token_list, token):
index_list = []
for i in range(len(t... |
import os
from dotenv import load_dotenv
from app import create_app
dotenv_path = os.path.join(os.path.dirname(__file__), '.env')
if os.path.exists(dotenv_path):
load_dotenv(dotenv_path)
app = create_app(os.getenv('FLASK_CONFIG') or 'default')
from flask_migrate import migrate, upgrade
from app import models
fr... |
x = True
y = False
if x or y:
print("Dio bien")
print("fskjdgh")
else:
print("Dio mal")
print("ok")
print("123")
|
# Built-in modules #
# Internal modules #
import illumitag
from illumitag.groups.aggregate import Collection, Aggregate
from illumitag.common.autopaths import AutoPaths
# Third party modules #
###############################################################################
class Projects(Collection):
"""A collect... |
import random
def random_list(n, max_int=1000000):
return [random.randrange(max_int) for _ in range(n)]
# ===================== O(n^2) algorithms =====================
def bubble_sort(lst):
for i in range(len(lst)):
for j in range(len(lst) - i - 1):
if(lst[j] > lst[j+1]):
l... |
# Write a Python program to get next day of a given date.
# Expected Output:
# Input a year: 2016
# Input a month [1-12]: 08
# Input a day [1-31]: 23
# The next date is... |
# -*- coding: utf-8 -*-
import pygame
import random
import time
from random import choice
from firebase import firebase
from tkinter import *
import sys
import tkinter as tk
FIREBASE_URL = "https://car-game.firebaseio.com/"
global result
if __name__ == '__main__':
# Cria uma referência para a aplicação Fireba... |
class NPC:
def __init__(self, n_name, n_job, n_body, n_mind, n_charm):
self.n_name = n_name
self.n_job = n_job
self.n_body = n_body
self.n_mind = n_mind
self.n_charm = n_charm
|
import numpy as np
class LantecyCalc( object ):
def __init__(self, file_name ):
#Inicializando as variaveis
self.periods = np.array( [])
self.mean = 0.0
self.std_deviation = 0.0
self.max = 0.0
self.size = 0
#Iterando nas linhas do arquivo e lendo os periodos.
file = open( file_name, 'r' )
for lin... |
# -*- coding: utf-8 -*-
"""
@author: Pramod Duvvuri
"""
print('Hello World!')
# Types in Python
print(type(3.14))
print(type(None))
# Arithemtic Operations in Python
print(6 + 12 - 3)
print(2 * 3.0)
print(- - 4)
print(10/3)
print(10.0/3.0)
a = 3
print(a + 2.0)
a = a + 1.0
a
print('Rounded Integer ', round(2.6))... |
import glob
# def load():
images = glob.glob('*vehicles/*/*')
cars = []
notcars = []
for image in images:
if 'non' in image:
notcars.append(image)
else:
cars.append(image)
## Uncomment if you need to reduce the sample size
#sample_size = 500
#cars = cars[0:sample_size]
#notcars = notcars[0:samp... |
from django import template
from provider import scope
register = template.Library()
@register.filter
def scopes(scope_int):
"""
Wrapper around :attr:`provider.scope.names` to turn an int into a list
of scope names in templates.
"""
return scope.to_names(scope_int)
|
import RPi.GPIO as GPIO
import time
from math import *
from random import *
off = True
while True:
level = int(input("Input: "))
if level > 1 or level < 0:
break
if level == 1 and off:
off = False
GPIO.setmode(GPIO.BOARD)
GPIO.setup(23, GPIO.OUT)
GPIO.output(23, 0)
elif level == 0 and not off:
off = T... |
from flask import url_for
def test_view_template_version(
client_request,
api_user_active,
mock_login,
mock_get_service,
mock_get_template_version,
mock_get_user,
mock_get_user_by_email,
mock_has_permissions,
fake_uuid,
):
service_id = fake_uuid
template_id = fake_uuid
... |
from pylab import *
from mats.eq_conv_mat import eq_conv_mat
from mats.conv_mat import conv_mat
def frac_shift_2(img, v):
assert(((v>=0) & (v<1)).all())
c0 = array([0, 1-v[0], v[0]])
c1 = array([0, 1-v[1], v[1]])
W = c0.reshape(1,-1)*c1.reshape(-1,1)
sh_img = shape(img)
c = eq_conv_... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# author: Yizhong
# created_at: 04/09/2018 10:23 PM
import tensorflow as tf
from .rnn import rnn
from .elmo_crf_seg import ELMOCRFSegModel
from .layers import self_attention
class AttnSegModel(ELMOCRFSegModel):
def _encode(self):
with tf.variable_scope('rnn_1... |
__author__ = 'saimanoj'
import preprocessing
import sys
def main():
# preprocessing.preprocess_train(arg)
preprocessing.preprocess_test()
if __name__ == "__main__":
main()
|
import argparse
from search.BFS import BFS
from search.DFS import DFS
parser = argparse.ArgumentParser(description='This program solves the N Queens problem using blind search.')
parser.add_argument('--algo', type=str, help='Blind search algorithm to use(BFS, DFS)', default='DFS')
parser.add_argument('--nq', type=int,... |
import scrapy
class UrlItem(scrapy.Item):
# 获取列表
url_list = scrapy.Field()
# 商店名称
shop_name=scrapy.Field()
class ShopItem(scrapy.Item):
# 商店名称
shop_name=scrapy.Field()
# 评论数目
comment_num=scrapy.Field()
# 人均消费
avg_pay=scrapy.Field()
# 口味
taste=scrapy.Field()
# 环境
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.