text stringlengths 38 1.54M |
|---|
window = Tk();window.title("add numeric widget");window.geometry('400x200')
spin = Spinbox(window, from_=0, to=100,width=5,state="normal");spin.grid(column=0,row=0)
spin1 = Spinbox(window, values=(1,4,8),width=5,state="readonly");spin1.grid(column=1,row=0)
#set defaultvalue
var = IntVar();var.set(10)
spin3 = Spinbox(wi... |
from datetime import datetime
from unittest import TestCase
from nintendeals import noj
from nintendeals.classes import N3dsGame, SwitchGame
LIST_LIMIT = 20
class TestNoj(TestCase):
def test_game_info_non_existant(self):
game = noj.game_info(nsuid="60010000000000")
self.assertIsNone(game)
... |
A = []
def check(a, b) :
for i in range(0, len(a)-1):
if a[i][0] == b:
return i
return -1
def new() :
tag = input("hashtag :")
x = check(A, tag)
if x == -1:
A.append([tag])
text = input("text :")
A[x].append(text)
... |
from nltk.classify import NaiveBayesClassifier
from nltk.corpus import subjectivity
from nltk.sentiment import SentimentAnalyzer
from nltk.sentiment.util import *
from nltk import tokenize
from nltk.sentiment.vader import SentimentIntensityAnalyzer
import nltk # this needs to be pip installed
# need the following nltk... |
# -*- ecoding : utf-8 -*- #
import re
import requests
from scrapy.spider import Spider
from scrapy.selector import Selector
from scrapy.http import Request
from medicine_info.items import *
class Evaluate(Spider):
name = "Evaluate"
custom_settings = {
'ITEM_PIPELINES' : {
'medicine_info.p... |
import base.FinanceDataSource as fd
import tushare as ts
import base.Dao as dao
def caculateMarketAnd2DB():
openDates = fd.getOpenDates()
openDates.reverse()
max_date = dao.select("select max(date) max_date from security_data", ())[0]['max_date']
min_date = dao.select("select min(date) min_date from se... |
from gtts import gTTS
import playsound
text = open('demo.txt', 'r').read()
language='en'
output = gTTS(text=text, lang=language, slow=False)
output.save('fileoutput.mp3')
# wait for the sound to finish playing?
blocking = True
playsound.playsound("fileoutput.mp3", block=blocking) |
# Install `XlsxWriter`
# pip install
import os
import pandas as pd
# Retrieve current working directory (`cwd`)
cwd = os.getcwd()
print( cwd )
# Change directory
os.chdir(r"C:\BLA\dev\python\training\my-python-snippets\tmp")
print( os.getcwd() )
# List all files and directories in current directory
print( os.listdi... |
# -*- coding: utf-8 -*-
# @Author: chenxinma
# @Date: 2018-10-01 16:04:49
# @Last Modified by: chenxinma
# @Last Modified at: 2018-10-19 15:01:45
import tensorflow as tf
import tensorflow.contrib.slim as slim
import numpy as np
import pandas as pd
import pickle
import os
from configs.config import *
from sklea... |
# This program send automatic emails
import smtplib
import pandas as pd
import os
import re
# import stdiomask as sm #used for masking input form user
from email.message import EmailMessage
import imghdr
# setting up a local smtplib server for testing
# in order to run properly, it must be start as administrator pr... |
import os
import webapp2
form="""
<form method="post">
What is your birthdate?
<br>
<br>
<label> Day
<input type="text" name="Day">
</label>
<label> Month
<input type="text" name="Month">
</label>
<label> Year
<input type="text" name="Year">
</label>
<br>
<br>
</form>
<br>
<form method="post">
... |
def solution(numbers):
answer = ''
temp = [str(i) for i in numbers]
answer = "".join(sorted(temp, key=lambda x: x * 3, reverse=True))
return answer
print(solution([0, 0, 0, 0]))
|
from django.contrib.auth.views import LoginView, LogoutView
from django.shortcuts import redirect, get_object_or_404
from authapp.forms import ShopUserLoginForm, ShopUserRegisterForm
from authapp.models import ShopUser
from django.urls import reverse_lazy
from django.views.generic import FormView
from mainpage.view... |
import sys
sys.path.append("..")
import dl2lib.query as q
import dl2lib as dl2
from context import get_context
from evaluation_queries import get_queries
from configargparse import ArgumentParser
import argparse
import torch
import signal
import time
import random
import numpy as np
parser = ArgumentParser(description... |
import sys
import numpy
sys.path.append('/d/bandrieu/GitHub/Code/Python/')
import lib_pole_of_inaccessibility as lpia
############################################
class Face:
def __init__(self, outer, inner, index):
self.outer = outer
self.inner = inner
self.index = index
##################... |
# -*- coding: utf-8 -*-
from sys import argv # importing argument support
script, input_file = argv # parsing argument into 2 variables.
def print_all(f): # defining function print_all.
print f.read() # body of function print_all. Printing whole file.
def rewind(f): # defining function rewind.
f.seek(0) # body of... |
import time
# rizhi = input("请输入今天的日志:")
# w 写入,每次会创建一个新的文件
# now = time.strftime("%Y-%m-%d-%H-%M-%S")
# print(now)
# with open("./%s日志.txt" % now, "w") as f:
# f.write(rizhi)
# a 续写
# with open("./日志.txt", "a") as f:
# f.write(rizhi)
# r 读取
with open("./日志.txt", "r") as f:
aa = f.readlin... |
import datetime
from django.views.decorators.http import require_POST
from lhwms.utils import data_search, restful, attachment
from lhwms import utils
from log.views.publicLog import log_print, errlog_add
from log.models import Errlog
from django.utils import timezone
from django.db import connection
fr... |
import unittest
from typing import Generator
from colonel.sentence import Sentence
from colonel.word import Word
from colonel.emptynode import EmptyNode
from colonel.multiword import Multiword
from colonel.base_sentence_element import BaseSentenceElement
class TestSentence(unittest.TestCase):
def test_init_wit... |
from django.shortcuts import render, redirect, HttpResponse
import requests
from django.contrib import messages
from authentication.decorators import admin_auth, admin_auth_and_server_exist
from django.contrib.auth.decorators import login_required
from problem.models import Problem, TestCase
import requests
from .model... |
import time
import json
import logging
from selenium.common import exceptions
from selenium.webdriver.remote.webelement import WebElement
from selenium.webdriver.support.select import Select
from selenium.webdriver.common.action_chains import ActionChains
from py_test.vic_tools import vic_find_object, vic_eval
from py_... |
"""
This is used to convert the data from the tfrecord files.
Created in Mai 2021
Author: Armin Straller
Email: armin.straller@hs-augsburg.de
"""
import time
import os
from os import walk
import matplotlib.pyplot as plt
from convert_single_scenario import tf_example_scenario
def get_scenarios_from_folder(path):
"... |
#-*- coding:utf-8 -*-
import web
import org.conf
from org.user import getUStat
from org.member import getMember
host=org.conf.host
cmrender=web.template.render('templates/comm')
def header():
notice=org.user.getpage(self.partnerid,'notice').replace('\n','<br />')
return cmrender.header()
def notice(partneri... |
# -*- coding: utf-8 -*-
'''
### <beg-file_info>
### document_metadata:
### - caption: "random_word_demo_py37"
### dmid: "uu733compactoraytrimming"
### date: created="2021-08-12 07:38:01"
### last: lastmod="2021-08-12 07:38:01"
### namespace:
### - nams: python/random
### - nams: progra... |
python
###########
import numpy as np
import pandas as pd
# from pandas.plotting import scatter_matrix
from regression_tools.dftransformers import (
ColumnSelector,
Identity,
Intercept,
FeatureUnion,
MapFeature,
StandardScaler)
from scipy import stats
from plot_univariate import plot_one_uni... |
# Plotting a single line is not always that useful. We can give plot
# Two lines if we want to plot them against each other
import matplotlib.pyplot as plt
myX = [i for i in range(20,30)]
myY = [i for i in range(10,0,-1)]
myY[4] = 12 # Let's just change a value so it isn't a straight line
plt.plot(myX, myY)
plt.tit... |
# Copyright 2017 Google 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 agreed to in writing... |
class Solution:
def reverseVowels(self, s: str) -> str:
i=0
j=len(s)-1
def vowel(c) -> bool:
c = c.lower()
if c=='a' or c=='e' or c=='i' or c=='o' or c=='u':
return True
return False
while i<j:
if vowel(s[i]... |
import tensorflow as tf
import numpy as np
import random
import skimage.color
import skimage.io
import skimage.transform
import scipy
import logging
def generate_anchors(scale, ratios, shape, feature_stride):
scales, ratios = np.meshgrid(np.array(scale), np.array(ratios))
scales, ratios = scales.flatten... |
from ff_espn_api import League
from getpass import getpass
from urllib import request
import os
import json
import properties
import pyfiglet
def main():
printHeader()
checkNet()
league = openLeague()
week = getWeek()
lastWeek = 0 ##last weeks poll points, will be gotten from fil... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.4 on 2017-08-17 09:36
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('news', '0007_userprofile'),
]
operations = [
migrations.AlterField(
... |
from ipaddress import IPv4Network
import random
class Sub:
def __init__(self, n='11.0.0.0', p='/8'):
self.net = n
self.pre = p
def __str__(self):
return self.net + self.pre
def getnet(self):
return self.net
def getpre(self):
return self.pre
o1 = str(random.ran... |
import fnmatch
import os
import dlib
import cv2
import json
from bs4 import BeautifulSoup
import re
import csv
import collections
import numpy as np
import matplotlib.pyplot as plt
import sys
detector = dlib.get_frontal_face_detector()
facebookDataSetPath = sys.argv[1]
metafile = os.path.join(facebookDataSetPath,"Ell... |
import gmplot
latitude_list = [ 30.3358376, 30.307977, 30.3216419 ]
longitude_list = [ 77.8701919, 78.048457, 78.0413095 ]
gmap3 = gmplot.GoogleMapPlotter(30.3164945,
78.03219179999999, 13)
# scatter method of map object
# scatter points on the google map
gmap3.scatter( latitude_list,... |
"""vincelearningweb URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.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')
Cl... |
import sys
import json
for line in sys.stdin:
line = line.strip()
dna = json.loads(line)
seqId = dna[0]
nucleotide = dna[1]
trimmedNucleotide = nucleotide[:-10]
print('%s\t%s' % (trimmedNucleotide, seqId))
|
import asyncio
import aiohttp
import aio_pika
import json
from bs4 import BeautifulSoup
from urllib.parse import urlparse
import random
from faker import Faker
fake = Faker()
import re
import polls.models.model_manager as model_manager
import polls.models.fake_model_manager as fake_model_manager
mm = model_manager... |
from dataImportJson import *
from saveVar import *
from dataIntegrity import *
from pprint import pprint
from datetime import datetime, timedelta
from io import StringIO
from sessions import divide_sessions
from sessions import print_session_summary as sessions_print_session_summary
import pkg_resources
import aiatool... |
# accounts.forms.py
from django import forms
from django.contrib.auth.forms import ReadOnlyPasswordHashField
from django.contrib.auth import authenticate
# from django_countries.countries import COUNTRIES
class ContactForm(forms.Form):
from_email = forms.EmailField(required=True, widget=forms.TextInput(
at... |
from django.contrib import admin
from .models import Clothes
admin.site.register(Clothes)
# Register your models here.
|
#
# Copyright (c) 2017 Constantine Gusev
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is di... |
#!/usr/bin/env python
# coding: utf-8
# In[1]:
import matplotlib
#matplotlib.use('Agg')
path_data = '../../assets/data/'
from datascience import *
get_ipython().run_line_magic('matplotlib', 'inline')
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
import math
import scipy.s... |
def evaluate(lelist, m):
lelist.sort()
i=0
while i<len(lelist):
if(lelist[0]+lelist[len(lelist)-1]<m):
del lelist[0]
elif(lelist[0]+lelist[len(lelist)-1]>m):
del lelist[-1]
elif(lelist[0]+lelist[len(lelist)-1]==m):
return True
elif(not leli... |
import os
import sys
import errno
import time
import cPickle as pickle
import numpy as np
from pickle import PicklingError
from haversine import haversine
from models import D4Duser
from utils import *
def main():
antennafilename = 'ContextData/SITE_ARR_LONLAT.CSV'
userfilename = 'SET2/raw/SET2_P01.CSV'
i... |
import pretty_errors
import pandas as pd
import os
import numpy as np
import openpyxl as op
import datetime
# 明天我要去月球
# 业绩外支付项目
EXTRA_ACHIEVE = ['支付会员卡赠', '支付代金券', '支付职能招待','支付转场', '支付活动赠送', '支付围台酒水', '支付宴请', '支付会员权益']
# 部门列表
DEPARTS = ["销-销售1部", "销-销售2部", "销-销售5部", "销-销售6部", "销-销售7部", "销-销售8部", "销-销售9部", "国际部", "市场部"... |
import os
import datetime
from flask import Flask, jsonify
from flask_sqlalchemy import SQLAlchemy
app=Flask(__name__)
app_settings=os.getenv('APP_SETTINGS')
app.config.from_object(app_settings)
db=SQLAlchemy(app)
class User(db.Model):
__tablename__="users"
id=db.Column(db.Integer, primary_key=True, autoinc... |
from pykeeb import DSA_KEY_WIDTH, Keyboard_matrix, project, Keyswitch_mount
from openpyscad import Cube, Sphere, Cylinder, Minkowski, Circle, Polygon
import numpy as np
# Magic numbers are harder to deal with directly
INDEX_SIDE = 0
INDEX = 1
MIDDLE = 2
RING = 3
PINKY = 4
BOTTOM_ROW = 0
CENTER_ROW = 1
TOP_ROW = 2
# ... |
from pydrake.common import FindResourceOrThrow
from pydrake.geometry import (ConnectDrakeVisualizer, SceneGraph)
from pydrake.lcm import DrakeLcm
from pydrake.multibody.rigid_body_tree import (RigidBodyTree, AddModelInstancesFromSdfFile,
FloatingBaseType, AddModelInstanceF... |
import numpy as np
from datetime import date
from pathlib import Path
def LeapYear(year):
"""
Check leap year or not
"""
if (year % 4) == 0:
if (year % 100) == 0:
if (year % 400) == 0:
return True
else:
return False
else:
... |
from stipy import *
ns = 1.0
us = 1000.0
ms = 1000000.0
s = 1000000000.0
# Set description used by program
include('channels.py')
include('motFunction.py')
include('absorptionImageFunction.py')
include('evaporativeCoolingFunction.py')
setvar('imageCropVector',(583, 375 ,300))
#setvar('imageCropVector',(500, 5... |
# General imports
from math import inf, exp, sin, cos, pi
import numpy as np
import matplotlib.pyplot as plt
#----------------------------------------#
#---------- Auxiliar Functions ----------#
#----------------------------------------#
def to_numpy(func):
"""
Decorator function to convert functions
to N... |
'''
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 use this ... |
import os
from django.db import models
from django.contrib.auth.models import User
from datetime import datetime
def get_img_path(instance, filename):
return os.path.join('image/usuarios', str(instance.id), 'profile_'+filename)
# Create your models here.
User.add_to_class('bday', models.DateField(default=dateti... |
"""
Adapting a social auth account to a user
"""
from allauth.socialaccount.adapter import DefaultSocialAccountAdapter
from allauth.account.utils import perform_login
from .models import User
class SocialAccountAdapter(DefaultSocialAccountAdapter):
"""
This class provides the option to add additional
funct... |
"""
week6_chinese_zodiac_year.py
Tuple and dictionary
"""
import sys
import math
def opening():
print()
print("Welcome to Chinese Zodiac Year.")
print("Enter your birth year to find out your Zodiac animal.")
print()
def closing():
print()
print("You didn't \"Y\".")
print("Thanks for ... |
"""
This file contains the all PDF report generator related attributes.
"""
class PDFReportGenerator(object):
"""
This class contains the all PDF report generator related attributes.
"""
def __init__(self):
"""
Init method of 'PDFReportGenerator' class.
"""
pass
|
""" This program takes a number in digits and prints out the corresponding word """
tens_dict = {1: 'ten', 2 : 'twenty', 3 : 'thirty', 4 : 'fourty', 5 : 'fifty', 6 : 'sixty', 7 : 'seventy', 8 : 'eighty', 9 : 'ninety'}
teens_dict = {0: 'ten', 1 : 'eleven', 2 : 'twelve', 3 : 'thirteen', 4 : 'fourteen', 5 : 'fifteen', 6 :... |
class Person:
def __init__(self, name, personality, isSitting=False):
self.name = name
self.personality = personality
self.isSitting = isSitting
def sit_down(self):
self.isSitting = True
def stand_up(self):
self.isSitting = False
|
from google.cloud import bigquery
def get_movie(client):
'''USED TO GET MOVIE DATA FOR DROPDOWN SELECTIONS. This function requires an authenticated google bigquery client and returns an array of hashtables with year, (genre), movie_ids, and movie_titles as keys and their corresponding values from Google Big Query... |
_author_="Vipul A M"
_email_="vipul@byclor.org"
import urllib
from google.appengine.api import urlfetch
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import db
import logging
class Registration(db.Model):
accountName=db.StringProperty(... |
from setuptools import setup, find_packages
setup(name='pymaniprob',
version='0.2.2',
author='Daniel Tait',
author_email='tait.djk@gmail.com',
url='http://github.com/danieljtait/pymaniprob',
license='MIT',
packages=find_packages(),
install_requires=['numpydoc', 'numpy', 'matpl... |
#Filname: getPic.py
import urllib2
import re
def saveFile(path,data):
f = file(path,"wb")
f.write(data)
f.close()
url = 'http://www.mnsfz.com/h/yangguang/PiaCabJHeaiaiPbiH.html'
pic = re.compile(r'img src="([^>]*?jpg)"',re.DOTALL)
html = urllib2.urlopen(url).read()
pics = pic.findall(html)
# print pics
path = 'E:... |
from django.contrib import admin
from simple_history.admin import SimpleHistoryAdmin
from .models import Avicola, Galpon, Granja
class GranjaInline(admin.TabularInline):
model = Granja
extra = 1
class AvicolaAdmin(SimpleHistoryAdmin):
history_list_display = ['nombre', ]
inlines = [GranjaInline, ]
... |
# -*- coding: utf-8 -*-
from cleo import Command
class CommandWithColons(Command):
"""
Test.
command:with:colons
{ --goodbye }
"""
|
#!/usr/bin/env python
# _*_ coding:utf-8 _*_
# _author_ = karlmarx123
import json
with open("file","r") as f:
menu = json.loads(f.read())
exit_flag = False
while not exit_flag:
print('-----省列表-----')
for province in menu:
print(province)
choice = input("请选择省,q退出>>>:")
if choice in menu:
... |
from django.test import TestCase
from django.core.urlresolvers import resolve
from .models import Post, Profile, Category
import unittest
from nose_parameterized import parameterized
|
import geo
def shapeopt_force(nodes_apx, edges_apx, nodes_t, edges_t, neighbours):
"""
:param nodes_apx: Nodes of inferred shape
:param edges_apx: Edges of inferred shape
:param nodes_t: Nodes of target shape
:param edges_t: Edges of target shape
:param neighbours: number of neighbours
:r... |
#%%
"""
Fit a polynomial force field to a dipolar signal
============================================================================
This example shows how to extract a force fields (modelled as a polynomial function)
from a dipolar signal.
"""
#%%
# Import required libraries
import numpy as np
import matplotlib... |
# -*- coding: utf-8 -*
import logging
from collections import namedtuple
from datetime import datetime, timedelta
from twisted.internet import defer
from tables import *
from twisted.python import log
from twistar.utils import joinMultipleWheres
class DatabaseInterrogator:
def __init__(self, dbpool):
Regi... |
"""
Boolean geometry union of solids.
"""
from __future__ import absolute_import
#Init has to be imported first because it has code to workaround the python bug where relative imports don't work if the module is imported as a main module.
import __init__
from fabmetheus_utilities.geometry.geometry_utilities import ... |
import pytest
from gol import XSIZE, YSIZE, tick, all_cells_are_dead, create_world
def test_world_can_be_created():
world = create_world(XSIZE, YSIZE)
def test_cell_dies_with_fewer_than_two_live_neighbours():
world = create_world(XSIZE, YSIZE)
world[10][10] = 1
tick(world)
assert world[10][10] == ... |
import requests
import random
import os
API_TOKEN = os.environ.get("TMDB_API_TOKEN", "")
def call_tmdb_api(endpoint):
full_url = f"https://api.themoviedb.org/3/{endpoint}"
headers = {
"Authorization": f"Bearer {API_TOKEN}"
}
response = requests.get(full_url, headers=headers)
response.raise_for_s... |
from Barber.Simulation import run
cabecera = "TOTAL CLIENTES;TOTAL ATENDIDOS;DESERTADOS;DESPUES DE CERRAR;PROMEDIO INTERMEDIO;PROMEDIO DE SERVICIO;PROMEDIO DE RETRASO;PROMEDIO DE ESPERA\n"
file = open('Datos.csv','w')
file.write(cabecera)
#Recolectando datos de la simulación ejecutada 100 veces con sistema de cola FIF... |
# This script browses through the "Freigegebenen Anlagen" of the SMA sunny portal website in order to find residential PV plants
# and download their generation data.
# After the initialisation of libraries and variables, the plants from the SMA plant list are extracted that are within a certain
# power range and are l... |
import cv2
import numpy as np
img = cv2.imread('bookpage.jpg')
ret,threshold = cv2.threshold(img, 12,255, cv2.THRESH_BINARY)
gray=cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
ret2,threshold2 = cv2.threshold(gray, 12,255, cv2.THRESH_BINARY)
gaus= cv2.adaptiveThreshold(gray, 255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C,cv2.THRESH_BINA... |
# coding=utf-8
from __future__ import unicode_literals
from flask.ext.login import current_user
from . import account_mod as mod
from pub_site import pay_client
from ..utils import login_required
from .. import response
@mod.route('/balance/', methods=['GET'])
@login_required
def balance():
user_id = current_user... |
# Copyright (c) 2012-2021, Mark Peek <mark@peek.org>
# All rights reserved.
#
# See LICENSE file for full license.
from typing import Optional
from .aws import Action as BaseAction
from .aws import BaseARN
service_name = "AWS Data Exchange"
prefix = "dataexchange"
class Action(BaseAction):
def __init__(self, a... |
import logging
import evdev
logger = logging.getLogger('gamepad')
logger.setLevel(logging.DEBUG)
class GamePadController:
def __init__(self, path):
self._controller: evdev.InputDevice = evdev.InputDevice(path)
logger.debug(f'gamepad: {self._controller}')
async def events(self):
asyn... |
import sys
try:
from OpenGL.GLUT import *
from OpenGL.GL import *
from OpenGL.GLU import *
except:
print '''
ERROR: PyOpenGL not installed properly.
'''
class abstractScene(object):
def __init__(self):
self.w = 500
self.h = 500
def initialize(self):
abstract
def update(self):
ab... |
def get_highest_sum(list_of_values):
list_max = 0
for values in list_of_values:
row_max = 0
for i in range(1, len(values)):
if (values[i] + values[i-1] > row_max):
row_max = values[i] + values[i-1]
if row_max > list_max:
list_max = row_max
retu... |
import pandas as pd
import glob
import xml.etree.ElementTree as ET
xml_folder = r'G:\Books\Hands On Computer Vision\code\chapter6\BCCD_Dataset-master\BCCD\Annotations/'
xml_path_list = glob.glob(xml_folder + '*.xml')
def xml2dataframe(xmlpath):
tree = ET.parse(xmlpath)
root = tree.getroot()
df = pd.DataF... |
from src.caseA import *
from src.caseB import *
from src.caseC import *
"""
access for the main program
"""
if __name__ == '__main__':
print("This is a program for control system design simulation")
choice = input("We have three different ways to do simulations, choose A, B, or C: ")
if choice ... |
def outer(f):
print 'some message com from outer function'
def inner(*arg):
print 'before function'
# f(3, 6)
print 'after function'
return inner
#
#
@outer
def func(a, b):
print func.__name__
print 'a = %s, b = %s' % (a, b)
if __name__=='__main__':
print... |
#this is the actual implementation of examplestack.py
#here we import our examplestack file
#this program show the implementation of stack in python3
import examplestack
import sys
ch='2'; ##for condition false
while ch!='1':
ch=input("\t\t\tMENU-->\n\t\t1:create stack\n\tenter your choice:");
if ch=='1':
... |
import unittest, os, time
from app import app,db
from app.models import User,Question,Answer
from selenium import webdriver
basedir = os.path.abspath(os.path.dirname(__file__))
class SystemTest(unittest.TestCase):
driver = None
def setUp(self):
self.driver = webdriver.Firefox(executable_path=os.path... |
from flask_testing import TestCase
from meetups import app, db, bcrypt
from meetups.config import TestConfig
from meetups.models import Events, Users, Guests
from datetime import date
class BaseTestCase(TestCase):
def create_app(self):
app.config.from_object(TestConfig)
return app
@classmetho... |
from adafruit_ble import BLERadio
from adafruit_ble.advertising.standard import ProvideServicesAdvertisement
from adafruit_ble.services.nordic import UARTService
from adafruit_circuitplayground import cp
import time
ble = BLERadio()
uart = UARTService()
advertisement = ProvideServicesAdvertisement(uart)
ble.start_adv... |
from flask import Blueprint, jsonify
from videoblog import logger,docs
from videoblog.schemas import VideosSchema
from flask_apispec import use_kwargs, marshal_with
from videoblog.models import Video
from flask_jwt_extended import jwt_required, get_jwt_identity
from videoblog.base_view import BaseView
videos = Bluep... |
from foodrition_api.services.ml_model import ModelFactory
from django.contrib.auth.models import User
from rest_framework.authtoken.models import Token
from django.db import IntegrityError
def foodrition_api_startup_func():
username = 'guest'
password = 'bacon'
try:
guest_user = User.objects.creat... |
import pandas as pd
import numpy as np
cars = pd.read_csv('cars.csv')
car_countries = pd.read_csv('car_countries.csv')
combined_cars = pd.merge(cars,car_countries, on='Make') #the merged tables
car_MPG = combined_cars['MPG'] #a variable for each car by mpg
car_origin = combined_cars.groupby('Origin')#a variab... |
array = ["A", "B", None, True, (1, 4)]
enu1 = list(enumerate(array))
enu11 = dict(enumerate(array))
print(enu1)
print(enu11)
print()
tup = ("A", "B", None, True, (1, 4))
enu2 = list(enumerate(tup))
enu22 = dict(enumerate(tup))
print(enu2)
print(enu22)
print()
dic = {"a": [1, 3], "b": "hello", "c": None, "d": True}
en... |
import random #makes random a useable function
import datetime #makes datetime a useable function
file = open #opens file so we can edit it
def test(): #Defines test
name=input("What is your first name: ") #Ask the user their name
sname=input("What is your surname: ") #Ask the user their surname
class_=in... |
import ccxt
import pandas as pd
from tqdm import tqdm
a = list()
exchange = ccxt.okex()
markets = exchange.load_markets()
for market in tqdm(exchange.fetch_markets()):
if market['id'][-9:] == 'USDT-SWAP':
a.append([market['symbol'][:-10], market['info']['contract_val'],
round(ex... |
from fractions import gcd
limit = 12000
result = 0
for d in xrange(limit, 4, -1):
minimum = d / 3 + 1
maximum = (d + 1) / 2
if d % 2 == 0:
step = 2
if minimum % 2 == 0:
minimum += 1
else:
step = 1
for n in xrange(minimum, maximum, step):
if gcd(n, d) ... |
# Вставка изображений и файлов в таблицу
import sqlite3
def convert_to_binary_data(filename):
# Преобразование данных в двоичный формат
with open(filename, 'rb') as file:
blob_data = file.read()
return blob_data
def insert_blob(emp_id, name, photo):
try:
sqlite_connection = ... |
"""
this is a simple guessing game using python
"""
# this whole section deals with modules , library
import random
#print(random.randint(0,100)) # generates the random numbers from o to 100
### guessing game
# we are going to use if else and random
compGuess = random.randint(0, 50 )
while True:
userGues... |
import json
from shutil import copy
from pathlib import Path
from unittest import mock
from requests import Response
from requests.auth import HTTPBasicAuth
from app import DEFAULT_CONFIG_PATH_FROM, DEFAULT_CONFIG_PATH_TO
def setup_module(module):
copy(str(Path(DEFAULT_CONFIG_PATH_FROM).resolve()), str(Path(DEFAU... |
from os import path
class CacheBase(object):
def __init__(self, cache_file_path):
self.values = []
self.cache_file_path = cache_file_path
self.__restore_cache(self.cache_file_path)
def __restore_cache(self, cache_file_path):
if not path.isfile(cache_file_path):
ret... |
x = int(input("Ingrese el valor máxinmo: "))
lista = []
for i in range(1, x+1):
if i % 5 == 0:
if i % 3 == 0:
lista.append(i)
print(lista)
|
from gym_jsbsim.task import Task
from gym_jsbsim.catalogs.catalog import Catalog as c
from gym import spaces
import math
import random
import numpy as np
import sys
"""
@author: Joseph Williams
This task isn't meant to be trained on, but rather as a test of already-trained
agents. It will run the agent through a ser... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.