text
stringlengths
8
6.05M
from providers.google_rss import GoogleRSS url_list = ['https://lh4.googleusercontent.com/-s2WOC8Z-cu8/UtVS1nj0FfI/AAAAAAAACPs/RIhCZxCLuB4/w1200-h812-p/2013%2BLondon%2Bmeeting%2B098-sRGB%2Bsmall.jpg', 'https://lh4.googleusercontent.com/-s2WOC8Z-cu8/UtVS1nj0FfI/AAAAAAAACPs/RIhCZxCLuB4/w1200-h812/2013%2BLon...
#!/usr/bin/python3 # This is the Python 3.x client-sided script for a Chat Server. from socket import socket, AF_INET, SOCK_STREAM, error HOST = 'localhost' PORT = 1337 serverAddress = (HOST, PORT) Client_Socket = socket(family=AF_INET, type=SOCK_STREAM) try: Client_Socket.connect(serverAddress)...
import numpy as np list_data = [1, 2, 3] array = np.array(list_data) print("배열 타입 :",array.dtype) print("배열 크기 :",array.size) array1 = np.arange(4) #0~3까지 배열 만들기 array2 = np.zeros((4,4), dtype=np.float) #4x4 크기의 0으로 초기화된 배열 array3 = np.ones((1,4), dtype=np.str) #1x4 크기의 1로 초기화된 배열 array4 = np.rando...
import inspect import json import sys from difflib import ndiff from django.conf import settings from django.contrib.gis.gdal import DataSource from django.db import transaction from organisations.models import ( DivisionGeography, OrganisationDivision, OrganisationDivisionSet, ) from storage.shapefile imp...
df.describe() df.info() df.head() ##KNN # Import KNeighborsClassifier from sklearn.neighbors from sklearn.neighbors import KNeighborsClassifier # Create arrays for the features and the response variable y = df['party'].values #用values 令X和y都是Numpy arrays X = df.drop('party', axis=1).values #去掉party列 # Create a k-NN...
#In main program, three different methods are called to show the threefold model #The service designed in this program is to generate a four_digit class id based on an input integer #Both the first method and second method could generate the class id, however there's possibility #that a fault could hanppen and result...
from serializer import Serializer class YamlSerializer(Serializer): # function that parses py-obj to json-str def parse(obj): return json.dumps(obj) # function that unparses json-str to py-obj def unparse(str_data): return json.loads(str_data)
import logging import sys import inject sys.path.insert(0,'../../../python') from model.config import Config logging.getLogger().setLevel(logging.INFO) from autobahn.asyncio.wamp import ApplicationSession from asyncio import coroutine ''' python3 findUsersByIds d44e92c1-d277-4a45-81dc-a72a76f6ef8d python3 findUsersB...
from src.Algorithms.abstract_algorithm import AbstractAlgorithm class DFSAlgorithm(AbstractAlgorithm): def __init__(self, knight, endpoint, board): super().__init__(knight, endpoint, board) self.__stack_path = [] def calculate_path(self): self.__dfs_helper(self.initial_x, self.initia...
from pdfminer.converter import PDFPageAggregator from pdfminer.layout import LAParams from pdfminer.pdfparser import PDFParser from pdfminer.pdfinterp import PDFDocument from pdfminer.pdfinterp import PDFResourceManager from pdfminer.pdfinterp import PDFPageInterpreter from pdfminer.pdfdevice import PDFDevice import os...
import re import uuid import boto3 from flask import current_app IMAGE_MIME_TYPES = set(['image/png', 'image/jpg', 'image/gif']) AVATAR_MAX_SIZE = 2 * 1024 * 1024 # 2MB class AvatarException(Exception): pass def allowed_avatar_type(mimetype): if mimetype not in IMAGE_MIME_TYPES: raise AvatarExcep...
o = open('1.txt', 'r') w = open('2.txt', 'w') for line in o: w.write(line) o.close() w.close()
import pandas as pd import matplotlib.pyplot as plt house = pd.read_csv('https://drive.google.com/uc?export=download&id=1kgJseOaDUCG-p-IoLIKbnL23XHUZPEwm') #%% numerical house['bedrooms'].describe() ''' box plot ''' fig = plt.figure(figsize=(10,8)) house['bedrooms'].plot.box() fig = plt.figure(figsize...
# -*- coding: utf-8 -*- # Generated by Django 1.9.2 on 2016-12-01 10:59 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('lhcbpr_api', '0002_auto_20160419_0727'), ] operatio...
import camera camera = camera.Camera(False) while True: frame = camera.read() print len(frame.getvalue())
from datetime import datetime from requests.exceptions import ConnectionError from django.test import TestCase from fetcher.tools import TleParser class TleParserTestCase(TestCase): """ Test the behavior of the TleParser tool """ def test_canImportTlecatparser(self): """ Tes...
import os, os.path as osp from torch.utils.cpp_extension import load dir_path = os.path.dirname(os.path.realpath(__file__)) lltm_cpp = load( name="lltm_cpp", sources=[osp.join(dir_path, "lltm.cpp")], extra_cflags=['-O2'], verbose=True ) # Example usage # from lltm.jit import lltm_cpp
import random import logging class AbstractSolver: """Base class for all maze solvers. Every solver implements its own algorithm to solve a maze by using or overriding the base class methods.""" def __init__(self, seed=0): self.log = logging.getLogger(__name__) self.path = [] self...
# -*- coding: utf-8 -*- __all__ = ['public_method'] def public_method(): print 'public_method' def private_method(): print 'private_method'
import exceptions from tstorm.utils import release from tstorm.utils import limit class RangeError(exceptions.Exception): pass class Range: def __init__(self, range_value): self.sup = limit.Limit(range_value[len(range_value)-1]) if not self.sup.is_sup(): raise RangeError('Superior ...
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Date : 2017-11-28 17:14:46 # @Author : swz # @Email : js_swz2008@163.com from bs4 import BeautifulSoup import os from download import http import pymongo import datetime import re import shutil class mzitu(): def __init__(self): self.client = pymongo....
#!/usr/bin/python #Vivek Sinha print "Content-Type: text/html" print import paramiko ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy( paramiko.AutoAddPolicy() ) ssh.connect('glgw4006.grid.uh1.inmobi.com', username='vivek.sinha', password='Password@123') stdin, stdout, stderr = ssh.exec_command('/opt/grids...
#!/usr/bin/env python # Copyright (c) 2011 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Confirms presence of files generated by our targets we depend on. If they exist, create a new file. Note target's input files are explic...
a=float(input("Length of one side")) b=float(input("Length of second side")) c=(a**2+b**2)**0.5 print("The length of Hypotenuse is",c)
import pygame import pprint pygame.init() pygame.mouse.set_visible(0) fancyFont = 'fonts/Aladin-Regular.ttf' plainFont = 'fonts/Arial.ttf' white = (255, 255, 255) purple = (57,2,68) pale = (209,203,211) black = (51,51,51) rain = (28,116,153) screen = pygame.display.set_mode((800, 480)) timeFont = pygame.font.Font(f...
#Main Restaurant page @app.route('/') @app.route('/restaurants/') #Create New Restaurant @app.route('/restaurant/new') #Edit Restaurant @app.route('/restaurant/<int:restaurant_id>/edit/') #Delete Restaurant @app.route('/restaurant/<int:restaurant_id>/delete/') #Show Restaurant Menu @app.route('/restaurant/<int:rest...
# coding=utf-8 def readAsDict(path): '''读取为str类型的字典,value可为空,不为None''' with open(path, 'rb') as f: kv = {} for line in f: line = line.replace('\r', '').replace('\n', '').strip() if line.startswith('#') or line == '': continue tokens = line.spl...
def factorial(n): i = 1 p = 1 while i <= n: p *= i i += 1 return p print(factorial(10)) print(factorial(11)) print(factorial(12)) # 檔名: exercise0805.py # 作者: Kaiching Chang # 時間: July, 2014
#-coding:utf-8 print list(range(1, 11)) L = [] for x in xrange(1,11): L.append(x*x) print L #列表生成式 print [x*x for x in xrange(1, 11)] print [x*x for x in xrange(1, 11) if x%2 == 0] #两层循环 print [x+y for x in ['a','b','c'] for y in '123'] #列出当前目录所有文件及文件名 import os print [d for d in os.listdir('.')] L = ['HELLO', '...
""" Model objects for the Nova mimic. """ from __future__ import absolute_import, division, unicode_literals import re import uuid import attr from random import randrange from json import loads, dumps from six.moves.urllib.parse import urlencode from six import string_types from six import text_type from mimic.uti...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models from django.contrib.auth.models import User class Note(models.Model): PRIVATE = 'PV' PUBLIC = 'PL' URL = 'UR' PUBLISHMENT_STATUS_CHOICES = ( (PRIVATE, 'Private'), # 表示不可。本人が編集閲覧のみ (PUBLIC, '...
from game import Game import sys def main(): game = Game() game.run() sys.exit() if __name__ == '__main__': main() """ BEhaviour: Game over: -snake touch edge of screen -snake touch itself snake movement: -body trails its head snake...
#!/usr/bin/env python print('Content-type: text/plain\n\nhello world from RSAL')
import cv2 import numpy as np lower_white = np.array([0, 0, 150]) # 0,0,200 5,100,100 , 0,0,200 - bardzo czule upper_white = np.array([180, 50, 255]) # 180,50,255 25,255,255 - 180, 255, 255 lower_pink = np.array([160, 100, 100]) upper_pink = np.array([179, 255, 255]) lower_dark_green = np.array([50, 60, 60]) up...
''' Created on Jul 26, 2013 @author: emma ''' from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.action_chains import ActionChains from robot.libraries.BuiltIn import BuiltIn class BillingInfo: ROBOT_LIBRARY_SCOPE = 'GLO...
# -*- encoding: utf-8 -*- ############################################################################## # # OpenERP, Open Source Management Solution # # Copyright (c) 2014 Noviat nv/sa (www.noviat.com). All rights reserved. # # This program is free software: you can redistribute it and/or modify # it under...
#import dask.bag as db #db.read_text('*.json').map(json.loads).pluck('name').frequencies().compute() import z import dask.dataframe as dd import dask import pandas as pd import os dask.config.set(scheduler='threads') def getName(path): return os.path.splitext(os.path.basename(path))[0] dfd = None def convertToD...
from sigpy.learn import app from sigpy.learn import util __all__ = ['app'] from sigpy.learn.util import * # noqa __all__.extend(util.__all__)
class Shell_sort: ''' shell排序 :type nums: List[int] 要排序的数组 ''' def sort(self, nums): ''' :type nums: List[int] 要排序的数组 ''' m = len(nums) gap = m//2 while gap > 0: for i in range(gap, m): j = i while j - gap >...
#!/usr/bin/env python3 # Copyright (c) 2012, the Dart project authors. Please see the AUTHORS file # for details. All rights reserved. Use of this source code is governed by a # BSD-style license that can be found in the LICENSE file. import logging import monitored import re typed_array_renames = { 'ArrayBuffer'...
class Solution: def zigzagLevelOrder(self, root: Optional[TreeNode]) -> List[List[int]]: q = collections.deque() if root: q.append(root) result = [] flag = True while q: l = len(q) temp = [] for _ in range(l): c...
import random import csv '''rate=0.2''' def add_data(rate,load,save): file = open(load) line = file.readline() listCsv = [] neg=[] pos=[] while line!='': listCsv.append(line.split(',')) line = file.readline() print(listCsv) for a in range(1,len(listCsv)): if(int(...
import RPi.GPIO as GPIO import time # Pin Constants LED = 23 GPIO.setmode(GPIO.BCM) GPIO.setup(LED, GPIO.OUT) #GPIO.setup(24, GPIO.IN, pull_up_down = GPIO.PUD_UP) on = True try: while True: if on: GPIO.output(led, 0) on = False else: GPIO.output(led, 1) on = True time.sleep(1) except KeyboardIn...
from datetime import datetime def date_to_mins(date): try: day = datetime.strptime(date, '%m/%d/%Y') except ValueError: return -1 return (day - datetime(day.year, 1, 1)).total_seconds() / 60 + 1440
from socket import * import time import re import sys import os tcpSerPort = 80 server_ip = '127.0.0.1' if len(sys.argv) != 3: print(sys.argv) print("Usage: python3 this.py server_ip port_num") else: server_ip = sys.argv[1] tcpSerPort = int(sys.argv[2]) print("Will use the deafule setting with port number %d and s...
import dataclasses import os import typing import requests access_token = os.getenv('QIITA_ACCESS_TOKEN', None) headers = {} if access_token: headers.update({ "Authorization": f"Bearer {access_token}" }) @dataclasses.dataclass class User: description: str facebook_id: str followees_cou...
# -*- coding: utf-8 -*- """ ############################################################################## The calculation of whole holistic invariant molecular descriptors (WHIM). You can get 70 molecular decriptors. You can freely use and distribute it. If you hava any problem, you could contact with us timely! ...
import xml.etree.ElementTree as xml from xml.dom import minidom import os import sys def custom_package_xml_generator(directory, packagename=None, version='45.0', filename='package.xml'): """Create custom package.xml file from directories with metadata""" METADATA_TYPE = { 'applications':'CustomAppli...
# -*- coding: utf-8 -*- """ Created on Mon Jul 11 20:27:24 2016 @author: Srinivas """ def testing_data(x, *y=1): print x, 'is also' for i in y: print i
#!/usr/bin/env python3 import dadi import numpy as np import matplotlib.pyplot as plt def bottleneck(params, ns, pts): """ Model 2 ------- Bottleneck followed by growth. Parameters ---------- nu0: Relative size of pop after bottleneck. T: Time of bottleneck. F: Inbreeding coeff...
inf = 999999 negInf = -999999 import os class GameBoard(): def __init__(self): self.board = [[' ' for i in range(0,7)] for j in range (0,6)] self.position = [] def show_board(self): os.system(['clear','cls'][os.name == 'nt']) print(self.board[0]) print(self.board[1]...
from django.db import models from string import capwords from datetime import datetime, timedelta from django.utils.timezone import utc from django.contrib.auth.models import User from lok.utils import level_from_value as level_from_value from lok.utils import value_from_level as value_from_level import random from ran...
import unittest from export_workers.workers.send_email.email_listener import job_listener import pika CONNECTION = pika.BlockingConnection( pika.ConnectionParameters(host="localhost", port=5672)) CHANNEL = CONNECTION.channel() CHANNEL.queue_declare(queue='answer_to_export') class CreateFileWorker(unittest.Test...
from flask import Flask, request from flask_mysqldb import MySQL app = Flask(__name__) app.config['MYSQL_HOST'] = 'localhost' app.config['MYSQL_USER'] = 'root' app.config['MYSQL_PASSWORD'] = '' app.config['MYSQL_DB'] = 'sports_synthesis' mysql = MySQL(app) @app.route('/signup',methods=['POST']) def signup(): i...
import pytest #import make_network #def test_answer(): # assert func(3) == 5
from django.contrib.auth import get_user_model, authenticate, password_validation from django.test import TestCase from user.form import UserCreateForm User = get_user_model() DATA = { 'first_name': 'test', 'last_name': 'test', 'email': 'test@example.com', 'password': 'Testing@123', } class LogInTest(TestCase)...
import logging from django.template import loader, Template, TemplateDoesNotExist, TemplateSyntaxError, TextNode from vacuum.rules import registered_rules class TemplateChecker(object): def check_template(self, template): """ Checks the given template for badness. """ if not ...
# Generated by Django 3.0.3 on 2020-05-19 09:00 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='WeatherBase', fields=[ ...
import requests import json json_obj = json.loads("{'key':'value'}") json_str = json.dumps(json_obj) # to get json responce headers = { 'Uer-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36', 'Accept':'application/json', 'X-R...
import sys sys.path.append('.') from objp.util import dontwrap class Simple: def hello_(self, name: str): print("Hello %s!" % name) print("Now, let's try a hello from ObjC...") from ObjCHello import ObjCHello proxy = ObjCHello() proxy.helloToName_(name) print("Oh, an...
#!/usr/bin/env python # -*- coding:utf-8 -*- __author__ = 'lish' import random def ProduceRandomStr(strlen): """ 获取指定个数的包含大小写字母和数字的字符串 :param bits: :return: """ n_set = [chr(i) for i in range(48,58)] b_char_set = [chr(i) for i in range(65,90)] s_char_set = [chr(i) for i in range(97,122...
# Generated by Django 2.0.5 on 2018-06-03 15:26 import django.core.validators from django.db import migrations, models import re class Migration(migrations.Migration): dependencies = [ ('calculation', '0009_auto_20180603_1003'), ] operations = [ migrations.AlterModelOptions( ...
""" find_element_by_id find_element_by_id find_element_by_xpath find_element_by_link_text find_element_by_partial_link_text find_element_by_tag_name find_element_by_class_name find_element_by_css_selector _________________________ from selenium.webdriver.common.by import By example: button = browser.find_element(By.ID...
n = int(input()) i = 0 while i != n: catalogo = {} total_arvores = 0 # lendo e contando os dados em um dicionario while len(catalogo) <= 10000 and total_arvores < 1000000: especie = input() if len(especie)==0: break if especie not in catalogo: catalogo[esp...
import time from subset_sum import SubsetSum s = SubsetSum() print s for i in range(0, 3): for j in range(1, 6): n = 10 ** i * j s.generar_problema_aleatorio("../in/subsetSum" + str(n) + ".txt", n, 0, 100) start = time.time() print s.resolver_problema("../in/subsetSum" + str(n) + "....
#!/usr/bin/python def gcd(a, b): if b == 0: return a else: return gcd(b, a % b) a = int(input("Enter the first number: ")) b = int(input("Enter the second number: ")) print("greatest common divisor: " + str(gcd(a, b)))
# This module contains the possible operations we can make on solutions and routes import cvrp.utile as utile import numpy as np import cvrp.const as const # Compute the demand of the route given def route_demand(route): d = 0 for i in route: d += const.demand[i] return d # Compute the cost of ...
import json class ConfigrationReader(object): def __init__(self, gitChangesFile, config, couldfomrationOutputs): try: self.configuration = json.loads(open(config, "r").read()) self.__outputFile = json.loads(open(couldfomrationOutputs, "r").read()) self.output = self.__o...
from setuptools import setup setup( name='GameAI-Courswork', author='Ekrem Emre', description='', install_requires=['pandas', 'sklearn', 'graphviz'] )
from initROOT import initROOT import ROOT from ROOT import gROOT, TCanvas, TF1,TFile,TTree import numpy as np import matplotlib.pyplot as plt import matplotlib.mlab as mlab from scipy.stats import norm from scipy import stats from array import array from math import * import cPickle as pickle ##################plot re...
# -*- coding: utf-8 -*- ''' Created on Apr 23, 2021 @author: flba ''' import pytest from pages.gmail import PageGmail from pages.yamm import Yamm from pages.spreadsheet import GoogleSpreadSheet from data.test_data import GMAIL_URL, SPREADSHEET_URL, SENDER_NAME, TEST_MAIL,\ TEST_MAIL_PASS, DRAFT_NAME, SPREADSHEET_N...
#_author_: Matas Kulikauskas #imports: import numpy as np import matplotlib.pyplot as plt from scipy.interpolate import interp1d plt.title('Figure 18.15 (Earthshine)') plt.xlabel('Earth phase angle (deg.)') plt.ylabel('Polarization degree (%)') vx1 = [49.1025641, 60.38461538, 71.66666667, 83.84615385, 95.76923077] v...
from __future__ import print_function from threading import Lock import requests import colorama import sys import os try: input = raw_input except NameError: pass def clear(): os.system('cls' if os.name=='nt' else 'clear') def github_version(): try: version = requests.get("https://raw.githubusercont...
import sys import sqlite3 from PyQt5.QtWidgets import QApplication, QMainWindow, QTableWidget, \ QTableWidgetItem from PyQt5 import QtCore, QtGui, QtWidgets class Ui_MainWindow(object): def setupUi(self, MainWindow): MainWindow.setObjectName("MainWindow") MainWindow.resize(644, 484) se...
from sqlalchemy.orm import Session from sqlalchemy.orm.scoping import instrument, makeprop from sqlalchemy_auth import AuthException, ALLOW, DENY class _BadgeContext: """ Allows for `with session.switch_badge():` syntax. """ def __init__(self, session): self.session = session self.bad...
#!/usr/bin/env python3 """ Update the full files for each rarity. """ import glob def main(rarity_file='rarities.yaml'): """ Create full files for each rarity. """ for rarity in glob.glob('*s/'): lines = [] for rare_file in glob.glob('{}*.dec'.format(rarity)): with open(rar...
import asyncio import logging import json from websockets.exceptions import InvalidState _log = logging.getLogger(__name__) @asyncio.coroutine def keep_alive(websocket, ping_period=30): while True: yield from asyncio.sleep(ping_period) try: yield from websocket.ping() except...
#Lauren Flanagan #import the required libraries import pandas as pd import numpy import numpy as np import seaborn as sn import matplotlib.pyplot as plt import eli5 from sklearn.linear_model import LogisticRegression as logr from sklearn.metrics import confusion_matrix, accuracy_score, precision_score, rec...
from numpy import arange, linspace, mean from scipy.stats import expon, zscore, norm import matplotlib.pyplot as plt from math import log10 # 30개의 샘플을 추출하고 표준화 하는 과정 times = 10 l = 10 loc = 0 m = [] for i in arange(times): m.append(mean(expon(loc, l).rvs(size=30))) #Lambda = 10인 지수분포를 랜덤으로 30개 생성하고 그 평균을 구해 배열(m)...
# -*- coding: utf-8 -*- """ Created on Fri Dec 11 20:33:43 2020 @author: Ayax """ import random import array import numpy import pandas as pd from deap import algorithms from deap import base from deap import creator from deap import tools #Definimos la matriz al leer desde un archivo csv matriz = pd....
# Copyright 2022 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). import pytest from pants.util.pip_requirement import PipRequirement def test_parse_simple() -> None: req = PipRequirement.parse("Foo.bar==1.2.3") assert req.project_name == "Foo....
number = float(input()) inputme = input() output = input() if inputme == "m" and output == "cm": number *= 100 elif inputme == "m" and output == "mm": number *= 1000 elif inputme == "cm" and output == "m": number /= 100 elif inputme == "cm" and output == "mm": number *= 10 elif inputme == "mm" and outp...
#!/usr/bin/python import sys import http_server import proxy import storage import tiles import wm_cache _DEFAULT_PORT = 15000 def RunServer(): tiles_path = sys.argv[1] hash_dir_root = sys.argv[2] server = http_server.MoreBaseHttpServer(_DEFAULT_PORT) proxy_cache = proxy.Cache('localcache') proxy_cache....
from django import template register = template.Library() @register.filter(name='chuyi') def chuyi(value, arg): a = value/arg return '%.2f' % a @register.filter(name='roundtwo') def roundtwo(value): return '%.2f' % value
from django.shortcuts import render from django.http.response import HttpResponse from .models import Members from pages.views import index # Create your views here. # def index(req): # return HttpResponse("<h1>hello</h1>") # def index(req): # return render(req, 'index.html') def login(req): if req.met...
# Generated by Django 2.2.1 on 2019-06-21 16:35 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('questi', '0019_auto_20190621_1833'), ] operations = [ migrations.AddField( model_name='score', ...
from django.urls import path from . import views # http://127.0.0.1:8000/about/ urlpatterns = [ path('', views.intro, name="intro"), path('intro/', views.intro, name="intro"), path('contact/', views.contact, name="contact"), path('faq/', views.faq, name="faq"), path('policy/', views.policy, name="p...
# -*- coding: utf-8 -*- """Parsers and serializers for /decoder API endpoints."""
#!/usr/bin/env python # coding: utf-8 # Copyright (c) Qotto, 2019 """BaseEventHandler All event handler must be inherit from this class. Handle function was called by consumer on each received events. For make an transaction in handle function return 'transaction' as string after end transaction otherwise return non...
import requests from bs4 import BeautifulSoup import urllib.request #Added comments def main_crawler(url): source=requests.get(url) source=source.text soup=BeautifulSoup(source,"html.parser") for links in soup.findAll('a',{'class':'question_link'}): link=links.get('href') if(link[0]==...
""" Edanur Demir Utilities are defined in this code. """ import os import csv import torch import pandas as pd import numpy as np import matplotlib.pyplot as plt import matplotlib.ticker as tick from torchvision import datasets, transforms from custom_eenet import CustomEENet from eenet import EENet plt...
import logging log = logging.getLogger(__name__) """Classes that remember parameters during training, e.g., remember best model so far""" class RememberBest(): def __init__(self, chan_name): self.chan_name = chan_name self.best_epoch = 0 self.lowest_val = float('inf') def re...
# -*- coding: utf-8 -*- import logging import os import sys import time from pythonjsonlogger.jsonlogger import JsonFormatter from sanic.log import DefaultFilter import ujson from jussi.typedefs import WebApp LOG_DATETIME_FORMAT = r'%Y-%m-%dT%H:%M:%S.%s%Z' os.environ['TZ'] = 'UTC' time.tzset() # JsonFormatter.conver...
import copy import re import nltk import numpy as np from HostileSet import * from sklearn import feature_extraction from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.metrics.pairwise import cosine_similarity from scipy.stats import kstest from nltk.corpus import stopwords from nltk.sentiment.vad...
import eons, esam import logging import pandas as pd class Pandatum(esam.Datum): def __init__(self, name=eons.INVALID_NAME()): super().__init__() def ToDataFrame(self): return pd.DataFrame.from_dict(self.__dict__, orient='index') def FromDict(self, rhs): # logging.info(rhs) ...
import numpy as np from torch import tensor from doa_math import tensor_angle class ToleranceScore: def __init__(self,thresholds,doa_classes): size = len(thresholds) self.CC = np.zeros(size) self.CX = np.zeros(size) self.XC = np.zeros(size) self.XX = np.zeros(size) self.thresholds = threshold...
a = 4 # 4 = 100 b = 11 # 11 = 1011 c = 0 c = 4|11 print("Line1-Value of c is ", c) c = 4>>11 print("Line2-Value of c is ", c) c = 4^11 print("Line3-Value of c is ", c) c = ~4 print("Line4-Value of c is ", c) c = 11&4 print("Line5-Value of c is ", c)
#!/usr/bin/env python # -*- coding: utf-8 -*- ############################################################################### # # 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...
import tensorflow as tf import numpy as np import matplotlib import matplotlib.pyplot as plt from sklearn import datasets from sklearn import preprocessing ''' 1. trees.csv를 읽어들여서 아래에 대해 Volume을 예측해 보세요.(텐서, 케라스) Girth 8.8, 10.5 Height 63, 72 ''' data = np.loadtxt("../../../data/trees.csv", delimiter=",", skiprows=...
import BayesianNetwork; import edge; class AveragedBayesianNetwork: def __init__(self, topologicalOrdering): self.topologicalOrdering = topologicalOrdering; self.edgeCounts = {}; self.numModelsConsidered = 0; for childIndex in range(len(topologicalOrdering)): for parentIndex in range(childInde...