text
stringlengths
8
6.05M
""" Note, sort the input.txt file numerically before running sort -n input.txt > tmp.txt && mv -f tmp.txt input.txt """ import sys class Project(object): def __init__(self, fh): self.input = fh def int_to_ip(self, data): binary = bin(data)[2:].zfill(32) sects = [] while len(b...
import os,sys,re import json import operator import itertools import common from common import * import logging logger = logging.getLogger('logcat') class LogcatLogLine(object): THREADTIME_PATTERN = re.compile(r'(?P<date>\d{4}-\d{2}-\d{2})\s+(?P<time>\d{2}:\d{2}:\d{2}.\d+)\s+(?P<pid>\d+)\s+(?P<tid>\d+)\s+(?P<prior...
import tensorflow as tf x1 = tf.constant([2, 3, 4]) x2 = tf.constant([4, 0, 1]) y = tf.add(x1, x2) with tf.Session() as sess: print(sess.run(y))
from game.items import HollowLog from game.models.model import Tree from game.skills import SkillTypes class HollowTree(Tree): name = 'Hollow Tree' health = 1 xp = {SkillTypes.woodcutting: 82.5} skill_requirement = {SkillTypes.woodcutting: 45} resource = HollowLog
from django.shortcuts import render from django.conf import settings from django.http import HttpResponse , HttpResponseBadRequest,HttpResponseForbidden from django.views.decorators.csrf import csrf_exempt from linebot import LineBotApi,WebhookParser from linebot.exceptions import InvalidSignatureError ,LineBotApiErr...
film_type = input().lower() rows = int(input()) cols = int(input()) total_seats = rows * cols price_Of_Billet = 0.0 if film_type == "premiere": price_Of_Billet = 12.0 elif film_type == "normal": price_Of_Billet = 7.50 elif film_type == "discount": price_Of_Billet = 5.0 money_earned = price_Of_Billet * t...
# -*- coding: utf-8 -*- import tkinter as tk # 使用Tkinter前需要先導入 # 第1步,產生實體object,建立視窗window window = tk.Tk() # 第2步,給窗口的視覺化起名字 window.title('My Window') # 第3步,設定窗口的大小(長 * 寬) window.geometry('500x300') # 這裡的乘是小x # 第4步,grid 放置方法 for i in range(3): for j in range(3): tk.Label(window, text=1).grid(row...
from selenium import webdriver import time import os driver = webdriver.Chrome() file_path = 'file:///'+os.path.abspath("C:\\课件\\我的课件\\测试\\selenium2\\locateElement\\selenium2html\\modal.html") driver.get(file_path) driver.maximize_window() #点击click driver.find_element_by_id("show_modal").click() time.sleep(5) #点击 clic...
from surveymonkey.calls.base import Call class Collectors(Call): def __create_collector(self, survey_id, collector, **kwargs): params = { 'survey_id': survey_id, 'collector': collector } assert collector.get('type') == 'weblink', \ "Only supported colle...
# connection to database is done by this file # has to be included in main.py before importing the views # as we are using mongo-db as our database # the database name should be lunchbox and collection should be same view names # I'm guessing we are using pymongo for now # import necessary libraries & just create a cl...
import numpy as np import pandas as pd import h5py import json import os os.chdir('C:/Users/llavin/Desktop/PRAS') from HDF5_utils import load_seams,clean_tx,clean_gen,add_gen,create_gen_failure_recovery_cols,HDF5Case #data loads #pickle these eventually to speed up code seams_transmission_df = load_seams...
import gmpy2 import rsa p = 275127860351348928173285174381581152299 q = 319576316814478949870590164193048041239 n = 87924348264132406875276140514499937145050893665602592992418171647042491658461 e = 65537 d = int(gmpy2.invert(e , (p-1) * (q-1))) privatekey = rsa.PrivateKey(n , e , d , p , q) #根据已知参数,计算私钥 with open("flag...
import math def _iterate_first_quartor(N): y = x = 0 # The quartor should include the right boarder for y in range(0, (N+1)//2): # The quartor does not include the bottom boarder for x in range(0, N//2): yield (y, x) def _rotate_coordinate(y, x, N): new_y = x new_x = N ...
from django.apps import AppConfig class PhishingDetectionConfig(AppConfig): name = 'phishing_detection'
from preprocess_rnn import get_data from keras.models import Sequential from keras.layers import Bidirectional, Masking import h5py from keras.layers.core import Dense, Dropout from keras.layers.recurrent import LSTM from keras.layers.normalization import BatchNormalization feature_size = 39 import numpy as np def cre...
import csv from get_data import GetData from lineup import Lineup from opt import Opt def get_credentials(): with open('./data/credentials.csv', "r") as f: reader = csv.reader(f, delimiter="\t") credentials = [] for line in reader: if ',' in line[0]: credential...
#from sympy.logic.utilities.dimacs import load_file,load from os.path import join import math import re sudoku_rules_path = "input" sudoku_rules = { 4 : "sudoku-rules-4x4.txt", 9 : "sudoku-rules-9x9.txt", 16 : "sudoku-rules-16x16.txt" } # For SUDOKU-16, 10-16 become A-E def letter_gen(x): if x >= 10: ...
import xml.etree.cElementTree as ET import re import csv import codecs import cerberus from unittest import TestCase import a_audit_data import c_create_schema lower_case_colon = re.compile(r'^([a-z]|_)+:([a-z]|_)+') problematic = re.compile(r'[=\+/&<>;\'"\?%#$@\,\. \t\r\n]') OSM_PATH = "data/bengaluru_india.osm" N...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ ``__hash__(self)`` 定义了 hash(obj)的行为。 """ class MyClass(object): def __init__(self, a): self.a = a def __hash__(self): return hash(self.a) def __eq__(self, other): return self.a == other.a if __name__ == "__main__": m1 = MyC...
''' Created on Nov 16, 2014 @author: Jigar ''' from __future__ import division import numpy import timeit time = -timeit.default_timer() path=r'fv3.txt' file1=open(path,'r') content=file1.read() data=content.split("\n") data=data[:-1] data=data[1:] fv = [] for datas in data: arr =eval(datas) for i in range(0,...
import re from collections import Counter # Using Viterbi Algorithm to find the hidden states in the given text def viterbiAlgorithm(text): probs = [1.0] lasts = [0] for i in range(1, len(text) + 1): temp_prob_k = 0 temp_k = 0 for j in range(max(0, i - max_word_length), i): ...
# all endpoints related to institution view from flask_app import * from db_connector import * from common import * from bson.json_util import dumps import json #Signup @app.route('/api/v1/institution/signup', methods = [ 'POST' ] ) def signup(): if request.method == 'POST': i_name = request.json.get('i_...
''' Created on 02.09.2018 @author: FM ''' import unittest import unittest.mock as mock from test.testing_tools import mock_scandir_gen, mock_assert_msg, mock_assert_many_msg import CLI from CLI import detect_file_sets mock_scandir = mock.MagicMock(name='scandir') mock_FileSet = mock.MagicMock(name='FileSe...
#!/usr/bin/env python PACKAGE="asr_direct_search_manager" from dynamic_reconfigure.parameter_generator_catkin import * gen = ParameterGenerator() # Name, Type, Reconfiguration level, # Description, # Default, Min, Max gen.add("fovH", double_t, 0, "", 15.0, 0.0, 1000.0) gen.add("fovV", double_t, 0, "", 10.0, 0.0...
from datetime import datetime, timedelta import pymysql.cursors from pymysql import MySQLError, converters import lab4.rozwiazanie.nbp as nbp # Connect to the database conv = converters.conversions.copy() conv[10] = str connection = pymysql.connect(host='localhost', user='root', ...
from __future__ import division import os import numpy as np import scipy.io as sio from imageio import imread import torch import torch.utils.data as data from datasets import pms_transforms from . import util np.random.seed(0) class UpsDiLiGenTDataset(data.Dataset): def __init__(self, args, split='train'): ...
myset = {"apple", "banana", "cherry"} print(myset) for x in myset: print(x) myset.add("orange") print(myset) myset.update(["grapes","mango"]) print(myset) myset.remove("banana") #myset.remove("banana1") #KeyError: 'banana1' print(myset) myset.discard("cherry") myset.discard("cherry1") print(myset) myset.pop() pri...
# -*- coding: UTF-8 -*- # Copyright 2018 Rumma & Ko Ltd # License: BSD (see file COPYING for details) """ A user interface for Lino applications that uses FaceBooks React JS framework. .. autosummary:: :toctree: views renderer models """ from lino.api.ad import Plugin class Plugin(Plugin): # u...
import unittest from PageObjModelDemo.tests.googleSearchTest import GoogleSearch from PageObjModelDemo.tests.newLogin import NewLoginTests from PageObjModelDemo.tests.loginTests import LoginTests from PageObjModelDemo.Utilities.Utils import Utils testCase1 = unittest.TestLoader().loadTestsFromTestCase(GoogleSearch) ...
"""Модуль юнит-теста. Проверяет код ответа фласка, проверяет тестовую страницу.""" import unittest import os import sys import inspect current_dir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))) parent_dir = os.path.dirname(os.path.dirname(current_dir)) sys.path.insert(0, parent_dir) impor...
""" Flatten ¯¯¯¯¯¯¯ This function can be used to flatten a message, whose elements are deeply nested in groups. """ import json import collections def flatten(d, parent_key='', sep='_'): """ source: https://stackoverflow.com/a/6027615 :param d: The dict, representing the json message :param parent_key...
from PIL import Image from tools.image import sliding_window, draw_red_square, create_dump_folder_for_images, convert_image_to_array, get_percentage_of_white from tools.classifier import get_trained_classifier from sklearn.svm import SVC from sklearn.neighbors import KNeighborsClassifier from sklearn.neural_network imp...
from django.core.urlresolvers import reverse from django.core.exceptions import MultipleObjectsReturned from django.utils.safestring import mark_safe from django.http import HttpResponse def export_csv(modeladmin, request, queryset): import csv from django.utils.encoding import smart_str response = HttpRes...
# coding: utf-8 # ##A. match_ends # Given a list of strings, return the count of the number of strings where the string length is 2 or more and the first and last chars of the string are the same. # Note: python does not have a ++ operator, but += works. # In[22]: def match_ends(words): count=0 for i in wo...
#!/usr/bin/python # -*- coding: utf8 -*- """ AstroRobot Exceptions """ from __future__ import unicode_literals class InitError(Exception): """ A class to represent incorrect setting up of your situation """ pass class DownloadingError(Exception): """ When a download / http fetch fails. ...
import cStringIO, gzip ''' Helper function to gzip JSON data (used in data API views)''' def gzip_data(json): # GZip all requests for lighter bandwidth footprint gzip_buffer = cStringIO.StringIO() gzip_file = gzip.GzipFile(mode='wb', compresslevel=6, fileobj=gzip_buffer) gzip_file.write(json) gzip_...
''' author: juzicode address: www.juzicode.com 公众号: juzicode/桔子code date: 2020.6.2 ''' print('\n') print('-----欢迎来到www.juzicode.com') print('-----公众号: juzicode/桔子code\n') print('list类型例程:') print('\nlist添加元素-extend:') l1 = [1,2,3] print('l1:',l1) l1.append([4,5,6]) print('l1经过append后:',l1) l2 = [1,2,3] print('l2...
#coding=utf-8 #1. Study how to get text by attrs # <span class="body"> xxx </span> ==> tag.find(attrs="body") #<div class="content"> ==> tag.find(attrs="content").get_text()[1:] # <div id="qiushi_tag_118914192" class="article block untagged mb15"> ==> soup.find_all(attrs="article block untagged mb15"), tag['id'] ...
""" thing module """ class Thing(object): """ Thing """ def __init__(self): pass
# Django from django.http import HttpResponseRedirect from django.http import JsonResponse from django.urls import reverse def login_required(f): def wrap(self, request, *args, **kwargs): if not request.user: return HttpResponseRedirect(reverse("login")) return f(self, request, *args, ...
# BUCKET-SORT(A) # Sorts the array A containing values that are distributed over the interval [0, 1) given by some given uniform distribution # X. The interval [0, 1) is divided into n-equal sized buckets (or subintervals). Since the inputs are unformaly distributed, # bucket sizes should be small. We then simply sort ...
''' Permutations without Dups: Write a method to compute all permutations of a string of unique characters. ''' def getPerm(str): if str is None or len(str) == 0: return None return getPermHelper(str) def getPermHelper(str): if len(str) == 0: return [""] firstChar = str[0] remainingPerm = getPermHelper(str[1...
#!/usr/bin/python # -*- coding: utf-8 -*- # @author: Tangxiaocu def talk_with_daddy(): def main(): who = '糖小醋的老妈 ' good_description = "西双版纳大白菜" is_cheap = False good_price = 2 #每降低一元,多买一斤 reasonable_price = 5 buy_amount = 2 #每降低一元,多买一斤 print '%s上街看到了%s, 卖 %d 元/斤' % (who, good_description, good_pri...
#!/usr/bin/env python """Variable Scope - Global variables, varaibles that are visible inside and outside of functions. NOTE: careful with assigning names to globals, as you could 'expose' this to other functions in your workspace/namespace""" __author__ = 'Saul Moore (sm5911@imperial.ac.uk)' __version__ = '0.0.1' _...
import logging from math import sqrt from configparser import ConfigParser class Data_Processing(object): def __init__(self, comm): self.logger = logging.getLogger('COMM') self.logger.info("[+] Initializing Data Processor") self.config = ConfigParser() self.config.read('config.ini') self.frame_rate = se...
__author__='alberto'
from tabula import read_pdf, convert_into #can convet into csv , json filename = "name of file" d = convert_into(filename, "test.csv", output_format="csv" , pages="all")
from django.db import connection def get_data(self): with connection.cursor() as cursor: cursor.execute( "SELECT count(character_id) FROM death_manner WHERE manner!='Unknown' GROUP BY manner ORDER BY count(character_id) DESC LIMIT 10;") data = cursor.fetchall() return data def ...
""" Sample Controller File A Controller should be in charge of responding to a request. Load models to interact with the database and load views to render them to the client. Create a controller using this template """ from system.core.controller import * import oauth2 as oauth import json import os ...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('invoice', '0001_initial'), ('case', '0015_auto_20170706_0105'), ] operations = [ migrations.RemoveField( ...
# -*- coding: UTF-8 -*- from nltk.util import ngrams import sys import operator n = int(sys.argv[2]) #print n i = 0 mydict={} temp=[] #輸入第一個值 是檔案名稱 file_input = file(sys.argv[1],"r") file_output = open("Data_Output.txt", "w",) while True: line = file_input.readline() #replace mark line=line.replace('\n',' ') ...
#!/usr/bin/env python distance_file = open('distance.txt', 'r+') snmp_file = open('host2_log.txt', 'r+') #signal_file = open('wlan0_output.txt', 'r+') distance = distance_file.readlines() snmp = snmp_file.readlines(); #signal = signal_file.readlines(); final_product = "" for snmp_line in snmp: combine_line = ...
import numpy as np import matplotlib.pyplot as plt xpoints = np.array(range(1, 101)) ypoints = xpoints * xpoints plt.plot(xpoints, ypoints, label = 'xsquared') plt.plot(xpoints, xpoints, label = 'straight', color = 'green') #plt.savefig('lecture1.png') randompoints = np.random.randint(1, 1000, 100) plt.scatter(...
import requests import sys, getopt from network import FixerAPI import database_api from database import ExchangeRateModel from datetime import datetime,date from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from database import ExchangeRateModel, Base engine = create_engine('sqlite:///curr...
# coding: utf-8 from me.tool import Data from numpy import * import operator from math import log import pickle # 多数投票决定该节点类型 def majorityCnt(classList): classCount = {} for vote in classList: if vote not in classCount.keys(): classCount[vote] = 0 classCount[vote] += 1 sortedCl...
from book import Book from recipe import Recipe cookbook = Book("cookbook") recipe1 = Recipe("cake", 2, 60, ["eggs","tet"], "dessert") # les self ne se mettent pas automatiquement ???? cookbook.add_recipe("plop") cookbook.get_recipes_by_types("dessert") cookbook.get_recipe_by_name("cake")
#!/usr/bin/env python3 __version__ = "0.3.0" __copyright__ = """ Copyright (c) 2009-2021 Bogdan Tataroiu """ __license__ = """ All source code available in this repository is covered by a GPLv2 license. """ import argparse import copy import logging import pathlib import shutil import subprocess import tempfile fr...
""" This stores Title Author ISBN and year of the book We can Add Select delete and update Entry. """ from tkinter import * from DbOperations import Database database=Database() class Window(object): def __init__(self,window): self.window=window self.window.wm_title("Abhij...
#!/usr/bin/env python from __future__ import division import argparse import random import pickle import queue """ =============================================================================== Please complete the following function. =============================================================================== "...
# coding=utf-8 # =============================================================== # Author: Óscar García Martínez # Email: racsodev93@gmail.com # # ABOUT COPYING OR USING PARTIAL INFORMATION: # This script was originally created by Oscar Garcia. Any # explicit usage of this script or its contents is granted # according...
from time import sleep from selenium import webdriver from selenium.webdriver import ActionChains from selenium.webdriver.common.by import By from selenium.webdriver.common.keys import Keys from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.support.wait import WebDriverWait def...
import wx import wx.lib.dragscroller import colorsys from math import cos, sin, radians #---------------------------------------------------------------------- BASE = 80.0 # sizes used in shapes drawn below BASE2 = BASE/2 BASE4 = BASE/4 USE_BUFFER = ('wxMSW' in wx.PlatformInfo) # use buffered drawing on Windows...
from flask import Flask, render_template, request from datetime import datetime from algo import algorithm, algo_dict, not_learnt app = Flask(__name__) @app.route('/') def index(): st = datetime.now() print("\n\n\n---------------------------------\nindex started at {}".format(st)) print("ren...
import sys from PyQt5.uic import loadUi from PyQt5 import QtWidgets, QtCore, QtGui from PyQt5.QtWidgets import QDialog, QApplication, QWidget from PyQt5.QtGui import QPixmap from PyQt5.QtWidgets import QApplication, QWidget, QDesktopWidget from camUtils import VideoThread from imutils.video import WebcamVideoStream fro...
# Generated by Django 3.0.3 on 2020-02-12 12:33 from decimal import Decimal from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Setting', fields=[ ...
#!/usr/bin/env python # -*- encoding: utf-8 -*- # Author: shoumuzyq@gmail.com # https://shoumu.github.io # Created on 2015/12/17 16:35 def gray_code(n): res = [0] for i in range(n): for j in range(len(res) - 1, -1, -1): res.append(1 << i | res[j]) return res print(gray_code(2...
#exception try: x=int(input("Enter number:")) y=int(input("Enter number:")) print(x/y) except ValueError: print("Invalid input(Enter integer only)") except ZeroDivisionError: print("Division by 0 not possible") except: print("Error!!!") else: print("Bye Bye") finally: print...
# !/usr/bin/python # coding=utf-8 # # @Author: LiXiaoYu # @Time: 2013-10-17 # @Info: Server Library. import os, sys from optparse import OptionParser from configparser import ConfigParser class ParseConfig(): #配置对象 __config = "" #配置文件 __config_file = "Config.ini" #初始化文件 def __init__(self...
"""Advent of Code Day 25 - Four Dimensional Adventure""" class FixedPoint: """Initialise fixed point as ranked, self-parented node.""" def __init__(self, num): self.num = num self.parent = self self.rank = 0 def find(point): """Return root of point (parent with parent as self).""...
from typing import Any import qrcode import platform def qr_terminal_str(data: Any, version: Any = None) -> str: """ :param data: qrcode data :param version:1-40 or None :return: """ if platform.system() == "Windows": white_block = '▇' black_block = ' ' new_line = '\n...
import conn db = conn.cursor def get_vak(db): vak = [] db.execute("SELECT * from vak") result = db.fetchall() resp = result return resp def add_vak(db,naam): sql = "INSERT INTO vak(vak_naam) value('" + naam + "')" db.execute(sql) conn.db.commit() def latest_vak(db): ...
# 导入相关数据包 import numpy as np import pandas as pd import seaborn as sns import matplotlib.pyplot as plt %matplotlib inline from scipy import stats from scipy.stats import norm root_path = '/opt/data/kaggle/getting-started/house-prices' train = pd.read_csv('%s/%s' % (root_path, 'train.csv')) test = pd.read_csv('%s/%s'...
from django.contrib import admin from django.urls import path, include from user.views import initial_view urlpatterns = [ path('admin/', admin.site.urls), path('manager/', include('manager.urls')), path('chef/', include('chef.urls')), path('runner/', include('runner.urls')), path('', initial_view)...
import datetime import mock import datetime from unittest import TestCase from flask_oauthlib.client import OAuthException from .. import linkedin from ..models import User, db, UserLinkedinInfo from .test_models import DbTestCase from .test_views import ViewTestCase FAKE_AUTHORIZED_RESPONSE = { 'access_token': '...
# -*- coding: utf-8 -*- # # 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 #...
from abc import ABC, abstractmethod class ObservableEngine(Engine): """Наблюдаемый класс""" def subscribe(self, subscriber): pass def unsbuscribe(self, subscriber): pass def notify(self, message): pass class AbstractObserver(ABC): @abstractmethod def update(self): ...
#!/usr/bin/python from funcs import Func,Plot import scipy.optimize import sys xmin= [-1.,-1.] xmax= [2.,3.] fkind= int(sys.argv[1]) if len(sys.argv)>1 else 1 f= lambda x:Func(x,fkind) # Minimize the function f res= scipy.optimize.minimize(f,[0.0,0.0]) print res print 'Result=',res.x Plot(xmin,xmax,f,x_points=[res...
#! /usr/bin/env python import sys from twisted.internet import reactor from example_secrets import get_page_title, main def print_page_title(url): print "fetching", url d = get_page_title(url) def got_info(title): print "title:", title reactor.stop() def fail_info(f): print "f...
from flask import Flask, request, jsonify from daos.book_dao_postgres import BookDaoPostgres from entities.book import Book from exceptions.book_unavailable_error import BookUnavailableError from exceptions.not_found_exception import ResourceNotFoundError from services.book_service_impl import BookServiceImpl import lo...
# -*- coding: utf-8 -*- from dash import Dash, dcc, html, dash_table, Input, Output, State import dash_cytoscape as cyto import dash_bootstrap_components as dbc import pandas as pd app = Dash(__name__, external_stylesheets=[dbc.themes.BOOTSTRAP],title = "HuBNet") server = app.server df = pd.read_csv("data/network_all...
# Network protocol constants TYPE = "type" TYPE_JAG = "jag" TYPE_VIC = "vic" TYPE_SOLENOID = "sol" TYPE_DIGITALOUT = "do" ARGS = "args" NUM = "num" TYPE_SENSOR = "s" SENSOR_TYPE = "st" SENSOR_DIGITAL_IN = "d" SENSOR_ANALOG_IN = "a"
import os def rename_files(): save_path = "C:/Users/HODOR/Desktop/rename_files_new" file_list = os.listdir(save_path) print(file_list) os.chdir(save_path) for file_name in file_list: print("Renaming file: "+file_name+" in Directory: "+save_path) os.rename(file_name,file_name.translate(None,"1234567890")) r...
import sys def minCost(i, j, n, m): if i == n-1 and j == m-1: return cost[i][j] if i >= n or j >= m: return sys.maxsize return cost[i][j] + min(minCost(i, j+1, n, m), minCost(i+1, j, n, m), minCost(i+1, j+1, n, m)) cost = [[1, 5, 11], [8, 13, 12], [2, 3, 7], [15, 16, 18]] ans = minCost(0...
from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.htmdata, name='htmdata'), ]
#!/usr/bin/env python # encoding: utf-8 import redis import json import tushare as ts import pandas as pd class DataHolder (): def __init__(self, stocks=[]): self.stocks = stocks if len(self.stocks) == 0: df = ts.get_stock_basics() df.to_json() def get_now_trans(self)...
def file_to_list(filename='ex_4.text'): list_file = [] with open(filename, 'r', encoding='utf-8') as file: for line in file: list_file.append(line.rstrip().split()) return list_file, filename # вот с этой функцией косяк. Если передавать напрямую возвращаемый первой функцией кортеж # то...
from threading import Timer import telegramfunctions as t import time from datetime import datetime import answerfinder as a import sensibledata as s import os import traceback active = True os.environ['TZ'] = 'Europe/Rome' time.tzset() def toggleBot(): global active active^=True def manageBot(input,chatid)...
#!/usr/bin/python # vim: set expandtab ts=4 import Tensor from sympy import pi,sin,cos,trigsimp,symbols,Abs,simplify import numpy as np class Spherical(Tensor.Coords): def __init__(self): x,y,z=symbols("x,y,z") X=x,y,z # spherical part # Unfortunately there is a lot of confusion a...
from pyfsm.machine import FSM, State, as_state from pyfsm.exceprions import UnreleasedTransition
import os from conans import ConanFile, tools required_conan_version = ">=1.43.0" class FastDoubleParserConan(ConanFile): name = "fast_double_parser" description = "Fast function to parse strings into double (binary64) floating-point values, enforces the RFC 7159 (JSON standard) grammar: 4x faster than strto...
import os import sys import re import logging import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns import japanize_matplotlib import category_encoders as ce from sklearn.model_selection import KFold, StratifiedKFold, GroupKFold from sklearn.metrics import mean_squared_error imp...
class CreateVehicleDto: id: int name: str registration_number: int capacity: int status: str class EditVehicleDto: id: int name: str capacity: int status: str class ListVehiclesDto: id: int name: str capacity: int status: str class GetVehicleDto: id: int ...
def test_yield(): print("----1----") yield 1 print("----2----") yield 2 print("----3----") yield 3 print("----4----") def fibona_create(max_num): print("-----first----") a, b = 0, 1 cursor = 0 while cursor < max_num: print("-----second----") #print(a) ...
"""empty message Revision ID: 5c1a09488932 Revises: 6dbb8fb1c3ab Create Date: 2018-10-01 22:10:34.569220 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '5c1a09488932' down_revision = '6dbb8fb1c3ab' branch_labels = None depends_on = None def upgrade(): # ...
#!/usr/bin/env python3 ''' Determines the tile proportions as a percentage for a given board. ''' import sys,os,re def main(args): if len(args) < 2: print("Usage: %s board boards..." % args[0]) return for fn in args[1:]: with open(fn) as fp: #Skip first 8 lines ...
#!/usr/bin/env python ''' Lists ''' from random import * # One dimensional list list1 = [] for i in range(5): var = randint(1, 100) list1.append(var) list1.sort() print('List-1: ' + str(list1)) # Two dimensional list n = 5 list2 = [[] for x in range(n)] for i in range(5): var = randint(1, 100) ...
# Predicting Heavy and Extreme Losses in Real-Time for Portfolio Holders # (c) 2015 QuantAtRisk.com, by Pawel Lachowicz # # heavy2.py import pandas_datareader.data as web import matplotlib.pyplot as plt import numpy as np from pyvar import cpr # ---1. Data Processing # fetch and download daily adjusted-close price s...
#!/usr/bin/env python3 print("Type integers, each followed by Enter; or just Enter to finish") total=0 count=0 while True: line=input("integer: ") if line: try: number=int(line) except ValueError as err: print(err) continue total+=number cou...
################### # CONFIG GLOBAL # ################### class ConfigGlobal: # Comprimento das barras de título barraComprimento = 70 def checaProjeto(): return 'checa' + str(barraComprimento) def __init__ (self): return None # ------------------------------ # Fim de 'ConfigGlobal'
# This file is kept only for backwards compatibility. Edit the one in ../mapgen class Lookup: def __init__(self, id='', table=None, display=None, comment='', instruction=None, rules=None): if rules is None: from filters import MSAnd rules = MSAnd() if instru...