text
stringlengths
38
1.54M
import sys from SocketServer import StreamRequestHandler, ThreadingTCPServer from PerfDataCache import PerfDataCache from RRD.RRDHandler import RRDHandler from utils.utils import decode, get_ip_address from utils.load_config import load_global_config from utils.get_logger import get_logger logger = get_logger('PerfD...
import itertools import argparse import os import time import argparse import numpy as np import tensorflow as tf import matplotlib.pyplot as plt import sys import random import collections import gym parser = argparse.ArgumentParser(description='PPO') parser.add_argument('--num-agents', type=int, default=8) parser.a...
from django.conf.urls import url from django.contrib import admin from shorten.views import create_shortcode, new_url, details_view urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^(?P<id>\d+)/$', new_url), url(r'^(?P<shortcode>[\w-]+)/$', details_view), url(r'^$', create_shortcode), ]
t=int(input()) while t>0: n=int(input()) a=[] for i in range(n): x=int(input()) a.append(x) a.sort() count=0 max_count=0 res=0 for i in range (n): count=a.count(a[i]) if max_count<count: max_count=count res=a[i] ...
import sys; sys.path.append("../modules"); sys.path.append("../../../CPlantBox"); sys.path.append("../../../CPlantBox/src") import plantbox as pb from functional.xylem_flux import XylemFluxPython # Python hybrid solver import visualisation.vtk_plot as vp import rsml.rsml_reader as rsml import matplotlib.pyplot as p...
"""Warning cog""" import discord import os import shutil from .utils.chat_formatting import * from .utils.dataIO import fileIO, dataIO from .utils import checks from discord.ext import commands from enum import Enum from __main__ import send_cmd_help colour = '099999' class Warn: def __init__(self, bot): ...
import unittest from unittest.mock import Mock from assertpy import assert_that from videothumbnailer.datamodel.datatypes import Chapter, TimeContainer as TC from videothumbnailer.io.fileio import FileIo from videothumbnailer.logic.dataserializer import DataSerializer from videothumbnailer.datamodel.datamodel import ...
inp=input ('Enter a file name: ') try: h=open (inp) except: print ('Invalid input!') exit() d=dict() words_list=[] for line in h: #line=line.rstrip()## Not needed when using list words indexes instead of line.startswith() words=line.split() if len(words)==0 : continue##Skips blank lin...
"""exercise_tracker URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/3.2/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Cl...
import sqlalchemy from sqlalchemy.ext.automap import automap_base from sqlalchemy.orm import Session from sqlalchemy import create_engine, func import datetime as dt import numpy as np from flask import Flask, jsonify ###Create and connect to databases engine = create_engine("sqlite:///Resources/hawaii.sqlite") Base...
import MySQLdb import tornado.ioloop import tornado.options import tornado.httpserver import tornado.web import os from tornado.options import define,options define('port',default='8888',help='run on the given port',type=int) define('mysql_host',default="localhost", help="database host") define('mysql_user',default='t...
import click from gensim.corpora.dictionary import Dictionary from gensim.models.coherencemodel import CoherenceModel from gensim.matutils import Dense2Corpus import numpy as np from torch.optim import Adam import torch from torch.utils.data import TensorDataset from tensorboardX import SummaryWriter import pickle fro...
from math import hypot, sqrt c1 = float(input('Insira o valor do cateto oposto: ')) c2 = float(input('Insira o valor do cateto adjacente: ')) print('A hipotenusa do triângulo é: {:.2f}'.format(hypot(c1,c2))) print('A hipotenusa do triângulo é: {:.2f}'.format(sqrt((c1**2 + c2**2))))
# 1 ''' n = 0 lista_n = list() while n < 6: nome = input("Nome %d: " % (n+1)) lista_n.append(nome) n += 1 nom_i = input("\nLeia nomes: ") while nom_i != "fim": if nom_i in lista_n: ind = lista_n.index(nom_i) lista_n[ind] = nom_i.upper() else: lista_n.app...
# encoding: utf-8 import sys import time import timeHelper import dbhelper import logging import copy reload(sys) sys.setdefaultencoding('utf8') TASK_TIMES_OF_RETRY_ON_ERROR = 1 # WAS 3 TASK_RETRY_SLEEP_TIME = 5 # ITERATED_TASK_ERROR_INTERVAL = 600 def abstract(): import inspect caller = inspect.getoute...
from aiogram.types import ReplyKeyboardRemove, \ ReplyKeyboardMarkup, KeyboardButton, \ InlineKeyboardMarkup, InlineKeyboardButton button_1hour = InlineKeyboardButton(text = '1 час', callback_data = '1hour') button_2hour = InlineKeyboardButton(text = '2 часа', callback_data = '2hour') button_3hour = InlineKeyboardBu...
"""Add core genes table Revision ID: 68b4dcb164af Revises: f6911f9c19ef Create Date: 2021-02-18 12:07:43.405371 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = '68b4dcb164af' down_revision = 'f6911f9c19ef' branch_labels = None depends_on = None def upgrade():...
__author__ = 'kai' import ROOT from root_numpy import root2array, root2rec import numpy as np from scipy.spatial import KDTree def main(): filename = '../Blatt7.root' signal_size = 10000 background_size = 20000 print("Reading Data from file " + filename) background = root2rec(filename, 'Untergr...
import numpy as np from util import * from PCA import PCA from LDA import LDA from KNN import KNN DATASET_DIR = './Yale_Face_Database/' TRAIN_DIR = DATASET_DIR + 'Training/' TEST_DIR = DATASET_DIR + 'Testing/' if not os.path.exists('./output'): os.mkdir('./output') train_faces, train_labels = read_faces(TRAIN_DIR...
# Generated by Django 2.0.1 on 2018-05-04 02:48 from django.db import migrations def load_basic_data(apps, schema_editor): db_alias = schema_editor.connection.alias RandomEncounterType = apps.get_model('campaign', 'RandomEncounterType') RandomEncounterType.objects.using(db_alias).bulk_create([ ...
import requests import bs4 response = requests.get('https://www.naver.com/').text soup = bs4.BeautifulSoup(response,'html.parser') # result = soup.select('div.PM_CL_realtimeKeyword_list_base span.ah_k') # result = soup.select('div.PM_CL_realtimeKeyword_list_base span.ah_r') result = soup.select('div.PM_CL_realtimeK...
from rest_framework import serializers from .models import Entries, User, SpeechTimeline, Face, AgeAll, AgeMale, AgeFemale class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['user_id', 'entry_date', 'description', 'password', 'total_quota', 'total_hours_analysed...
rule preprocess: input: "{sample}.fasta" output: "clear_{sample}.fasta" run: cmd = '''source activate antismash python Preprocess.py {input} 1000 source deactivate antismash''' shell(cmd) rule antismash: input: "{sample}/{sample}.txt" output: ...
from collections import defaultdict from itertools import product N = int(input()) f = defaultdict(int) for x, y, z in product(range(1, 100), repeat=3): n = x * x + y * y + z * z + x * y + y * z + z * x f[n] += 1 for i in range(1, N + 1): print(f[i])
import pytest import json import shapely.geometry import shapely.wkt import os import sys import inspect currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))) parentdir = os.path.dirname(currentdir) sys.path.insert(0,parentdir) from spatial_api import app testdata = [ ('POLYGON(...
# To use this code, make sure you # # import json # # and then, to convert JSON from a string, do # # result = cube_item_wrapper_from_dict(json.loads(json_string)) from typing import Optional, Any, List from cube.models.wrapper_util import * class CubeItemWrapper: symbol: Optional[str] market: Option...
import pandas as pd import numpy as np import csv import json from datetime import datetime from shapely.geometry import Point, shape def convert_to_unix_time(record): datetime_index = pd.DatetimeIndex([datetime(record['year'], record['month'], 1)]) unix_time_index = datetime_index.astype(np.int64) // 10**6 ...
import csv headers={'username','age','height'} value=[ {'王强',12,123}, {'lily',16,155}, {'carl',18,190} ] values=[ {'username':'王强','age':11,'height':22}, {'username':'李四','age':11,'height':21}, {'username':'张四','age':41,'height':21} ] # with open('classroom.csv','w',newline="") as fp: # writ...
""" Описать класс Shape - фигура, у которого должно быть 2 абстрактных метода: - get_perimeter для расчета периметра - get_square для расчета площади Описать класс Circle для круга, отнаследоваться от фигуры добавить недостающие атрибуты перегрузить методы get_perimeter и get_square Длина окружности = 2 * pi * r Площа...
from CourtFinder import db, ma class Court(db.Model): id = db.Column(db.Integer, primary_key=True) uid = db.Column(db.String(255), unique=True, nullable=False) address = db.Column(db.String(60), nullable=False) name = db.Column(db.String(80), nullable=False) total_courts = db.Column(db.Integer, d...
#!/usr/bin/env Python # coding=utf-8 import smtplib from email.mime.text import MIMEText from email.header import Header smtpsever='smtp.163.com' user='18701873051@163.com' password='123jhh' sender='18701873051@163.com' receive='jhh5845201314@126.com' subject=u'Web selenium 自动化测试报告' content='<html><h1 style="color...
class ClassNode: name = "" id = "" node_class = "" attributes = [] def __init__(self, name, node_id, node_class): self.name = name self.id = node_id self.node_class = node_class def __init__(self, name, node_id, node_class, attributes): self.name = name ...
from django.conf.urls import patterns, url from apps.register.views import RegisterView urlpatterns = patterns('', url(r'^$', RegisterView.as_view()), )
import numpy as np import random from openrec.utils.samplers import Sampler def YouTubeEvaluationSampler(dataset, max_seq_len, user_feature, seed=100, sort=True): random.seed(seed) def batch(dataset, user_feature=user_feature, max_seq_len=max_seq_len): while True: for user_id ...
''' 脚本一: 用例名称:验证根证书下发功能\验证根证书移除功能 编写人员:马丹丹 编写日期:2021/7/13 测试目的:验证根证书下发功能\验证根证书移除功能 测试步骤: 1.开启认证服务,通过命令ps -ef | grep verifymod、netstat -ultpn查询服务进程及服务端口是否存在 2.下发根证书文件到设备上 3.移除根证书文件 4.关闭认证服务,通过命令ps -ef | grep verifymod、netstat -ultpn查询服务进程及服务端口是否存在 预期结果: 1.认证服务开启成功,服务进程有/usr/local/ipauth/verifymod /etc/jsac/Initialize.co...
# To avoid retyping the attribute name in the descriptor declarations, we’ll generate a # unique string for the storage_name of each Quantity instance. class Quantity: _counter = 0 def __init__(self): cls = self.__class__ prefix = cls.__name__ index = cls._counter self.storage...
import math p = int(input().strip()) for a0 in range(p): prime = 'Prime' n = int(input().strip()) if n == 1: print('Not prime') elif n == 2: print('Prime') else: for i in range(2, math.ceil(math.sqrt(n))+1): if (n % i) == 0: prime = 'Not prime' ...
import json from flask import Blueprint, render_template, request from core.blueprints.user import login_required from sqlalchemy import asc from core.db_connector import db from core.models import GmapsBusiness, WeedMapping, WeedmapsShop weed_blueprint = Blueprint("weed_blueprint", __name__, url_prefix="/w...
# -*- coding: utf-8 -*- # Generated by Django 1.10.4 on 2017-01-09 18:46 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('core', '0017_student_action'), ] operations = [ migrations.CreateModel( ...
import unittest, pdb, argparse, test_inc, types, json PATH_SET_SONIC_TMPL = '/sonic' PATH_GET_SONIC_TMPL = '/sonic' TEST_CFG_VXLAN_JSON = """ { "VXLAN_TUNNEL": { "vtnl01": { "src_ip": "169.254.200.31", "dst_ip": "169.254.200.35" } }, "VXLAN_TUNNEL_MAP": { ...
import pandas as pd import numpy as np class Node: def __init__(self,elem): # used for storing and merging clusters self.left = None self.right = None self.parent = None self.elem = elem # list of data points in clusterS def dist(arr1,arr2): cos_sim=np.sum(arr1*arr2)/(np.sqr...
''' Created on 3 Jul 2019 @author: Ken ''' from django import template register = template.Library() @register.inclusion_tag('mainpage/coppyright.html', takes_context= True) def CoppyRightTag(context): result = {} return result
import aiohttp import asyncio from concurrent.futures import ( ThreadPoolExecutor, ) from django.db import ( migrations, ) import logging from pokeapi.utils import ( extract_id_from_uri, ) from pokeapi.utils.objects import ( create_pokemon, POKEMONS, ) import requests from typing import ( Any, ...
import torch import torch.nn as nn from torch.nn import init from torch.nn.utils import spectral_norm import functools from torch.optim import lr_scheduler import numpy as np import torch.nn.functional as F import math ############################################################################### # Helper Functions ...
from django.contrib import sitemaps from django.urls import reverse from django.contrib.sites.models import Site class StaticViewSitemap(sitemaps.Sitemap): priority = 0.8 changefreq = 'daily' def get_urls(self, site=None, **kwargs): site = Site(domain='www.exontime.com', name='www.exontime.com') ...
class Alphabets: def heart(self,name): grid = [[' ', ' ', ' ', ' ', ' ', ' '], [' ', 'O', 'O', ' ', ' ', ' '], ['O', 'O', 'O', 'O', ' ', ' '], ['O', 'O', 'O', 'O', 'O', ' '], [' ', 'O', 'O', 'O', 'O', 'O'], ['O', 'O', 'O', 'O', 'O', ' '], ['O', 'O',...
import weakref from .utils import opt_json roles = [ 'datastore::del', 'datastore::get', 'datastore::recent', 'datastore::set', 'domain::create', 'domain::destroy', 'domain::find', 'domain::get', 'domain::update', 'env::read', 'env::write', 'events::read', 'events::w...
# -*- coding: utf-8 -*- import gettext _ = gettext.gettext WELCOME_MSG = _("Welcome to {}") HELP_MSG = _("Welcome to {}. You can play, stop, resume listening. How can I help you ?") UNHANDLED_MSG = _("Sorry, I could not understand what you've just said.") CANNOT_SKIP_MSG = _("This is radio, you have to wait for prev...
import requests from .logger import Logger class Cryptonator: """ Class for interaction with cryptonator api (www.cryptonator.com) """ base_url = "https://api.cryptonator.com/api" logger = Logger("Cryptonator").get_instance() all_possible_currency_codes = list() @classmethod def get_e...
""" Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distri...
import numpy as np from scipy.io import loadmat import pdb import h5py class ImageSentenceFeatures: def __init__(self, args, split): # code only supports sampling 1 extra sentence, or take them all if split == 'train': sample_k_sentences = 1 else: sample_k_sentences ...
from tkinter import * from threading import * from tkinter import filedialog from tkinter import ttk import os import file_share import globalVars def chooseFile(): filePath = filedialog.askopenfilename() #!filetypes=(("All files", "*.*")) Why this is not working? entry1.delete(0,END) entry1.ins...
import webbrowser import pandas as pd import requests import time df10 = pd.read_csv('data.csv') df = df10.sort_values(by=['Price'], ascending=False) wallet = int(input()) con_rate = 73.6 wallet_in_dollars = wallet/con_rate df['Name'] = df[df['Price'] < wallet_in_dollars]['Name'] df = df.dropna() d...
from django.db import models from doctor_account.models import Doctorprofile from patient_account.models import Patientprofile from django.utils.translation import ugettext_lazy as _ from django.db.models.signals import post_save from django.dispatch import receiver from django.utils.text import slugify class Servi...
# @class_declaration elganso_sync # from models.flsyncppal import flsyncppal_def as syncppal class elganso_sync(flfactalma): params = syncppal.iface.get_param_sincro('apipass') def elganso_sync_damelistaalmacenessincro(self, params): try: if "auth" not in self.params: se...
n, m = map(int, input().split(" ")) a = list(map(int, input().split(" "))) b = list(map(int, input().split(" "))) Log = [0] * (1 << max(n, m)) for i in range(max(n, m)) : Log[1 << i] = i c = [1] * (1 << n) for i in range(1, 1 << n) : msk = i & -i lbt = Log[msk] c[i] = c[i ^ msk] * a[lbt] c.sort() d = [1...
import pandas as pd def create_pipeline(*functions): def pipeline(_in): res = _in for function in functions: res = function(res) return res return pipeline def create_set_index(index): def set_index(df): return df.set_index(index) return set_index def ...
# Chapter06-01 # 병행성(Concurrency) # 이터레이터, 제네레이터 # Iterator, Generator # 파이썬 반복 가능한 타입 # collections, text file, list, Dict, Set, Tuple, unpacking, *args... -> iterable # 반복문(for문 등) 사용가능? # 반복 가능한 이유? -> iter(x) 함수 호출 t ='ABCDEFGHIJKLMNOPQRSTUVWXYZ' for c in t: print('>', c) # while(위의 for문에서 이런 내부로직을 통해 값을 출력...
#!/usr/bin/env python import csv import numpy as np import matplotlib.pyplot as plt CSV_FILE_PATH = "/home/darobot/Research/water_quality/src/gds_tools/data/error_crash_odo_sat.csv" CSV_FILE_PATH_2 = "/home/darobot/Research/water_quality/src/gds_tools/data/error_crash_turbidity.csv" with open(CSV_FILE_PATH, 'r') as...
ISWR1 DEFINITIONS ::= %{ /* * * (C) Copyright 1989 by Carnegie Mellon University * * Permission to use, copy, modify, and distribute these programs * and their documentation for any purpose and without fee is * hereby granted, provided that this copyright and permission * notice appear on all copies and supp...
from datetime import datetime, timedelta import time import socket import threading import logging import logging.handlers import sys import binascii import struct remote_addr = '172.16.1.41' remote_port = 7272 class UdpEchoClient(threading.Thread): def __init__(self, rsock, log): threading.Thread.__ini...
def my_func(st): res = [] #Iterate over the characters for index, c in enumerate(st): if index % 2 == 0: #Refer to each character via index and append modified character to list res.append(c.upper()) else: res.append(c.lower()) #Join the list into a ...
import math import nltk import os from itertools import product from collections import defaultdict def ijk_iter(words, nonterm): 'lsym_ik, rsym_kj, sym_ij, logprob' for j in range(2, len(words) + 1): # スパンの右側 for i in range(j - 2, -1, -1): # スパンの左側(右から左へ) for k in range(i + 1, j): # rsy...
from flask_restful import Resource from flask import request, jsonify from model.models import db, Color, ColorSchema, Led, LedSchema, LedOutput, LedOutputSchema class LedSetting(Resource): def get(self): led = Led.query.all() led_schema = LedSchema(many=True) led_output = LedOutput.query....
from src.libraries import weather import requests import textwrap import json import io from PIL import Image """ resizes an image Args: required: imagePath : path to img wihin ./src/static/img width : pixel width optional: height : pixel height | will constrain proportions if unspecif...
#!/usr/bin/env python2.7 # Amazon FPGA Hardware Development Kit # # Copyright 2016 Amazon.com, Inc. or its affiliates. All Rights Reserved. # # Licensed under the Amazon Software License (the "License"). You may not use # this file except in compliance with the License. A copy of the License is # located at # # htt...
from lxml import html from collections import OrderedDict from time import sleep from os import listdir from os.path import isfile, join import requests import json import inspect import os import urllib3 urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) all_stocks = [ ('3M', 'MMM'), ...
""" Есть 2 рабочие смены через класс: class Shift: time_from: time time_to: time date_from: date date_to: date week_days: list Нужно проверить, что они не пересекают друг друга """ from datetime import date, time, timedelta from typing import Tuple def add_days(days_week: list, time_to: timedelt...
# -*- coding: utf-8 -*- """ Created on Sat Sep 29 10:13:10 2018 @author: Atul Anand """ def trapWater(list1): left=[0 for i in range(len(list1))] right=[0 for i in range(len(list1))] left[0]=list1[0] right[-1] = list1[-1] for i in range(len(list1)): left[i]= max(left[i-1...
STAGES = ( ('X', 'X'), ('0', '0'), ('1', '1'), ('2', '2'), ('3', '3'), ('4', '4'), ) MODIFIER = ( ('X', 'X'), ('A', 'A'), ('B', 'B'), ('C', 'C'), ('D', 'D'), ) TREATMENT_INTENT = ( ('UNK', 'Unknown'), ('Curative', 'Curative'), ('Palliative', 'Palliative'), ) TR...
# Load libraries import pandas as pd from sqlalchemy import create_engine # Create the database engine engine = create_engine('sqlite:///data.db') # Load hpd311calls without any SQL hpd_calls = pd.read_sql('hpd311calls', engine) # View the first few rows of data print(hpd_calls.head()) # Create the database engine ...
# @generated by generate_proto_mypy_stubs.py. Do not edit! import sys from google.protobuf.descriptor import ( EnumDescriptor as google___protobuf___descriptor___EnumDescriptor, ) from google.protobuf.internal.containers import ( RepeatedCompositeFieldContainer as google___protobuf___internal___containers___R...
import datetime def printTimeStamp(name): print("Автор програми: " + name) print("Час компіляції: " + str(datetime.datetime.now()),"\n") printTimeStamp("Valeriy Neroznak") import math as m a=1015 b=719.1 c=797.1 p=(a+b+c)/2 s=m.sqrt(p*(p-a)*(p-b)*(p-c)) print("Площа трикутника : %.2f"%s,"км**2")
from django.utils.timezone import now from tastypie.paginator import Paginator from urllib import urlencode __author__ = 'rudy' class StreamPaginator(Paginator): """ Paginates calls by putting a created date filter on the query if it doesn't exist so that duplicate objects are not sent down to the caller...
""" # UW Data Science # Please run code snippets one at a time to understand what is happening. # Snippet blocks are sectioned off with a line of #################### """ # import package import pandas as pd # Download the data url = "http://archive.ics.uci.edu/ml/machine-learning-databases/mammographic-masses/mammog...
import os import pytz from django.db import models from notification import settings class AppUser(models.Model): STATUS_ACTIVE = 1 STATUS_EXPERIMENT_DONE = 0 STATUS_HIDDEN = -1 STATUS_TYPES = ( (STATUS_ACTIVE, 'Active'), (STATUS_EXPERIMENT_DONE, 'Finish experiment'), ...
# Michael Wu (mvw5mf) import random print("Welcome to Pig!") player = 0 computer = 0 total_player = player total_computer = computer turn = 'y' switch = False # roll = random.randint(1,6) while total_player != 100 or total_computer != 100: while switch is False: roll = random.randint(1, 6) pri...
stock_tickers = {'ABB': {'ticker': '17979', 'description': 'ABB India Ltd'}, 'ABCAPITAL': {'ticker': '7310', 'description': 'Aditya Birla Capital Ltd'}, 'ABFRL': {'ticker': '946826', 'description': 'Aditya Birla Fashion and Retail Ltd'}, 'ACC': {'ticker': '17980', 'des...
import time import os from time import sleep from datetime import datetime import board import busio import adafruit_ads1x15.ads1015 as ADS from adafruit_ads1x15.analog_in import AnalogIn from adafruit_ads1x15.ads1x15 import Mode import keyboard # Create the I2C bus i2c = busio.I2C(board.SCL, board.SDA) # Create the...
#!/usr/bin/env python #build 2798 0.0 0.0 20300 2388 ? S Sep07 0:00 ssh -p 322 cygwin-19 cd /home/build/dailybuild; /home/build/dailybuild/buildcommoncygwin overlord /mvista/dev_area/mobilinux/tahoma070907_0703947/build 0703947 /opt/montavista mobilinux mobilinux /home/build/tahoma070907_0703947-exp...
from django.shortcuts import render from rest_framework import status from rest_framework.decorators import api_view from rest_framework.response import Response from esp.moc_esp import ProjectESP from games.models import Game from games.serializers import EmailValidSerializer ESP = ProjectESP() @api_view(['POST'])...
import datetime import pytz import requests import lxml.etree from tv_schedule import schedule, dateutil def need_channel_code(): return False _URL = 'http://boxingtv.ru/schedule/%Y/%m/%d' _source_tz = pytz.timezone('Europe/Moscow') _parser = lxml.etree.HTMLParser() _daydelta = datetime.timedelta(1) def get_s...
#문제 : https://www.acmicpc.net/problem/17142 #참고 : https://chldkato.tistory.com/124 from collections import deque from itertools import combinations import sys input = sys.stdin.readline dx = [1, -1, 0, 0] dy = [0, 0, 1, -1] def bfs(): cnt, cnt2 = 0, 0 while q: qlen = len(q) flag, flag2 = 0, 1 ...
import ipdb as pdb import sys import os sys.path.append(str(os.environ['QTRADE'])) from pyTrade.data.DataAgent import DataAgent import pandas as pd import unittest import logbook import datetime as dt import pytz ''' Way to use: python -m unittest --buffer --catch --failfast test_data.test_DataAgent.test_c...
import tensorflow as tf import numpy as np import cv2 def add_gradient_summary(grad, var): if grad is not None: tf.summary.histogram(var.op.name + "/gradient", grad) def get_image(imageL,imageAB): zero = np.zeros((imageL.shape[0],imageL.shape[1],3), np.uint8) # imageL = cv2.cvtColor(imageL,...
## Letter combination of a Phone Number class Solution: def letterCombinations(self, digits): map_dict = { 2:'abc', 3:'def', 4:'ghi', 5:'jkl', 6:'mno', 7:'pqrs', 8:'tuv', 9:'wxyz' } ...
from argparse import ArgumentParser import numpy as np from PIL import Image from utils import save_time import timeit def decrypt(image_reference, image_crypted, out_path="decrypt_text.txt"): imgSize = image_reference.size pixels_reference = image_reference.reshape(imgSize // 3, 3) pixels_crypted = imag...
''' This script looks at all csv files in a directory from which it takes all the paths to the wav files and applies normalisation. The normalisation applied is neg23 (EBU R128) and can be found at this link: https://github.com/esonderegger/neg23 Note: this script is based upon it and is modified for this project's c...
from django.contrib import admin from .models import csfaculty from .models import mtfaculty from .models import msfaculty from .models import llbfaculty from .models import otherfaculty # Register your models here. admin.site.register(csfaculty) admin.site.register(mtfaculty) admin.site.register(msfaculty) admin.si...
''' Unit tests for the generic image class functionality ''' import unittest from helpers import gbdx_vcr, mockable_interface, WV01_CATID, WV02_CATID from gbdxtools import CatalogImage class ImageUtilTest(unittest.TestCase): @classmethod def setUpClass(cls): cls.gbdx = mockable_interface() @g...
# 版本二,使用装饰器property和setter class Video: # 构造函数 def __init__(self, play_page=None, poster=None, banner=None, duration=None, score=None, title=None, play_count=None, region=None, introduction=None, sub_title=None, video_language=None, publish_time=None): '''用双下划线开头的变量,表示...
from sklearn.feature_extraction.text import CountVectorizer from nltk.corpus import stopwords from nltk.stem.wordnet import WordNetLemmatizer import codecs import util import string import spacy import concurrent.futures import logging from util import DataCorrection from string import digits import nltk import configu...
import turtle turtle.shape('turtle') turtle.speed(100) def draw_circle(direction, step): angle=2*direction for i in range(180): turtle.forward(step) turtle.left(angle) step=2.0 turtle.left(90) for i in range(0, 10, 1): draw_circle(1, step) draw_circle(-1, step) step+=0.3
from flask import Flask, request import cntk from driver import * import time app = Flask(__name__) @app.route('/score', methods = ['POST']) def scoreRRS(): """ Endpoint for scoring """ if request.headers['Content-Type'] != 'application/json': return Response(json.dumps({}), status= 415, mimetype...
from argparse import ArgumentParser from time import sleep import requests import base64 import sys import networkx as nx import numpy as np import pickle import os def convert_to_binary_vec(fpbytes): s = ''.join(["{:08b}".format(x) for x in fpbytes]) # binary string return np.array(list(map(int,...
import numpy as np import pandas as pd from keras.models import Sequential from keras.layers import Dense, LSTM, Dropout from keras.layers.core import Dense, Activation, Dropout from sklearn.preprocessing import MinMaxScaler from sklearn.metrics import mean_squared_error import matplotlib.pyplot as plt def create_data...
from django.template import Context from django.template.loader import get_template from utils import get_definitions from utils import get_indicators, get_indicator_type from models import System_Boundary, Generate_Requirements definitions = [ {'id': 1, 'name': "World Bank", 'definition': """Sustainable developme...
import matplotlib.pyplot as plt import numpy as np import tensorflow as tf from edward.models import Categorical, Normal import edward as ed def next_batch(dataset, N, i): left = i*N % len(dataset[0]) right = (i+1)*N % len(dataset[0]) if left < right : return dataset[0][left:right], dataset[1]...
from PyQt5 import QtCore, QtGui, QtWidgets import sys from tesa import Ui_Dialog app = QtWidgets.QApplication(sys.argv) Dialog = QtWidgets.QDialog() ui = Ui_Dialog() ui.setupUi(Dialog) Dialog.show() def bp(): ui.textEdit.setText("1 'a' синф ўқувчилари тўғрисида маълумот.\n\n" ...
import time, sys, os from pathlib import Path from datetime import datetime import argparse import findspark findspark.init("/opt/manual/spark") from pyspark.sql import SparkSession, functions as F ap = argparse.ArgumentParser() ap.add_argument("-i", "--input", required=True, type=str, default='hdfs://localhost:9000...