text
stringlengths
8
6.05M
#!/usr/bin/python import sys from kbhit2 import TKBHit def KBHit(): kbhit= TKBHit() return kbhit.KBHit(timeout=0.1) if __name__=='__main__': import time disp= '.' while 1: c= KBHit() print c if c is not None: sys.stdout.write('> %r\n'%c) sys.stdout.flush() if c=='q': break ...
import pandas as pd import urllib.request import traceback from backend.common import * DATA_PATH = f'{get_root()}/data/world.xlsx' def consolidate_country_col(df, country_col, country_id_col, covid_df): """ This method adjusts the values in the country field of the passed DF so that the values are match...
class Rectangle: count = 0 # 클래스 변수 >> 모든 클래스가 공유해요. # 초기자(initializer) def __init__(self, width, height): # self.* : 인스턴스변수 >> 객체마다 값이 달라요. self.width = width self.height = height Rectangle.count += 1 # 메서드 def calcArea(self): area = self.width * self.he...
from wsgiref.simple_server import make_server def f1(): return "F1" def f2(): return "F2" def f3(): return "F3" routers = { "/index/": f1, "/news/": f2, "/home/": f3 } def RunServer(environ, start_response): start_response("200 OK", [('Content-Type', 'text/html')]) # return '<h1>Hello,...
from django import forms from .models import ( Utilisateur ) class Form_ajout_utilisateur(forms.Form): nom = forms.CharField(max_length=40, required=False) prenom = forms.CharField(max_length=40, required=False)
#!/usr/bin/env python # Funtion: # Filename: import urllib.request url = "http://blog.csdn.net/lovingprince/article/details/6627555" file = urllib.request.urlopen(url) file.getcode()
import sqlite3 def setUserVoice(user_id, photo): conn = sqlite3.connect('Database.db3') FH = open("voice.dat", "r") line = FH.readline() voice_id = int(line) + 1 FH.close() FH = open("voice.dat", "w") FH.write(str(voice_id)) FH.close() # Create a file object in "write" mode ...
#!/usr/bin/env python from mayavi import mlab import sys, os vtkname = sys.argv[1] src = mlab.pipeline.open(vtkname) src2 = mlab.pipeline.set_active_attribute(src, point_scalars='T') iso_surface = mlab.pipeline.iso_surface(src2) iso_surface.contour.auto_contours = False iso_surface.contour.contours[0:1] = [0.995] objna...
# 加法群 # 加法ついて群をなす(可換) from abc import abstractclassmethod, ABCMeta from typing import TypeVar AdditiveGroupType = TypeVar("AdditiveGroupType", bound="AdditiveGroup") class AdditiveGroup(metaclass=ABCMeta): # 加法 @abstractclassmethod def __add__(self: AdditiveGroup, x: AdditiveGroup) -> AdditiveGroup: ...
from schemas import BaseSchema, JSONBSchema bs = BaseSchema() bs.load() js = JSONBSchema() js.load()
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('myapp', '0001_initial'), ] operations = [ migrations.CreateModel( name='KMin', fields=[ ...
#_*_coding:utf-8_*_ from django.conf.urls import patterns, include, url urlpatterns = patterns('', url(r'^$','apps.vipuser.views.vipuser_api',name='vipuser'), url(r'^nonvipuser/?$','apps.vipuser.views.nonvipuser',name='nonvipuser'), url(r'^access_user/?$','apps.vipuser.views.access_user',name='access_user...
import os import argparse import pandas as pd from sklearn.model_selection import train_test_split from src.get_data import read_params def split_and_save_data(config_path): config = read_params(config_path) test_data_path = config['split_data']['test_path'] train_data_path = config['split_data']['train_p...
temp = int(input()) if temp > 30: print('hace calor') elif temp < 10: print('hace frio') else: print('esta bien') if temp >= 100: print('hierve') if temp <= 0: print('se congela')
import pandas as pd from sklearn.model_selection import train_test_split; from sklearn.datasets import * from sklearn.preprocessing import StandardScaler from sklearn.linear_model import LogisticRegression from sklearn.decomposition import PCA, KernelPCA from sklearn.discriminant_analysis import LinearDiscriminantAnaly...
"""This package provides statistics objects to be used by Gaussian Family likelihoods. """ # flake8: noqa
input_file = open('./twain.txt') # word_count = {} # for line in input_file: # line =line.rstrip() # words = line.split() # for word in words: # word_count[word]=word_count.get(word,0) +1 # for word, count in word_count.items(): # print(word, count) word_counts ={} for line in input_file: ...
from decimal import Decimal, getcontext getcontext().prec=60 summation = 0 for k in range(50): summation = summation + 1/Decimal(16)**k * ( Decimal(4)/(8*k+1) - Decimal(2)/(8*k+4) - Decimal(1)/(8*k+5) - Decimal(1)/(8*k+6) ) print(summation)
""" """ import phantom.rules as phantom import json from datetime import datetime, timedelta def on_start(container): phantom.debug('on_start() called') # call 'Format_Caller_Level_1' block Format_Caller_Level_1(container=container) return def Format_Caller_Level_1(action=None, success=None, con...
# coding:utf-8 class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): def numTrees(self, n): """ :type n: int :rtype: List[TreeNode] """ if n==0: return 0 g = [0 for _ in rang...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Name: RealSR ncnn Vulkan Python wrapper Author: ArchieMeng Date Created: February 4, 2021 Last Modified: February 13, 2022 Dev: K4YT3X Last Modified: February 13, 2022 """ # built-in imports import importlib import math import pathlib import sys # third-party import...
lines = [] with open("Sample Text.txt", 'r+') as f: lines = f.read().split("\n") words = [] for line in lines: for word in line.split(): words.append(word) characters = [] for word in words: for character in word: characters.append(character) print("Number of Lines :", len(lines)) print...
{ PDBConst.Name: "family", PDBConst.Columns: [ { PDBConst.Name: "ID", PDBConst.Attributes: ["int", "not null", "auto_increment", "primary key"] }, { PDBConst.Name: "Name", PDBConst.Attributes: ["varchar(128)", "not null"] }], PDBConst.Initials: [ {"Nam...
import sys import paper_scissor_rock if __name__ == "__main__": game = paper_scissor_rock.RockPaperScissors() # options needed to RockPaperScissors instance with parameters # options = {'rock': 0, 'paper': 1, 'scissors': 2} # test_dict = { # "ties": 0, # "wins": 0, # "losses":...
# ----------------------------------------------------------------------------- # Copyright (c) 2014--, The Qiita Development Team. # # Distributed under the terms of the BSD 3-clause License. # # The full license is in the file LICENSE, distributed with this software. # ------------------------------------------------...
from django.conf import settings from daemonextension import DaemonCommand from django.core.management import call_command class Command(DaemonCommand): def handle_daemon(self, *args, **options): options.pop('pidfile',None) call_command('celerycam',*args,**options)
# Generated by Django 2.2.6 on 2019-10-27 10:07 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('techei', '0031_eventimage'), ] operations = [ migrations.AlterField( model_name='eventimage', ...
"""模块的公开方法. 避免让外部直接访问定义的对象,以此来进行解耦. """ import contextlib from typing import Type from playhouse.db_url import connect from .user import User from ._base import ( db, BaseModel, Tables ) def bind_db(dburl: str): """指定数据库的url初始化代理对象并创建表. Args: dburl (str): 支持peewee所支持的数据库url写法 """ ...
soma = 0 cont = 0 for c in range(1,7): n= int(input(f'Digite o {c}º valor: ')) if n % 2 == 0: cont += 1 soma += n print(f'Você informou {cont} número(s) par(es), e a soma entre todos eles é {soma}')
from random import randrange def playgame(): Choices = ["Rock","Paper","Scissors","ROCK","PAPER","SCISSORS","rock","paper","scissors","R","P","S","r","p","s"] choosing = True user_input = 0 while choosing: user_input = raw_input("Rock(r), Paper(p), or Scissors(s): ") if user_i...
# -*- coding: utf-8 -*- from snippets.admin.actions import deactivate_action, activate_action # NOQA from snippets.admin.filters import IsNullFieldListFilter # NOQA from snippets.admin.admin import SuperUserDeletableAdminMixin, BaseModelAdmin # NOQA
from collections import deque def solve(data, upper): sorted_intervals = deque(sorted([(int(start), int(end)) for line in data for start, end in [line.split('-')]], key=lambda x: x[0])) # [(0, 2), (4, 7), (5, 8)] answers = [] total, n, index = 0, 0, 0 while n < upper: start, end = sorted_in...
# Author : Dharatiben Shah # Date : 04-17-2021 import os import sqlite3 import random from getpass import getpass # create a database - sqllite3 as it comes with python installation # this will create a database called "auth.sqlite3" in the same directory as the script DEFAULT_PATH = os.path.join(os.path.dirname(...
from ED6ScenarioHelper import * def main(): # 蔡斯 CreateScenaFile( FileName = 'T3105 ._SN', MapName = 'Zeiss', Location = 'T3105.x', MapIndex = 1, MapDefaultBGM = "ed60084", Flags = 0, En...
#Oops Concept class Cars: def __init__(self,name,color,price): self.name = name self.color = color self.price = price def start(self): print(self.name + " Engine started") car1 = Cars("Maruti", "Red", 10000) car2 = Cars("BMW", "Black", 200000) print(car1.name, car1...
from django.db import models class Residence(models.Model): residence = models.CharField(max_length=20, verbose_name='Residencia') class Meta: verbose_name = 'residencia' verbose_name_plural = 'residencias' def __str__(self): return self.residence.title() class Category(models....
import pandas as pd from sklearn import datasets from kmeans import mkmeans from make_gif import make_gif, delete_png if __name__ == '__main__': # load data wine = datasets.load_wine() wine_df = pd.DataFrame(wine.data, columns=wine.feature_names) # execute sample_df = mkmeans(wine_df, ['alcohol',...
""" Module with invoke tasks """ import invoke import net.invoke.analyze import net.invoke.host import net.invoke.train import net.invoke.tests import net.invoke.visualize # Default invoke collection ns = invoke.Collection() # Add collections defined in other files ns.add_collection(net.invoke.analyze) ns.add_coll...
# Write a Python program that asks the user for the radius of a circle. # Next, ask the user if they would like to calculate the area or circumference of a circle. # If they choose area, display the area of the circle using the radius. # Otherwise, display the circumference of the circle using the radius. #Area = πr^2...
from turtle import * colors=["red","blue","brown","yellow","grey"] for n in range(3, 8): for i in range(n): color(colors[n-3]) forward(100) left(360/n) from turtle import * colors = ["red","blue","brown","yellow","grey"] for n in range(0,5): begin_fill() color(colors[n...
#config.py WIN = True
#__author: "Jing Xu" #date: 2018/1/23 import sys import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) sys.path.append(BASE_DIR) from module import main main.main()
# -*- coding: utf-8 -*- """ Tencent is pleased to support the open source community by making 蓝鲸智云PaaS平台社区版 (BlueKing PaaS Community Edition) available. Copyright (C) 2017-2020 THL A29 Limited, a Tencent company. All rights reserved. Licensed under the MIT License (the "License"); you may not use this file except in co...
#!/usr/bin/python3 # -*- coding:utf-8 -*- # author: Stanford cs231n 2016 winter assignment teaching-assistant, Justin Johnson # modified by zhaofeng-shu33 import numpy as np def rel_error(x, y): """ returns relative error """ return np.max(np.abs(x - y) / (np.maximum(1e-8, np.abs(x) + np.abs(y)))) def eval_numeric...
from pyquil.quilbase import * from pyquil.gates import QUANTUM_GATES from quil_run import quil_run class MeasurementReset(AbstractInstruction): """ This is the pyQuil object for a Quil measurement instruction. """ def __init__(self, qubit, classical_reg): if not isinstance(qubit, (Qubit, Qubit...
#!/usr/bin/python3 from sys import argv, stdin from docopt import docopt from collections import defaultdict import re import codecs from signal import signal, SIGPIPE, SIG_DFL doc = r""" Usage: ./column.py [options] [<input> ...] -h,--help show this -s,--separator <sep> specify t...
from flask import Blueprint, render_template, request, redirect, url_for import json import os from . import crud import sys main = Blueprint('main', __name__) #cannot define function and use in a route. try creating a module of functions and importing @main.route('/') def index(): lists = crud.read_lists() return...
import subprocess from tests import helpers as h from tests.paths import LIB_SH class Case: def __init__(self, args, rc, stdout, stderr): self.args = args self.rc = rc self.stdout = stdout.encode() self.stderr = stderr.encode() def __str__(self): return self.args.repl...
import cv2 import numpy as np image = cv2.imread('image.jpg') img_bgr = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) template = cv2.imread('template.jpg', 0) w, h = template.shape[::-1] res = cv2.matchTemplate(img_bgr, template, cv2.TM_CCOEFF_NORMED) res1 = cv2.cvtColor(res, cv2.COLOR_GRAY2BGR) threshold = 0.8 loc = np.wh...
# Generated by Django 2.1.15 on 2020-02-21 05:44 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('ibookApp', '0005_auto_20200221_1049'), ] operations = [ migrations.AddField( model_name='feeds', name='byEmailID', ...
# simple network to demonstrate what the contours of the cost # function look like in various scenarios # now stochastic... import matplotlib.pyplot as plt import numpy as np import pdb m = 200 X = np.random.randn(2, m) Y = np.zeros(m) p_range = [[-3, 3], [-3, 3]] # generate the data for i in range(0, m): if 1*X[...
from setuptools import setup, find_packages version = '0.9.4' long_description = open("README.txt").read() long_description += """ CHANGES ========== """ long_description += open("CHANGES.txt").read() setup(name='fa.extjs', version=version, description="jQuery widgets for formalchemy", long_descrip...
import turtle turtle.shape("turtle") turtle.speed(4) # 궁극의 방법 def drawSomething(size, angle): for i in range(angle): turtle.forward(size) turtle.right(360/angle) drawSomething(100, 5) drawSomething(200, 6) drawSomething(10, 10)
from django.conf.urls import url from areas import views from rest_framework.routers import DefaultRouter urlpatterns = [ ] # 1 创建路由 router = DefaultRouter() # 2 注册路由 router.register(r'infos',views.AreaViewSet,base_name='area') # 3 将router自动生成的url添加到urlpatterns urlpatterns += router.urls
import json import requests op = -1 def imprimirHabitacion(habitacion): id = habitacion['id'] plazas = habitacion['plazas'] equipamiento = habitacion['equipamiento'] n = len(equipamiento) cadequip = equipamiento[0] if(n > 1): i = 1 while(i < n): if(i < n-1): ...
try: result = 4/0 print(result) except Exception as e: print(e) print("Program End")
from sample_device.tsne_ecg import scatter from np_datasets_wizard.json_to_np_randomly import get_numpy_from_json from np_datasets_wizard.json_to_np_by_qrs import get_numpy_from_json as get_np_by_shift from sample_device.utils import load_json from settings import PATH_TO_METADATASETS_FOLDER from np_datasets_wizard.dow...
import sqlite3 #name = input() #idade = input() db = sqlite3.connect("projeto.db") c1 = db.cursor() c1.execute("select * from users") for item in c1.fetchall(): print(item) c1.close() #db.commit()
a = int(input()) b = int(input()) s = a * b print(s)
# -*- coding: utf-8 -*- import time from report import report_sxw import logging _logger = logging.getLogger('reportes') class reportes_report_v(report_sxw.rml_parse): gran_cantidad = 0.0 gran_exento = 0.0 gran_neto = 0.0 gran_iva = 0.0 gran_total = 0.0 final_exento=0.0 final_neto=0.0 final_iva=0.0 final_...
import config from sqlalchemy import create_engine import pandas as pd ## Enter DBname here config.POSTGRES_DBNAME = 'dvdrental' ## Connection string postgres_str = ('postgresql://{username}:{password}@{ipaddress}:{port}/{dbname}'.format(username=config.POSTGRES_USERNAME, ...
import logging import argparse import os import json from os.path import join as pjoin import tarfile import errno from utils import sha1_for_path, canonical_path, makedirs, mygzip from .models import (ZincIndex, load_index, ZincError, ZincErrors, ZincOperation, ZincConfig, load_config, ZincManifest, load_man...
from sqlalchemy.dialects.postgresql import HSTORE as HSTOREBase from sqlalchemy.ext.mutable import MutableDict class HSTORE(HSTOREBase): """ Extends the default HSTORE type to make it mutable by default. """ MutableDict.associate_with(HSTORE)
import time from selenium.common.exceptions import NoSuchElementException from threading import Thread from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from to_import_secret import sendEmail, comandExecutor from to_im...
import numpy as np import os import pytest import unittest from geopyspark.geotrellis import SpatialKey, Extent, Tile from geopyspark.geotrellis.layer import TiledRasterLayer from geopyspark.tests.base_test_class import BaseTestClass from geopyspark.geotrellis.constants import LayerType, Operation, Neighborhood from g...
# Create your views here. #from django import form import urlparse import settings from django.http import HttpResponse, HttpResponseRedirect from django.core.urlresolvers import reverse from django.template import Context, loader, RequestContext from django.views.decorators.debug import sensitive_post_parameters fro...
#!/usr/bin/env python3 import pandas as pd csvData = pd.read_csv("data/MOCK_DATA.csv") #print(csvData) print()
from django.urls import path from . import views app_name = 'afrivent' urlpatterns = [ path('', views.home, name="home"), path('all/events', views.all_events, name="all-events"), path('event-order/details/<int:eventId>', views.event_order_details, name='event-order-details'), path('edit/event/<event_s...
#!/usr/bin/python3 def common_elements(set_1, set_2): new_list = [] for i in set_2: for b in set_1: if (i == b): new_list.append(i) return new_list
import sys import numpy as np # r_tags={0,1,2,3,4,5,6,7,8,9,10,11,12} # map_dict={'institution': 4, 'journal': 5, 'booktitle': 1, 'pages': 8, 'author': 0, # 'note': 7, 'editor': 3, 'publisher': 9, 'location': 6, 'date': 2, 'tech':10, 'title':11, 'volume':12} r_tags = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12} map_dic...
import csv import os import math import os.path import ROOT def formatUnc(unc): return "{0:4.3f}".format(unc) tableHeader=["","systematic"] tableTotal=["","total uncertainty"] tableRows=[ ['stat', "statistical"], ["line"], #fitting ['fiterror', "ML-fit uncertainty"], ['diboson', "Diboson fraction"], ['...
# -*- coding: utf-8 -*- __author__ = 'Yuvv' import functools from predictor.models import Rule, Knowledge def valid_rule_filter_fixed(rule, knowledge): rule.cf_e = 0 if rule.relationship == '&': for rkf in rule.related_knowledge_factor.all(): if rkf.mark.mark not in knowledge: ...
import os import signal from string import Template import subprocess import time from TdcPlugin import TdcPlugin from tdc_config import * class SubPlugin(TdcPlugin): def __init__(self): self.sub_class = 'ns/SubPlugin' super().__init__() def pre_suite(self, testcount, testidlist): '''...
#!/usr/bin/env python # Copyright (c) 2011, 2012 Nicira, 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 appli...
# -*- coding: utf-8 -*- import nysol._nysolshell_core as n_core from nysol.mcmd.nysollib.core import NysolMOD_CORE from nysol.mcmd.nysollib import nysolutil as nutil class Nysol_Mnewnumber(NysolMOD_CORE): _kwd ,_inkwd,_outkwd = n_core.getparalist("mnewnumber",3) def __init__(self,*args, **kw_args) : super(Nysol_...
import random import socket import sys import tqdm import os import numpy as np PRIME_LIMIT = 1000000000 # Check if number is prime def is_prime(num): if num == 2: return True if num < 2 or num % 2 == 0: return False for n in range(3, int(num ** 0.5) + 2, 2): if num % n == 0: return False return True # ...
#!/usr/bin/env python import rospy from geometry_msgs.msg import PoseStamped from geometry_msgs.msg import Twist def position_command_talker(): pub = rospy.Publisher('/drone_1/cmd_vel', Twist, queue_size=100) #pub_2 = rospy.Publisher('/drone_2/command/pose', PoseStamped, queue_size=100) rospy.init_node('v...
#!/usr/bin/python3 MyInt = __import__('100-my_int').MyInt my_i = MyInt(3) print(my_i) print(my_i == 3) print(my_i != 3)
#箐优网APP签到脚本 import requests import json #sever酱SCkey SCkey = '***********' Cookie = '*************************' ##################################################以下内容请勿修改############################################### def start(): headers={ 'version': '139', 'authorization': 'Token 9...
ans = [0] for x in range(1,10): for y in range(1,x+1): print(y,end='') print("\n")
#!/etc/anaconda3/bin/python import tensorflow as tf import os import numpy as np from attr import Attr # Setup the configuration for GPU #os.environ['CUDA_VISIBLE_DEVICES'] = '0' #config = tf.ConfigProto() #config.gpu_options.per_process_gpu_memory_fraction = 0.19 #session = tf.Session(config=config) def next_batch(n...
s='aaabbaa' s.replace('a','z')
"""Drop SurveyAnswer flag Column Revision ID: eb83b734b11d Revises: f6f2d282fd3f Create Date: 2018-12-09 10:53:38.674905 """ from alembic import op import sqlalchemy as sa from sqlalchemy.dialects import mysql # revision identifiers, used by Alembic. revision = 'eb83b734b11d' down_revision = 'f6f2d282fd3f' branch_la...
#!/usr/bin/env python from lib.command.remove_command import RemoveCommand if __name__ == '__main__': command = RemoveCommand() command.run()
#导入外部函数库 from selenium import webdriver from time import sleep from bs4 import BeautifulSoup import urllib.request import os #导入自建函数库 from make_pic2pdf import conpdf #定义要处理网页、浏览器位置、存储路径 url = 'https://wenku.baidu.com/view/6e329617580102020740be1e650e52ea5418ce76.html?sxts=1537239654915' chrome_path = 'E:\汪...
import sys, os sys.path.append(os.path.abspath('C:/Users/Maciek/Desktop/stepik/lab1/zad3/src/App.py')) import unittest from src import App song = App.song class SongTest(unittest.TestCase): def test_one_verse_first(self): self.assertEqual(song.sing(2), "On the second day of Christmas my true love gave to m...
import formatNum as fN import os import urllib __author__ = 'syao' def _fetch(file_url, local_file_name): print 'start download from {}'.format(file_url) if not os.path.exists(local_file_name): urllib.urlretrieve(file_url, local_file_name) print '{} is completed!'.format(local_file_name) ...
#-*- coding:utf8 -*- __author__ = 'meixqhi' import json import time import random from django.db import models from django.db.models import Sum from shopback.base.models import BaseModel from shopback.base.fields import BigIntegerAutoField,BigIntegerForeignKey from shopback.users.models import User from shopback.monito...
# pragma pylint: disable=missing-docstring, invalid-name, pointless-string-statement # --- Do not remove these libs --- import numpy as np # noqa import pandas as pd # noqa from pandas import DataFrame from freqtrade.strategy.interface import IStrategy # -------------------------------- # Add your lib to impor...
# ----------------------------------------------------------------------------- # Copyright (c) 2014--, The Qiita Development Team. # # Distributed under the terms of the BSD 3-clause License. # # The full license is in the file LICENSE, distributed with this software. # ------------------------------------------------...
#MUHAMMET ENES AY import time urunler = dict() keyler=[] # unique barkod numaralari olusturmak için kontrol saglıyor def ana(): print( """***DEPO STOK TAKİP OTOMASYONU*** 1)ÜRÜN EKLE \n2)ÜRÜN GÜNCELLE \n3)ÜRÜN ARA \n4)ÜRÜN SİL \n5)KDV'Lİ FİYAT HESAPLA \n6)ÜRÜN LİSTELE \n7)SATIŞ YAP \n8)STOK KONTROL\n9...
data = [] with open('/home/cyagen1/Downloads/rosalind_seto.txt','r') as f: for line in f: data.append(line.strip('\n')) U = set(str(i)for i in range(1, int(data[0])+1)) A = set([x for x in data[1].strip('{}').replace(' ','').split(',')]) B = set([x for x in data[2].strip('{}').replace(' ','').split(',')]) ...
import tkinter as tk from tkinter import ttk class Checkbar(tk.Frame): def __init__(self, parent=None, picks=[], side=tk.LEFT, anchor=tk.W): tk.Frame.__init__(self, parent) self.setUsers(picks) def state(self): return map((lambda var: var.get()), self.vars) def setUsers(self, userList): ...
# -*- coding: utf-8 -*- import logging from collections import OrderedDict try: import PyV8 except: pass from .abstract import AbstractBackend from .exceptions import ArgumentError, JSFunctionNotExists __all__ = ['PyV8Backend', ] class PyV8Backend(AbstractBackend): """ Backend class for PyV8 """ lo...
# Test # Local settings for kegbot. # Edit settings, then copy this file to /etc/kegbot/local_settings.py or # ~/.kegbot/local_settings.py # Disable DEBUG mode when serving external traffic. DEBUG = True TEMPLATE_DEBUG = DEBUG import os ### Database configuration import dj_database_url DATABASES = {'default': dj_dat...
def float_to_binary(f): BINARY_LENGTH = 32 assert 0 <= f <= 1 binary = ['0' for i in range(32)] base = 1. for i in range(BINARY_LENGTH): if f == 0: break base /= 2 if f >= base: f -= base binary[i] = '1' if f != 0: return None...
""" Copyright (c) Microsoft Corporation. Licensed under the MIT License. """ from setuptools import setup, find_packages from mechanical_markdown import __version__ as version # The text of the README file README = "" try: with open("README.md", "r") as fh: README = fh.read() except FileNotFoundError: ...
# Generated by Django 2.1.7 on 2019-03-31 17:37 import django.core.validators from django.db import migrations, models import django.db.models.deletion import main.fields import main.models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.C...
from django.urls import path from .views import RealtorListView,RealtorView,TopSellerView urlpatterns = [ path('',RealtorListView.as_view()), path('topseller',TopSellerView.as_view()), path('<pk>',RealtorView.as_view()) ]
#Iris Identification import numpy as np import csv syn=[] X=[] y=[] def getData(): data=[] with open('../data/006/iris.csv','r') as f: spamreader=csv.reader(f) for row in spamreader: i=[] for thing in row: i.append(float(thing)) data.append...