text
stringlengths
8
6.05M
from random import randint, sample def number_generator(): return sorted(sample(xrange(1, 50), 6)) + [randint(0, 9)] def check_for_winning_category(your_numbers, winning_numbers): superzahl_match = your_numbers.pop() == winning_numbers.pop() matches = len(set(your_numbers).intersection(winning_numbers))...
import pandas as pd import csv ''' The initial conditions of the application needs a pre-defined empty csv file named "Student_Data.csv" with column names [name,age,branch,year,semester,prev_sem_score] ''' def getStudentData(): student_data = pd.read_csv("Student_Data.csv",index_col = False) if(len(student_...
from flask_sqlalchemy import SQLAlchemy from sqlalchemy import cast,Date, and_,or_ import config, bcrypt,subprocess,requests,re,logging from datetime import date, datetime,timedelta from database import match, User from flask import Flask, render_template, request, redirect from flask_login import LoginManager, login_u...
import requests from api.wework import WeWork class DepartmentManege(WeWork): #部门管理 secret = "ATvrnjJTv6Qu3zqUSDLXUJzmsPSBT_lHHd8pW68SVUs" #创建部门 def create(self,name,parentid,**kwargs): data = {"name":name,"parentid":parentid} data.update(kwargs) url = "https://qyapi.weixin.qq....
#M, D = map(int, input().split()) line = input().split() M = int(line[1]) D = int(line[0]) mp = [ "Thursday", "Friday", "Saturday", "Sunday", "Moday", "Tuesday", "Wednesday" ] count = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] sum = D-1 for i in range(M-1): sum += count[i] print...
import pandas as pd from bs4 import BeautifulSoup as soup from urllib.request import urlopen as uReq testurl="file:///C:/Users/vamsi/Desktop/BidAlert.htm"#url to Scrape uClient=uReq(testurl) page_html=uClient.read() uClient.close() page_soup=soup(page_html,"html.parser") #Columns to be Parsed BidAlertNos...
import matplotlib.pyplot as plt import pandas as pd df= pd.read_csv('E:\csvdhf5xlsxurlallfiles\percent-bachelors-degrees-women-usa.csv') print(df.shape) year=df['Year'] computer_science=df['Computer Science'] physical_science=df['Physical Sciences'] plt.plot(year, computer_science, color='red') plt.plot(year,...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Nov 8 13:16:19 2019 Parameter scans @author: fabio """ import numpy as np #import pandas as pd #import matplotlib.pyplot as plt #from smaller_model_function_AtoU import simple_small as ss from AtoU_model import simple import multiprocessing import time...
# Program to connect to ActiveMQ broker and read messages from the FuSE.ModelOutput topic and then publish messages # to MCITOPIC to be consumed by the phone. import paho.mqtt.client as mqtt import paho.mqtt.publish as publish import json import time broker = "localhost" # The mqtt broker location (can be changed to...
import mine import os import mysvg from manim import * def rate_dump(): print (rate_functions.__all__) for rate_function in rate_functions.__all__: call = f"{rate_function}(.5)" bar = eval(call) if not callable(bar): mysvg.ink_text_animation("Cross-smooth", "abcde", iteratio...
# encoding=UTF-8 # Клонирует или обновляет репозитории from dotenv import load_dotenv, find_dotenv from pathlib import Path import json import os import os.path import pymysql import traceback import time import sys import re import subprocess import io from google.cloud import speech from google.cloud.speech import en...
import cv2 as cv import os, os.path import numpy as np def read_an_image_series(series='birds'): """ Read a series of images :param series: :return: """ # general path that contain all images of a series main_path = 'C:\\Users\\Home\\Dropbox\\codes\\CV\\96131125_HW06\\JPEGS_min...
def hashify(string): result = {} string = string + string[0] for a in xrange(len(string) - 1): k, v = string[a:a + 2] try: result[k].append(v) # dictionary value is a list except AttributeError: result[k] = [result[k], v] # dictionary value is NOT a l...
from django.contrib import admin from .models import WalletPlatform, Wallet class WalletInLine(admin.TabularInline): """ Inline admin for wallet relation """ model = Wallet class WalletPlatformAdmin(admin.ModelAdmin): list_display = ('name', ) inlines = [ WalletInLine ] admin....
#!/usr/bin/env python import sdm import sys, random from time import time from sdm import Bitstring, Hardlocation def test_uniform_distribution(qty=10000): n = sdm.get_dimension() v = [0]*n for i in xrange(qty): a = Bitstring() for j in range(n): v[j] += a.bitsign(j) import...
from .Basic import fac def binomial(n, k): if k > n: return 0 if k < 0: return 0 return float(fac(n)) / float(fac(k) * fac(n - k)) def perm(n, k): k = float(k) n = float(n) if k > n: return 0 if k < 0: raise ValueError("k must be non-negative") return ...
jpy = 100 usd = jpy * 0.0094 eur = jpy * 0.0084 print(f"JPY={jpy}") print(f"小数点以下0桁:{jpy:.0f}") print(f"小数点以下1桁:{jpy:.1f}") print(f"小数点以下2桁:{jpy:.2f}") print() print(f"USD={usd}") print(f"小数点以下0桁:{usd:.0f}") print(f"小数点以下1桁:{usd:.1f}") print(f"小数点以下2桁:{usd:.2f}") print() print(f"EUR={eur}") print(f"小数点以下0桁:{eur:.0f}")...
""" Usage: call with <filename> <typename> """ import sys import clang.cindex def find_typerefs(node, typename): """ Find all references to the type named 'typename' """ if node.kind.is_reference(): ref_node = node.get_definition() if ref_node: if ref_node.spelling == typename:...
import re from api.models import * from api.serializers import * from django.contrib.auth.models import User from django.shortcuts import render from rest_framework import viewsets from rest_framework.views import APIView from rest_framework.authentication import SessionAuthentication, BasicAuthentication from ...
#!/usr/bin/env python import time,datetime import sys curDate= datetime.datetime(*(time.localtime(time.time()))[0:6]) for line in sys.stdin: red="" print line line= line.strip() AthleteID, FirstName, LastName, DOB, Gender, Country= line.split('\t') if DOB!="": date1= time.strpt...
from django import forms from student.models import Student class FeeForm(forms.Form): roll_no = forms.IntegerField()
import numpy as np def mutation_tags(tags, mutpb): """Mutation that alters each tag with 0.1 probability.""" # Number of guides n_guides = len(tags) new_tags = [] for i in range(n_guides): rnd = np.random.rand(1)[0] if rnd <= mutpb: new_tags.append(1-tags[i]) ...
# coding: utf-8 """ Various import statements """ import os from material.data_types.types_tryout import globals_d from material.data_types.main import main as dt_main from material.functions import main as fn_main_aa
import numpy as np from numpy import linalg as la import math import os import sys trainlabel = [] testlabel = [] icurr = 0 icurrTest = 0 #arrTest = np.zeros((xaxis,yaxis,zmaxtesting)) #defines dimension of 3d array abnormalTraining = 72 abnormalTesting = 48 normalTraining = 500 normalTesting = 336 i = 572 #No of...
# Generated by Django 2.2.4 on 2019-10-08 12:34 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('webapp', '0022_notice_images'), ] operations = [ migrations.RenameField( model_name='notice', old_name='files', ...
import logging logging.root.setLevel(logging.NOTSET) def get_custom_console_handler(): c_handler = logging.StreamHandler() c_handler.setLevel(logging.INFO) c_format = logging.Formatter('%(name)s - %(levelname)s: \n%(message)s\n--------------------') c_handler.setFormatter(c_format) return c_handl...
#作图用 #按照GO,将gene ID计数。并加上class 列 input_file = open("gene_swiss_GO.id") output_file = open("go_gene_sum.count","w") go_gene_dict = {} for line in input_file: text_list = (line.strip()).split("\t") gene_id = text_list[0] if len(text_list) != 2: go_all = text_list[2] go_list = go_all.split(";"...
# -*- coding: utf-8 -*- # Generated by Django 1.9.4 on 2016-03-21 00:04 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('choosing', '0001_initial'), ] operations = [ migrations.AlterField( ...
from bs4 import BeautifulSoup import CustomWebGen as cwg import logging import glob import yaml import os logging.basicConfig( level=logging.NOTSET, format="%(asctime)s:%(levelname)s:%(name)s:%(message)s", handlers=[logging.FileHandler("debug.log"), logging.StreamHandler()], ) root_path="." yaml_files = g...
# Import the random package to randomly generate cross-over points import random # Import the superclass (also called base class), which is an abstract class, # to implement the subclass BlendCrossoverOperator import GeneticOperator # Import the Individual package import Individual as IND # The subclass that inherit...
test_case = int(input()) for _ in range(test_case): x = int(input()) print((x + 7 - 1)//7)
#!/usr/bin/env python3.7 import os import sys import subprocess import re acceptinput = "Y" def environment_variables(): print("HOME: " + os.environ.get("HOME", "")) print("PATH: " + os.environ.get("PATH", "")) print("UNASSIGNED: " + os.environ.get("UNASSIGNED", "")) print(sys.argv) ## Prints the pro...
#!/bin/python import os import sys if int(sys.argv[1]) == 0x1a7: arg = "/bin/sh" gid = os.getegid() uid = os.geteuid() os.setresgid(gid, gid, gid) os.setresuid(uid, uid, uid) os.execv("/bin/sh", [arg]) else: print("No !")
# Exercício 9.2 - Livro import sys args = sys.argv if len(args) != 4: print(f'Dica: {args[0]} arquivo início fim') else: inicio = args[2] fim = args[3] nome = args[1] file = open(nome, 'r') for linha, dado in enumerate(file.readlines()): if (linha + 1) >= int(inicio) and (linha + 1) <= ...
class ListUtil: def __init__(self, the_list): self.the_list = the_list def flatten(self): """ Flatten an arbitraily nested list """ return self.__flatten(self.the_list) def __flatten(self, the_list, buf=None): if buf is None: buf = list() for item in ...
import math from repartition_experiments.algorithms.utils import Volume, get_file_manager, get_blocks_shape from repartition_experiments.file_formats.hdf5 import HDF5_manager from repartition_experiments.algorithms.utils import get_opened_files def get_entity_sizes(cs, bytes_per_voxel, partition): bs = cs[0] * cs...
#!/usr/bin/env python import numpy as np import csv from model import NB_Classifier import time # import the required packages here def run(Xtrain_file, Ytrain_file, test_data_file=None, pred_file=None): '''The function to run your ML algorithm on given datasets, generate the predictions and save them into the pro...
from random import randint class Hospital(object): def __init__(self, name, capacity): self.patients = [] self.name = name self.capacity = capacity def admit(self, patient): if len(self.patients) >= self.capacity: print "The hospital is full." else: self.pat...
# GIF Creator A program that puts together multiple images (PNGs, JPGs, TIFFs) to make a smooth GIF that can be exported # Optional: Make the program convert small video files to GIFs as well. # import the library from appJar import gui from tkinter import * from PIL import Image, ImageTk import imageio # ...
import json import os import sys import time from http import HTTPStatus from os import path from typing import List import requests import yaml from flask import Flask, Response, abort from flask import request import re from logging.config import dictConfig dictConfig({ 'version': 1, 'formatters': {'defau...
class Estado(): def __init__(self): print ("estado atual: " + str(self)) def __str__(self): return self.__class__.__name__ # estado 1 class link_down(Estado): def on_event(self, event): if event == 'interface_ok': return send_start() print ("estado atual: " +...
# Output handler for solver statistics import numpy as np from ..DREAMException import DREAMException from ..DataObject import DataObject import DREAM.Settings.Solver class Solver: def __init__(self, solverdata=None, output=None): """ Constructor. """ self.solverdata = None...
from pydantic import BaseModel class UserModel(BaseModel): nanoid: str name: str username: str password: str class PostModel(BaseModel): nanoid: str post: str user: str replyTo: str isReply: bool
from django.shortcuts import render from .models import Film, Review from django.views.generic import ListView, DetailView, CreateView from django.contrib.auth.views import LoginView, LogoutView from django.views.generic import TemplateView from .forms import RegistrationForm, LoginForm from django.contrib.auth.models ...
# transcendental.py # Adrian Del Maestro # 09.13.2012 # A graphical solution of a transcendental equation import matplotlib.pyplot as plt import numpy as np plt.style.use('notebook'); x_sol = [] # ---------------------------------------------------------------------------- def trans(x,a): ''' A transcendental...
import os from definitions import NOMENCLATURES_DIR from definitions import TRAINING_DIR from definitions import TFIDF_NATIONALITIES_DIR import definitions import wsdm.ts.helpers.persons.persons as p_lib def init_dictionary(): nationalities = {} with open(os.path.join(NOMENCLATURES_DIR, 'nationalities.txt'), e...
class GameWorker(webapp2.RequestHandler): def post(self): players={}
# 배열 array의 i번째 숫자부터 j번째 숫자까지 자르고 정렬했을 때, k번째에 있는 수를 구하려 합니다. # 예를 들어 array가 [1, 5, 2, 6, 3, 7, 4], i = 2, j = 5, k = 3이라면 # array의 2번째부터 5번째까지 자르면 [5, 2, 6, 3]입니다. # 1에서 나온 배열을 정렬하면 [2, 3, 5, 6]입니다. # 2에서 나온 배열의 3번째 숫자는 5입니다. # 배열 array, [i, j, k]를 원소로 가진 2차원 배열 commands가 매개변수로 주어질 때, commands의 모든 원소에 대해 앞서 설명한 연산을 ...
from scrapUtil import get_pages, get_tables class Train(): def __init__(self, id): self.id = id
class Rectangulo: def __init__(self, base, altura): self.base = base self.altura = altura def area(self): return print("El area del rectangulo es:", self.base*self.altura) baseRectangulo = int(input("Ingrese la base del rectangulo: ")) alturaRectangulo = int(input("Ingrese la altur...
#Accept two numbers from user and print their GCD and LCM def GCD_LCM(no1,no2): if no1<=0 or no2<=0: return lcm=1 i=2 temp1=no1 temp2=no2 while(no1!=1 or no2!=1): if no1%i==0 or no2%i==0: lcm*=i else: i+=1 continue if no1%i==0:...
class HumanObject: def __init__(self, weight, cost): self.weight = weight self.cost = cost def __str__(self): result = f"HumanObject for backpack with weight of: {self.weight} and cost of: {self.cost}" return result if __name__ == '__main__': size = 20...
# coding:utf-8 def handle(event, context): print("done")
# from multiprocessing import set_start_method # set_start_method("spawn") import tarfile import os import sys import pickle #import tensorflow as tf from datetime import datetime from multiprocessing import Pool from multiprocessing import Process import multiprocessing import getopt from itertools import repeat impor...
import tensorflow as tf from nolearn.lasagne import BatchIterator class Trainer: def __init__(self, graph_model, epochs, batch_size, logdir, save_path, val_epoch=100, save_epoch=200): self.graph_model = graph_model self.epochs = epochs self.val_epoch = val_epoch self.save_epoch = s...
import socket IP = '10.2.2.243' # 修改为别人的 IP PORT port = 29529 address = (IP, port) cli = socket.socket(socket.AF_INET, socket.SOCK_STREAM) cli.connect(address) while True: msg=input('type your msg') msg='C罗:{}'.format(msg) cli.send(msg.encode('utf8')) remsg= cli.recv(1024) print(remsg.decode('utf8'...
import os import re import shutil from PIL import Image from PIL import ImageOps from tqdm import tqdm import time def ResizeToSquare(path): desired_size = 1024 im = Image.open(path) old_size = im.size # old_size[0] is in (width, height) format ratio = float(desired_size) / max(old_s...
import os from obfuscator_source.python_obfuscator import Obfuscator from shutil import copy import ntpath class File: def __init__(self, file_path, new_file_path): self.file_path = file_path self.extension = self.__extract_file_extension() self.file_name = self.__extract_file_name() ...
# -*- coding: utf-8 -*- """ Created on Thu Jan 16 10:04:01 2020 @author: KelvinOX25 """ import pyvisa import time import logging import numpy as np import struct from qcodes import VisaInstrument, validators as vals from qcodes.instrument_drivers.Keysight.Keysight_B2962A import B2962A class B2962A_Isrc(B2962A): ...
from sys import argv if len(argv) != 3: print("usage: ./converter.py <in> <out>") exit(-1) data = [] with open(argv[1], "r") as f: for l in f: data.append(int(l, 16)) with open(argv[2], "w") as f: for x in data[2:]: f.write("%08x\n"%x) f.write("00c00093\n") f.write("00008067\n")
import numpy as numpy import cv2 import matplotlib.pyplot as plt from matplotlib.ticker import NullFormatter from scipy.special import erfc import sys import logging logging.basicConfig(stream=sys.stderr, level=logging.DEBUG) #size of constellation (N symbols per frame; N frames per constellation) N=64 im...
import unittest from katas.kyu_7.radio_dj_helper_function import longest_possible class LongestPossibleTestCase(unittest.TestCase): def test_equals(self): self.assertEqual(longest_possible(215), 'For Reasons Unknown') def test_equals_2(self): self.assertEqual(longest_possible(270), 'YYZ') ...
#!/usr/bin/env python3 import argparse import sys import os our_version = 10 def do_version(): return '{}.0.0'.format(our_version) def do_components(): return 'all all-targets analysis asmparser asmprinter binaryformat bitreader bitwriter codegen core coroutines coverage debuginfocodeview debuginfodwarf debuginfo...
import unittest from katas.kyu_5.first_non_repeating_letter import first_non_repeating_letter class FirstNonRepeatingLetterTestCase(unittest.TestCase): def test_equal_1(self): self.assertEqual(first_non_repeating_letter('a'), 'a') def test_equal_2(self): self.assertEqual(first_non_repeating_...
# Day 2: I Was Told There Would Be No Math # <ryc> 2021 import re def inputdata(): with open('day_02_2015.input') as stream: data = stream.readlines() data = [ [ int(number) for number in re.findall('\d+', line) ] for line in data ] return data def get_wrapping_paper(data): count = 0 ...
import sys import time def lazy_evaluation(n): print("1 sec") time.sleep(1) return n """Iterator 와 Generator 의 차이""" n_list = [lazy_evaluation(n) for n in range(1, 6)] for i in n_list: print(i) n_generator =(lazy_evaluation(n) for n in range(1,6)) for j in n_generator: print(j) x_ran...
from file.content import ContentManager from parser import ServerHttpRequest, ServerHttpResponse from conf.basic import SUPRESS_EXCEPTION def process_request((client_socket, addr), server): try: req_msg = read_socket(client_socket) http_req = ServerHttpRequest(req_msg) proto_version = htt...
operation=input("Dime la operación (multiplicacion, suma, resta, division):") first_number=float(input("Primer número: ")) second_number=float(input("segundo número: ")) if operation == "multiplicacion": result=first_number*second_number print("el resultado es: {}".format(result)) elif operation == "suma": ...
# -*- coding=utf-8 -*- ''' Created on 20171031 @author: leochechen @summary: ctf全局变量 ''' import weakref import threading from functools import wraps # 线程级全局变量,该变量会存储CTF Server和Client连接中 CTFWorkerLocal = threading.local() # CTF全局字典 CTFGlobal = {} # CTF全局互斥锁 CTFLock = threading.Lock() # 获取当前线程的local变量的弱引用 def get_we...
def main(): year = 1900 month = 1 months_30 = [4,6,9,11] day = 1 i = 1 sunday_counter = 0 while True: if month in months_30: limit = 30 elif month == 2: limit = 28 if year%4==0 and year % 100 !=0: limit = 29 if year%400 == 0: limit = 29 else: limit = 31 if i > limit: i = 1 mo...
from pyscrap3.spiders import Spider from pyscrap3.spiders import Item from pyscrap3.spiders import ItemList
import time import pandas as pd import numpy as np from IPython.display import display CITY_DATA = { 'chicago': 'chicago.csv', 'new york city': 'new_york_city.csv', 'washington': 'washington.csv' } def get_filters(): """ Asks user to specify a city, month, and day to analyze. ...
import subprocess subprocess.call(['./first.sh'])
import uuid from datetime import datetime from django.db import models from django.template.defaultfilters import slugify from django.contrib.sites.shortcuts import get_current_site from django.utils.functional import SimpleLazyObject from django.conf import settings from django.core.exceptions import ObjectDoesNotExi...
aluno = dict() aluno['nome'] = str(input('Nome: ')) aluno['media'] = float(input('Media: ')) if aluno['media'] >= 7: aluno['situaçao'] = "aprovado" else: aluno['situaçao'] = "Reprovado" for x, y in aluno.items(): print(f'-{x} é igual a {y}') print(aluno.keys()) print(aluno.values())
def main(): print("This programs generates usernames from a file of names") infilename = input("Which file has all the names: ") outfilename = input("Place usernames in this file: ") infile = open(infilename, "r") outfile = open(outfilename, "w") for i in infile: uname = i.upper() ...
import os import json import requests from requests.auth import HTTPBasicAuth DEFAULT_API_URL = 'http://localhost:8080' class HttpClient(object): def __init__(self, username="", password="", api_url=DEFAULT_API_URL, create_user=True): self.api_url = api_url self.username = username self...
temp.py import random import numpy as np import cv2 import matplotlib.pyplot as plt img = cv2.imread('test2.png',0) delete_freq=5          i=0 def feature_sparsity(img): akaze = cv2.AKAZE_create(threshold=0.0...
###################################################################### ############### Naive Bayes Classifier ############################### ###################################################################### import math import numpy as np from sklearn import datasets from sklearn.decomposition import PCA # load...
# -*- coding: utf-8 -*- """ Created on Wed Oct 23 15:26:46 2019 @author: Valeria """ import iv_save_module as ivs import iv_utilities_module as ivu import matplotlib.pyplot as plt #%% Parameters this_filename = 'C:\\Users\\Valeria\\OneDrive\\Labo 6 y 7\\Análisis\\Potencia_M_20191018_10\\Resultados.txt' #%% Load da...
''' Convert CSV to COCO (test) ''' import os import json import argparse import numpy as np import pandas as pd import glob import os import shutil from IPython import embed from sklearn.model_selection import train_test_split classname_to_id = {'Aortic enlargement':0, 'Atelectasis':1, 'Calcification':2, 'Cardiomegal...
import sys # methods def init_Snap(archived_pnt, value, trade_date, time,POSITIVE_DEV,NEGATIVE_DEV): prev_val = float(archived_pnt['value']) prev_time = int(archived_pnt['time_value']) time = int(time) value = float(value) Smax = (value+POSITIVE_DEV*value-prev_val)/(time-prev_time) Smin = (valu...
# Copyright (c) 2017-2023 Digital Asset (Switzerland) GmbH and/or its affiliates. All rights reserved. # SPDX-License-Identifier: Apache-2.0 # fmt: off # isort: skip_file from .object_meta_pb2 import ObjectMeta from .config_management_service_pb2 import GetTimeModelRequest, GetTimeModelResponse, SetTimeModelRequest, S...
#!/usr/bin/python import sys import csv from datetime import datetime ## Convert a string to datetime def toDatetime(date): return datetime.strptime(date[:-3], '%Y-%m-%d %H:%M:%S.%f') reader = csv.reader(sys.stdin, delimiter="\t") for entry in reader: author_id = entry[3] added_at = entry[8] ## If we have ...
class OutOfRange(Exception): """Raised when resulting *progress* is more than *total* value.""" def __init__(self): super(OutOfRange, self).__init__( "resulting progress is out of range" ) class DoesNotExist(Exception): """Raised when requested Celery task does not exist. ...
#! /usr/bin/env python3 import argparse, sys, os, time, urllib, urllib.request, urllib.parse, json from pyclustering.cluster import cluster_visualizer from pyclustering.cluster.optics import optics from pyclustering.utils import read_sample # return list of path files from argument string, space delimitted def fileli...
import numpy as np from dataserver import get_file from demo_helpers import generate_rank1_data, generate_rank2_data f = get_file('accumulating_test.h5').get_numbered_child() f.create_dataset('line', rank=1) f.create_dataset('img', rank=2) for x, trace in zip(generate_rank1_data(), generate_rank2_data()): #time...
import os from dropbox.client import DropboxClient from dropbox.datastore import DatastoreManager, DatastoreConflictError from bottle import route, request, static_file, run, template, TEMPLATE_PATH from config import DROPBOX_TOKEN, IMAGES_PATH, MAX_RETRIES from Logger import _logger import datetime @route('/') def ro...
# -*- coding: utf-8 -*- class UnionFind: def __init__(self, n): self.ids = list(range(n)) self.sizes = [1] * n def root(self, i): while i != self.ids[i]: self.ids[i] = self.ids[self.ids[i]] i = self.ids[i] return i def union(self, p, q): i,...
import os from telethon.sessions import StringSession from telethon.sync import TelegramClient from dotenv import load_dotenv load_dotenv() api_id1 = int(os.getenv("api_id1")) api_hash1 = str(os.getenv("api_hash1")) with TelegramClient(StringSession(), api_id1, api_hash1) as client: print("Скопируйте код 1 сесси...
import sys from PyQt5.QtWidgets import ( QDialog, QDialogButtonBox, QLabel, QVBoxLayout, QMessageBox ) class CustomDialog(QDialog): icon_dict = { 'info' : QMessageBox.Information, 'question' : QMessageBox.Question, 'warning' : QMessageBox.Warning, 'critical' : QM...
# Generated by Django 3.2.12 on 2022-03-20 12:40 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('osmcal', '0029_alter_event_description'), ] operations = [ # This deletes already existing duplicates in the DB: migrations.RunSQL(""" ...
from Tested_Method.MethodToTest import working_function_3 from unittest.mock import patch import pytest TESTED_MODULE = 'Tested_Method.MethodToTest' # mocking just the public function # if you have functions such as: connection to DB ecc that executes in more tests we can create fixture # pre-processing for test @patc...
# Example directly sending a text string: import requests r = requests.post( "https://api.deepai.org/api/summarization", data={ 'text': 'YOUR_TEXT_HERE', }, headers={'api-key': '79728e79-d56e-40bc-be98-ece560a7dd3c'} ) print(r.json())
from unittest import TestCase import os from graph_db.access import db from graph_db.engine.api import EngineAPI from graph_db.engine.error import GraphEngineError from graph_db.engine.types import DFS_CONFIG_PATH class ParserCase(TestCase): temp_dir = 'db/' queries = [ 'create graph: test_graph', ...
__author__ = 'Justin' import geojson import networkx as nx from geopy.distance import vincenty as latlondist # DESCRIPTION: # This script converts geojson road geometry files to a tractable networkx object (.gexf) # Geojson map data such as node positions, edge connections, edge types, max speeds, and edge names are ...
# Generated by Django 2.2.6 on 2019-10-19 11:01 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('checkout', '0006_shippingaddress_current_address'), ('carts', '0001_initial'), ] operations = [ mig...
# Copyright 2014 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). import sys import types import unittest import uuid from contextlib import contextmanager from dataclasses import dataclass from typing import Any from pkg_resources import ( Distribu...
import cv2 citra = cv2.imread('PVHotSpot.jpg') citra1 = cv2.imread('PVHotSpot.jpg', cv2.IMREAD_GRAYSCALE) if not citra is None: cv2.imshow('Gambar Seek Thermal.png', citra1) cv2.imshow('Gambar convert gray scale', citra) cv2.waitKey(0)
from mongoengine import * from login import User class Post(Document): """ A post is the last object in the big list of referenced fields. It works like this, one Board has many Categories one Category has many topics (threads) one Thread has many Posts one Post has one User """ au...