text
stringlengths
38
1.54M
from dataset import DataEntry, DataSet, Vocab, Action from nn.utils.io_utils import deserialize_from_file #-------------------------------------- # ADDED #-------------------------------------- #import dynet as dy #import random #import math #import sys def write_to_file(output_file, dataset, max_num): query_writer ...
#for statements 1 - 9 """Laços Aninhados""" for i in range (1,10): print("Tabuada do " + str(i)) for j in range(0,11): print(str(j) + "" + str(j*i))
import sys import numpy as npy import matplotlib.pyplot as plt import matplotlib.image as img m = img.imread(sys.argv[1]) w, h = m.shape[:2] new = npy.zeros([w, h, 3], dtype=int) mask = npy.zeros([w, h, 3], dtype=int) arr = npy.zeros([8, 3], dtype=int) wt = npy.zeros([8, 3], dtype=float) def gradient_r(x1, y1, xc, ...
import re; from mHTTP.mExceptions import cHTTPException, cTCPIPException, cSSLException; from oConsole import oConsole; from mColors import *; grFavIconLinkElement = re.compile( r'<link' r'(?:\s+\w+="[^"]+")*' r'\s+rel="(?:shortcut )icon"' r'(?:\s+\w+="[^"]+")*' r'\s+href="([^"]+)"' r'\s*\/?>', re.I );...
import paramiko import os paramiko.util.log_to_file('logfile.log') host = "101.102.103.104" port = 22 transport = paramiko.Transport((host, port)) password = "pass" username = "user" transport.connect(username = username, password = password) sftp = paramiko.SFTPClient.from_transport(transport) filepa...
def mapper(filename): map_result = [] with open(filename, 'r') as file: for line in file: line = line.replace(".", " ").replace(",", " ").lower() for word in line.split(): map_result.append((word, 1)) return map_result def shuffle_sort(map_result): shuff...
import atexit import sys import io class Solution: def find(self, a, parent): if parent[a] < 0: return a x = self.find(parent[a], parent) parent[a] = x return x def merge(self, a, b,parent): a = self.find(a, parent) b = self.find(b, paren...
from turtle import Turtle import random food_shape=("circle","turtle","arrow") class Food(Turtle): def __init__(self) -> None: super().__init__() self.shape("turtle") self.penup() self.shapesize(stretch_len=0.5,stretch_wid=0.5) self.color("blue") self.speed(...
#Scatter plotting import matplotlib.pyplot as plt x=[1,2,3,4,5,6,7,8] y=[5,3,4,2,5,4,2,1] plt.scatter(x,y,label="random values",color="red") #syntax: plt.scatter(x coordinate, y coordinate, label, colour) plt.title("Scatter Graph") #heading of the graph plt.legend() plt.xlabel("x axis") plt.ylabel("y axis") plt.show()
import matplotlib.image as mpimg import matplotlib.pyplot as plt import numpy as np import cv2 import glob import time from sklearn.svm import LinearSVC from sklearn.preprocessing import StandardScaler from skimage.feature import hog from sklearn.model_selection import train_test_split, GridSearchCV from sklearn import...
#!/usr/bin/env python # -*- coding: utf-8 -*- # # This script is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # It is distributed in t...
from generallibrary.iterables import extend_list_in_dict, split_list from generallibrary.functions import SigInfo, wrapper_transfer, Recycle from generallibrary.diagram import TreeDiagram from generallibrary.objinfo.children import _ObjInfoChildren from generallibrary.objinfo.type import _ObjInfoType from generallibr...
import re import pdb import nltk import pickle import random import numpy as np import unicodedata from tqdm import tqdm from collections import defaultdict from nltk.corpus import wordnet as wn def synset_from_sense_key(sense_key): ADJ, ADJ_SAT, ADV, NOUN, VERB = 'a', 's', 'r', 'n', 'v' sense_key_regex = re.c...
import os import sys sys.path.append('.') sys.path.append('/home/huangzeyu/tmp/yolov3') import torch from detectron2.data import samplers from utils.datasets import * from utils.utils import * from detectron2.utils.comm import get_world_size def build_yolo_detection_train_loader(cfg, mapper=None): hyp = { ...
""" Clinical Trials Policy class Raluca Cobzaru (c) 2018 Adapted from code by Donghun Lee (c) 2018 """ from collections import namedtuple import numpy as np from scipy.stats import binom import scipy import math import pandas as pd import copy from ClinicalTrialsModel import ClinicalTrialsModel import time def trunc...
import socket UDP_IP = "0.0.0.0" UDP_PORT = 9000 MESSAGE = "Hello, World!" # print "UDP target IP:", UDP_IP # print "UDP target port:", UDP_PORT # print "message:", MESSAGE sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # UDP while True: sock.sendto(bytes(MESSAGE, "utf=8"), (UDP_IP, UDP_PORT))
"""v0.1 Revision ID: 787738fb2362 Revises: f6778600730b Create Date: 2019-06-22 17:57:41.370758 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '787738fb2362' down_revision = 'f6778600730b' branch_labels = None depends_on = None def upgrade(): # ### comma...
class Solution: def __init__(self): self.result = [] def dfs(self, nums, index, path): if path not in self.result: self.result.append(path) for i in range(index, len(nums)): self.dfs(nums, i + 1, path + [nums[i]]) def solution(self, nums): self.dfs(...
# -*- coding: utf-8 -*- """ Created on Fri Oct 19 00:31:03 2018 @author: hongx """ import numpy as np import pandas as pd import seaborn as sns import matplotlib.pyplot as plt music = pd.read_csv("../data/lyrics_sentiment_no_lyrics.csv") #music.head() d11 = music["date"] music["right_date"] = pd.to_datetime(d11) musi...
__author__ = 'nahla.errakik' import pandas as pd def get_ind_file(filetype): """ Load and format the Ken French 30 Industry Portfolios files """ known_types = ["returns", "nfirms", "size"] if filetype not in known_types: raise ValueError(f"filetype must be one of:{','.join(known_types)}")...
""" This is the test script """ # flake8: noqa W191 import sys import pandas as pd sys.path.append("ibmcloudsql") import ibmcloudsql # noqa import test_credentials # noqa try: from exceptions import RateLimitedException except Exception: from .exceptions import RateLimitedException pd.set_option("display....
from rest_framework import serializers from laptops.models import Laptop, CPU class LaptopSerializer(serializers.ModelSerializer): cpu = serializers.StringRelatedField() manufacturer = serializers.StringRelatedField() gpu = serializers.StringRelatedField(many=True) class Meta: model = Laptop ...
# -*- coding: utf-8 -*- """ Created on Wed Mar 20 11:44:47 2019 @author: a-kojima """ import numpy as np import matplotlib.pyplot as pl import soundfile as sf from scipy import signal as sg from scipy.fftpack import fft import copy class PlotBeamPattern: def __init__(self, gammatone_path, sampli...
#operadores de asignacion x=3 x+=2 # x= x+2 print(x) x-=1 print(x) print("{}{}".format('Estoy Practicando ',7)) x*=5 print(x)
import argparse import json from imdb import IMDb from tqdm import tqdm def fetch_imdb_info(vocab_path, output_path): print('Reading vocab...') with open(vocab_path) as file: vocab = json.load(file) ia = IMDb() imdb_info = {} for id, entry in tqdm(vocab.items(), desc='Fetching IMDb info....
def sum_element_1(n): return 1 / (4*n + 1) def sum_element_2(n): return 1 / (4*n + 3) def sum_element(n): return sum_element_1(n) - sum_element_2(n) def approximation_of_pi(limit): estimate = 0 n = 0 while n <= limit: estimate += sum_element(n) n += 1 return estimate * 4 for i in [1, 3, 6, 9]: print(fo...
from gtts import gTTS # import os import playsound text = "LOL this is real funny" output = gTTS(text=text, lang='en', slow=False) output.save('output.mp3') # os.system("afplay output.mp3") # wait for the sound to finish playing? blocking = True playsound.playsound("output.mp3", block=blocking)
import cv2 import matplotlib.pyplot as plt import numpy as np import imutils import easyocr ## Read in Image, Greyscale/Blur img = cv2.imread("C:/Users/asus/Desktop/Python Project/License Plate Recog/IMG_9.jpg") gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # plt.imshow(cv2.cvtColor(gray, cv2.COLOR_BGR2RGB)...
# -*- coding: utf-8 -*- """Agent_Timing.ipynb """ from google.colab import drive drive.mount('/content/gdrive', force_remount=True) import sys sys.path.append('/content/gdrive/My Drive/EtaZero') # Commented out IPython magic to ensure Python compatibility. # %matplotlib inline import matplotlib.pyplot as plt import ...
# 03_jsonTest02.py # 첨부 파일 some.json을 이용하여 각 정보를 출력해보세요. import json filename = 'some.json' def get_Json_Data(): print('함수 호출됨') filename = 'some.json' myfile = open(filename, 'rt', encoding='utf-8') print(type(myfile)) myfile = myfile.read() print(type(myfile)) # loads(str) : 문자열 형식의...
# PIL modulunu goruntunun pikselini # cikarmak ve uzerinde degisiklik yapmak icin kullanacagiz from PIL import Image import speech_recognition as sr sr.__version__ r = sr.Recognizer() audiodata = sr.AudioFile("data/voicerecord.wav") with audiodata as source: audio = r.record(source) result = r.recognize_goog...
from BinarySearchTreeNode import Node class BTS: # Binary Search Tree def __init__(self): self.__Head = None def Insert(self, Value): if self.__Head is None: self.__Head = Node(Value) else: self.__insert(Value, self.__Head) def __insert(self, Value, root):...
import bottle from bottle import request, response import sqlalchemy as sa from bauble import app, API_ROOT from bauble.middleware import basic_auth, filter_param from bauble.model import SourceDetail column_names = [col.name for col in sa.inspect(SourceDetail).columns] def resolve_source(next): def _wrapped(*a...
import typing as tp from lib import input_utils def two_sum( stream: tp.Iterable[int], target: int, ) -> tp.Optional[tp.Tuple[int, int]]: cache = set() for e in stream: expected = target - e if expected in cache: return e, expected cache.add(e) retur...
from django.shortcuts import render from django.http import HttpResponse from AppTwo.models import Topic, Webpage, Access # Create your views here. def index(request): webpages_list = Access.objects.order_by('date') date_dict = {'access': webpages_list} # my_dict = {"insert_me": "Now I am from AppTwo/index....
from __future__ import annotations import requests from typing import Optional, Union from bs4 import BeautifulSoup from collections import Counter from helpers import NA from bs4.element import Tag import json from time import sleep from requests.exceptions import ConnectionError from urllib3.exceptions import MaxRetr...
#Written by Chang Wang #this code used KNN algorithm #it picked 9 column from the input file and dealed with these features #main aims to discuss the difference between using same algorithm but different features with other group members #the output is such as: #the best k = 13 #precision score = 0.7142857142857143 #r...
from PIL import Image from PIL import ImageFilter from PIL.ImageFilter import * import os def CreatePath(name): outPath = r"C:\Users\emili\Desktop\ClusterASD\Images\ImgFiltros/"+name+"Filtros/" os.makedirs(outPath, exist_ok=True) def ImageFilter(path): # path of the folder containing the raw images ...
from flask import render_template, url_for, flash, redirect, Blueprint from app import db, bcrypt from app.models import Teacher, Classes from app.teacher.forms import ChangeTeacherForm from flask_login import current_user, login_required teacher = Blueprint('teacher', __name__) @teacher.route('/teacher_profile') ...
#!/usr/bin/env python import RPi.GPIO as GPIO from mfrc522 import SimpleMFRC522 import time servoPIN = 17 GPIO.setmode(GPIO.BCM) GPIO.setup(servoPIN, GPIO.OUT) myServo = GPIO.PWM(servoPIN, 50) # GPIO 17 for PWM with $ myServo.start(2.5) # Initialization reader = SimpleMFRC522() try: while True: id, text = reader...
from database import db, IDPKMixin, DescriptionMixin, SystemMixin class Site(db.Model, IDPKMixin, DescriptionMixin, SystemMixin): """Site model""" __tablename__ = 'site' name = db.Column(db.Text) code = db.Column(db.Text, unique=True)
from twython import Twython import requests import zmq APP_KEY = '6LTEgHCBchKPIQdXb3IH6kJSI' APP_SECRET = 'waHGTlmTVKQmsm485tf5WPWpUShQkTecvdvwKOBB7DA8nQlnSB' twitter = Twython(APP_KEY, APP_SECRET) auth = twitter.get_authentication_tokens() OAUTH_TOKEN = auth['oauth_token'] OAUTH_TOKEN_SECRET = auth['oauth_token_se...
# -*- coding: utf-8 -*- import math import httplib import urllib import urllib2 import json import hashlib import hmac import time import copy import string import random import socket import sys from _CLASS import * from _ExmoAPI import * from _key import * import _file import g # global import ted...
COMPONENT_NAMES = [ # "compute_accessibility", "school_location", "workplace_location", "auto_ownership_simulate", "free_parking", "cdap_simulate", "mandatory_tour_frequency", "mandatory_tour_scheduling", "joint_tour_frequency", "joint_tour_composition", "joint_tour_participa...
from xstatic.main import XStatic # names below must be package names mod_names = [ 'asciinema_player', 'bootbox', 'bootstrap', 'font_awesome', 'jquery', 'jquery_ui', 'jquery_file_upload', 'pygments', ] pkg = __import__('xstatic.pkg', fromlist=mod_names) serve_files = {} for mod_name in...
from django.shortcuts import render,get_object_or_404,redirect, Http404, HttpResponseRedirect,HttpResponse from django.core.paginator import Paginator from django.views import generic, View from qa.models import Question,Answer,CustomUser,Session from django.views import generic from qa.forms import AnswerForm,AskForm,...
#-*- coding: utf-8 -*- """ Created on 2019/5/14 @Author: xhj """ import os import sys __all__ = ['utils', 'data_prepare', 'camera_calibration']
__author__ = 'rayatnia' import smtplib from email.mime.text import MIMEText from threading import Thread from django.core.mail import send_mail from django.conf import settings def async(f): def wrapper(*args, **kwargs): thr = Thread(target=f, args=args, kwargs=kwargs) thr.start() return wrapp...
""" The surface into which tetrominoes fall. https://tetris.wiki/Playfield """ import pygame from src.config import config as src_config from src.tetromino import Block class Playfield: """The surface into which tetrominoes fall""" config = src_config["playfield"] def __init__(self, display): ...
from common_colors import * import os, sys import pycoingecko import requests # to get image from the web import shutil # to save it locally # Argument is coingecko image output path coingecko_client = pycoingecko.CoinGeckoAPI() top_tokens = coingecko_client.get_coins_markets(vs_currency='USD', per_page=100) tokens =...
import string, random import networkx as nx import matplotlib.pyplot as plt from scipy.sparse import random as sparse_random from layout_grouped_graph import partition_layout # Random string generator def rand_string(size=6, chars=string.ascii_uppercase): return ''.join(random.choice(chars) for _ in range(size))...
# coding: utf-8 """ Digitick REST API The Digitick REST API is a set of methods giving access to catalog, user and cart management. OpenAPI spec version: v1.0 Contact: contact@digitick.com Generated by: https://github.com/swagger-api/swagger-codegen.git """ from pprint import pformat from six i...
import os import sys from pathlib import Path if len(sys.argv) != 2: print('You must pass the data directory as the first argument. E.g. "py createDataFolder.py C:/DATA"') exit() dir = sys.argv[1] Path(dir + "/CCAP/T0/Change9606").mkdir(parents=True, exist_ok=True) Path(dir + "/CCAP/T1").mkdir(parents=True, ...
import regex import lib.logger as logging from lib.functions import wait_until from lib.game import ui from lib.game.battle_bot import ManualBattleBot from lib.game.missions.missions import Missions logger = logging.get_logger(__name__) class WorldBossInvasion(Missions): """Class for working with World Boss Inv...
# Copyright 2012-2013 OpenStack, LLC. # # 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 ...
# 숫자를 1 ~ 31 까지 담는다 # 반복문을 사용해서 숫자 31이 될떄까지 # 컴퓨터 임의갯수숫자를 부르고 사용자가 임의갯수숫자를 입력한다. # 사용자가 임의갯수숫자를 입력하면 # 컴퓨터는 나머지의 숫자를 순서대로 임의갯수대로 나타낸다. # 여기서 숫자가 31이 나오지 않으면 다시 사용자가 임의갯수숫자 입력으로 돌아감 # 사용자가 컴퓨터 다음 숫자를 임의갯수대로 입력한다 # 컴퓨터는 사용자가 입력한 숫자의 다음 숫자를 임의갯수대로 입력한다 # 6행줄로 다시 돌아간다. # 컴퓨터가 30까지 입력하면 컴퓨터 승리! 사용자가 30을 입력하면 사용자 승리...
from rest_framework import generics, permissions from core.models import Pet from core.serializers import PetSerializer,PetCreateSerializer class PetList(generics.ListAPIView): queryset = Pet.objects.all() serializer_class = PetSerializer permission_classes = () class PetDestroy(generics.DestroyAPIView):...
#!/usr/bin/env python3 # install pip3 install requests from tickets import Ticket import os import time # This is the main code to the code challenge # Contains: class CodingChallenge(): def display_menu(self): # This is the main display menu # clears out the screen everytime method is called ...
# Adapted for numpy/ma/cdms2 by convertcdms.py # # Test Outline (Go) module # ############################################################################ # # # Module: testoutline module # # ...
# O(v+e) time | o(v) space class Node: def __init__(self, name): self.children = [] self.name = name self.visited = set() def addChild(self, name): self.children.append(Node(name)) return self def depthFirstSearch(self, array): stack = [] stack.appe...
from .device import SimulatedLakeshore372 from ..lewis_versions import LEWIS_LATEST framework_version = LEWIS_LATEST __all__ = ['SimulatedLakeshore372']
"""Annotators for numbering things.""" import random import re from binascii import hexlify from collections import defaultdict from sparv import Annotation, Output, Wildcard, annotator START_DEFAULT = 1 @annotator("Number {annotation} by position", wildcards=[Wildcard("annotation", Wildcard.ANNOTATION)]) def numb...
from unittest import TestCase from mock import patch, Mock from tables.rows.builders import TvShowSearchRowBuilder class MockTvShow: def __init__(self, name, rotten_tomatoes_score, start_year, end_year): self.name = name self.rotten_tomatoes_score = rotten_tomatoes_score self.start_year ...
# coding=utf-8 from unittest import TestCase from monitorrent.plugins.trackers.rutracker import RutrackerTracker, RutrackerLoginFailedException from monitorrent.tests import use_vcr from monitorrent.tests.rutracker_helper import RutrackerHelper class RutrackerTrackerTest(TestCase): def setUp(self): self.t...
import csv with open('file2.csv','r',newline='\r\n') as f: file_reader=csv.reader(f) for i in file_reader: print(i)
# import socket # import struct # def send( text, s): # msgbody = bytes(text.encode('utf-8')) # msglen = len(msgbody) # header = struct.pack('>H', msglen) # message = header + msgbody # s.sendall(message) # def recieve(sock): # data = b'' # while len(data) < 2: # data = sock.recv(1...
from time import sleep from bs4 import BeautifulSoup from urllib.request import urlopen, Request # from django.db import models from .models import Article def find_article(): url = 'https://medium.com/blockchain' r = Request(url, headers={'User-Agent': 'Mozilla/5.0'}) html = urlopen(r).read() soup = ...
import cv2 import numpy as np from matplotlib import pyplot as plt img = cv2.imread("brasao.jpg") color = ('b','g','r') for i, col in enumerate (color): histr = cv2.calcHist([img],[i],None,[256],[0,256]) plt.plot(histr,color= col) plt.xlim([0,256]) cv2.imshow("Imagem original",img) plt.show() cv2.waitKey(...
import dash import dash_html_components as html from os import sys, path sys.path.append(path.dirname(path.dirname(path.abspath(__file__)))) app = dash.Dash(__name__) server = app.server # Layout app.layout = html.Div([ # Title - Row html.Div( [ html.H1( '{{cookiecutter.a...
from multiprocessing import Pipe, Process from utils.importhelper import load from os import listdir, chdir, getcwd from subprocess import call config = {} ''' These classes below basically simulate structs as in C. ''' class package: ''' Stores a package for use in the updater script. ''' def __init...
from shoe import * from dealer import * import random class Table(object): def __init__(self,players,nDecks,bankroll,minBet,maxBet,bjmultiplier,dealtRatio): self.dealtRatio=dealtRatio self.bjmultiplier=bjmultiplier self.shoe=Shoe(nDecks) self.players=players self.bankroll=bankroll self.minBet=minBet self...
import cv2 import skimage import numpy as np from scipy import ndimage from functools import reduce import matplotlib.pyplot as plt import skimage.morphology as morph from skimage.color import rgb2gray from scipy.ndimage.morphology import binary_opening from skimage.segmentation import felzenszwalb, find_boundaries d...
class Element: def agg_state(self, t, v): if v == "fahrenheit": t = Iron.convert_fr(self, t) elif v == "kelvin": t = Iron.convert_cl(self, t) print('Температура в цельсиях: ' + str(t)) if t < self.t_plav: return 'Затвердение' elif t >= se...
#!/usr/bin/env python3 ''' @author: Josh Snider ''' import filters import pdb import tropes import unittest class TestTropes(unittest.TestCase): def test_sep_shoutouts(self): with tropes.Tropes(False) as datab: shoutouts = datab.get_shoutouts( 'http://tvtropes.org/pmwiki/pmwiki.php/TabletopGame...
from .player_profile import login, register def intro_graphic(): print( """ 888 d8b 888 888 888 Y8P 888 888 888 888 888 888888888 .d8888b888888 8888b. .d8888b888888 .d88b. .d88b. ...
import pandas as pd import numpy as np import tensorflow as tf from tensorflow import keras import matplotlib.pyplot as plt train = pd.read_csv('training_data.csv') test = pd.read_csv('testing_data.csv') validation = pd.read_csv('validation_data.csv') train_in = [] test_in = [] train_out = [] test_out = [] validation...
n=raw_input() import math r=float(n.split()[0]) n=int(n.split()[1]) a=float(2*r*math.sin(3.14/n)) p=float(n*a) print round(p,1)
from abaqusConstants import * from .GeometricRestriction import GeometricRestriction from ..Region.Region import Region class TopologyCyclicSymmetry(GeometricRestriction): """The TopologyCyclicSymmetry object defines a topology cyclic symmetry geometric restriction. The TopologyCyclicSymmetry object is de...
from PyQt5 import QtCore, QtGui, QtWidgets class noticeProfile(object): def setup(self, Notice,data): self.data = data Notice.setObjectName("Notice") Notice.resize(580, 429) self.frame = QtWidgets.QFrame(Notice) self.frame.setGeometry(QtCore.QRect(10, 10, 561, 381)) ...
# Run Selenium tests in parallel with Python for Selenium Python tutorial import pytest from selenium import webdriver import os from webdriver_manager.firefox import GeckoDriverManager from webdriver_manager.chrome import ChromeDriverManager import boto3 from selenium.webdriver import DesiredCapabilities from seleniu...
n = int(input()) i = 0 n += 3 while n>0: n -= 3 if n%5==0: j= n//5 print(i + j) break i += 1 if n<0: print(-1)
import joblib import numpy as np from ndarraydjango.fields import NDArrayField from sklearn.linear_model import LogisticRegression from sklearn.tree import DecisionTreeClassifier from sklearn.metrics import confusion_matrix, accuracy_score from django.db.models import * import pickle from census.models import Census f...
class Base(object): def clone(self): copy = self.__class__() for col in self.__table__.columns: val = getattr(self, col.name) setattr(copy, col.name, val) return copy def update_from_dict(self, d): for k, v in d.items(): setattr(self, k, v) ...
# -*- coding: utf-8 -*- """Добавляет к выбору цепи выбранного оборудования. Отфильтровывает из выбора лишние категории""" __title__ = 'Выбрать цепи\nоборудования' __author__ = 'SG' import re import clr clr.AddReference('System.Core') from System.Collections.Generic import * from Autodesk.Revit.DB import ElementId, Par...
import data import webbrowser #from T_Gui import update_count URL = "https://api.nasa.gov/planetary/apod" def run(): url_im = "" request = data.requests.get(URL, data.params) if request.status_code == 200: data.count_req = request.headers['X-RateLimit-Remaining'] url_im = data.json.loads(...
import os import unittest from urllib.parse import parse_qs import requests import requests_mock from gratisdns import AAAARecord, ARecord, GratisDNS, MXRecord, TXTRecord def mocked_response(fname): path = os.path.sep.join((os.path.dirname(os.path.abspath(__file__)), fname)) return open(path, 'r').read() ...
import cdaotg import webtest def test_get(): app = webtest.TestApp(cdaotg.app) # test when same length response1 = app.get('\pata?a=123&b=456') assert response1.status_int == 200 assert response1.content_type == 'text/html' assert response1.body.contains('123456') # test when a longer than b response2 = app....
import torch import torch.nn.functional as F from hessian_eigenthings.power_iter import Operator, deflated_power_iteration from hessian_eigenthings.lanczos import lanczos from sklearn.cross_decomposition import CCA from time import time import sys #%% This operator could be used as a local distance metric on the GAN im...
import os import glob import yaml import time import struct import argparse import multiprocessing import crcmod.predefined from queue import Empty from usbcan import CANFrame, run m3fc_id = 1 msg_id = lambda x: x << 5 m3fc_msg_cfg_profile = m3fc_id | msg_id(54) m3fc_msg_cfg_pyros = m3fc_id | msg_id(55) m3fc_msg_cf...
a = [1,2,3,5] while a[-1] < 4000001: k = a[-1] + a[-2] a.append(k) s = 0 for i in a: if i % 2 == 0: s += i print(s)
from evaluator import Evaluator from games.chess import Chess import chess class MaterialPositionChessEvaluator(Evaluator): def evaluate(self, game): """ Taken from https://medium.com/@andreasstckl/writing-a-chess-program-in-one-day-30daff4610ec https://www.chessprogramming.org/Simplified...
import pymysql import config as cfg import logging import sys import pandas as pd logger = logging.getLogger() logger.setLevel(logging.DEBUG) # Create formatter formatter = logging.Formatter('%(asctime)s-FILE:%(filename)s-FUNC:%(funcName)s-LINE:%(lineno)d-%(message)s') # Create a file handler and add it to logger. fi...
from flask_sqlalchemy import SQLAlchemy import base64 import hashlib import os import settings db = SQLAlchemy() with open(settings.PRIVATE_KEY_FILE, 'rb') as f: private_key = f.read(16) class Pony(db.Model): id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(255), unique=True) ...
from decouple import config import pika, json import os import django os.environ.setdefault("DJANGO_SETTINGS_MODULE", "prescriptions2.settings") django.setup() from entries.serializer import PrescriptionSerializer, PikUpSerializer from entries.models import OurPrescriptions params = pika.URLParameters(config('pika_para...
from pulumi import export as pulumi_export from pulumi import Output import app.__main__ as app_code import infra.__main__ as infra_code infra = infra_code kubeconfig = infra_code.cluster_kubeconfig app_infra = kubeconfig.apply( lambda val: app_code.create_app(kubeconfig_val=val) ) pulumi_export("endpoint_url", ...
import random import traceback from telebot import types, TeleBot import time import threading import config dnd = TeleBot(config.dndbot_token) db2 = config.mongo_client.dnd users2 = db2.users users = db2.users nowid = db2.nowid spells = db2.spells open_objects = db2.open_objects if open_objects.find_one({}) == None: ...
N, K, M = map(int, input().split()) A = list(map(int, input().split())) sum = 0 for i in range(N-1): sum += A[i] flag = 0 for i in range(K+1): if((sum + i)/N >= M): print(i) flag = 1 break if(flag == 0): print("-1")
import re from typing import List from abc import ABC, abstractmethod from source_hunter.utils.log_utils import logger from collections import OrderedDict class BaseParser(ABC): @abstractmethod def parse_children_modules(code_str: str): """ :param code_str: str, code string :return: li...
import FWCore.ParameterSet.Config as cms from RecoParticleFlow.PFClusterProducer.particleFlowClusterECALUncorrected_cfi import * particleFlowClusterOOTECALUncorrected = particleFlowClusterECALUncorrected.clone( recHitsSource = "particleFlowRecHitOOTECAL" )
from vk_api.keyboard import VkKeyboard, VkKeyboardColor class Keyboard(): def create_keyboard(response): themes = ['Социальная сфера','Политика','Экономика','Наркотики','Феминизм','Международные отношения',\ 'Спорт', 'СМИ', 'Мигранты', 'Религия', 'Этика'] themes_low = ['социальная...