text
stringlengths
8
6.05M
from typing import TypeVar, Union from pydantic import BaseModel sentinel = object() Url = str JsonType = Union[int, str, bool, list, dict] T = TypeVar('T') T_body = TypeVar('T_body', BaseModel, int, str, bool, covariant=True) T_json_obj = TypeVar('T_json_obj', BaseModel, list, int, str, bool, covariant=True) T_head...
import asyncio import logging import gzip from io import BytesIO from datetime import datetime from aiowebsocket.converses import AioWebSocket import json import sqlite3 import ssl ssl._create_default_https_context = ssl._create_unverified_context conn = sqlite3.connect('btc_tick.db') cursor = conn.cursor() cursor.ex...
import unittest from app import formatDate from datetime import date import database_api from sqlalchemy import create_engine from database import ExchangeRateModel,Base from sqlalchemy.orm import sessionmaker class DateTestCases(unittest.TestCase): def test_date(self): self.assertEqual(date(2018,1,1),formatDate("...
# -*- coding: utf-8 -*- """ Created on Wed Feb 24 20:40:49 2021 @author: jfalk Pulling stock data using pandas-datareader Analyzing it...somehow FUCKING TENDIES BABYYYYYYYYYYYYYY Want to estimate the low for the day to guess best time to buy """ import pandas as pd import numpy as np import os ...
#!/bin/python3 """ Compute the edit distance between two strings """ def main(): print(edit_distance(input(), input())) def edit_distance(A, B): a_len = len(A) b_len = len(B) # use zeroth array indexing by taking advantage of how -1 wraps to the # end of an array: 0-length precomputed row & colum...
import numpy as np import torch from sklearn.metrics import roc_curve import sklearn.metrics as sk_metrics def most_recent_n(x, orig, n, metric): sgn = np.sign(orig) orig_mask = orig.copy() for i in range(orig_mask.shape[0]): num_revs = orig_mask[i,:].astype(bool).sum() if n > num_revs: ...
"""Hypergeometric Distribution Gendankenexperiment: Foreground and background sequence sets are pre-defined. Given N foreground sequences and M-N background sequences, we randomly select N sequences from M. We consider the consensus residue in the foreground as being type I and ask w...
from openspending.model import Classifier from openspending.test import DatabaseTestCase, helpers as h def make_classifier(): return Classifier(name='classifier_foo', label='Foo Classifier', level='1', taxonomy='class.foo', des...
# Generated by Django 3.1.7 on 2021-04-07 07:16 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('authentication', '0005_auto_20210401_1635'), ] operations = [ migrations.RemoveField( model_name='user', name='group...
#coding=utf-8 from django import forms from Apps.Materia.models import Materia #formulario para crear materia class FormCrearMateria(forms.ModelForm): class Meta: model = Materia fields = [ 'id', 'nombre', 'intensidad', ] labels = { 'id': 'Identificación', 'nombre': 'Nombre', 'intensidad': 'Inten...
import logging import math from backend.group_service.group.domain.group import Group, GroupSerializer from backend.user_service.user.domain.rider import Rider from backend.user_service.user.domain.driver import Driver from backend.common.messaging.infra.redis.redis_message_publisher \ import RedisMessagePublish...
from echo_server import create_server_socket, send_msg, recv_msg import socket if __name__ == '__main__': client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) client_socket.connect(('localhost', 8000)) msg = input('Type the message:') try: send_msg(client_socket, msg) ...
from typing import Counter def solution(string): c = Counter() for i in string: c[i] += 1 for i in string: if c[i] == 1: return i return '\0' print(solution('fjdjfljfdslfjdsj\n')) """ 题目二:字符流中第一个只出现一次的字符 """ class Solution: def __init__(self): self._contai...
#!/usr/bin/python # -*- coding: utf-8 -*- # Author: Gusseppe Bravo <gbravor@uni.pe> # License: BSD 3 clause """ This module provides a few of useful functions (actually, methods) for describing the dataset which is to be studied. """ from __future__ import print_function import numpy as np import matplotlib.pyplot as...
gkey = "get google api"
from typing import Optional, Dict from summer import StrainStratification, Multiply from autumn.models.covid_19.parameters import VocComponent from autumn.models.covid_19.constants import DISEASE_COMPARTMENTS, Strain, INFECTION def get_strain_strat(voc_params: Optional[Dict[str, VocComponent]]): """ Stratif...
#Weighted Average of 4 items #Has many issues while True: w1 = float(raw_input('Enter Weight 1\n')) if w1 == 'next': break w2 = float(raw_input('Enter Weight 2\n')) if w2 == 'next': break w3 = float(raw_input('Enter Weight 3\n')) if w3 == 'next': break w4 ...
import numpy as np import pyqg import pytest import unittest def QG(): return pyqg.QGModel def Layered(): return pyqg.LayeredModel def SQG(): return pyqg.SQGModel def BT(): return pyqg.BTModel @pytest.fixture(params=[QG, Layered, SQG, BT]) def model(request): klass = request.param() model =...
#!/usr/bin/env python import sys import os import optparse import urlparse from util import open_xml, filter_manifest, ProjectJSONEncoder from project import Project, project_differences import json def resolve_manifest(node, filters=None, exclude=True): if filters: node = filter_manifest(node, filters)...
import torch.optim as optim class Train: def __init__(self, data_sampler, model, criterion): self.data_sampler = data_sampler self.criterion = criterion self.model = model def train(self, iterations, lr): optimizer = optim.Adam(self.model.parameters(), lr) avg_loss = 0...
import psycopg2 import pandas as pd import ast import random import datetime def random_date(): start_date = datetime.date(1950, 1, 1) end_date = datetime.date(2002, 1, 1) time_between_dates = end_date - start_date days_between_dates = time_between_dates.days random_number_of_days = random.randran...
import numpy import pandas from bokeh import models from bokeh.models import HoverTool from bokeh.plotting import figure, show from bokeh import palettes from sqlalchemy.orm import Session from ticclat.flask_app.db import database def corpus_size(): query = """ SELECT SUM(word_count) / 1e8 AS sum_word_count, ...
#!/usr/bin/python3 #above is path to the interpreter which the script will use print("Hello, World!")
#Sort Stack : have all mins at the top class Stack: def __init__(self): self.stack = [] self.size = 0 def push(self , val): self.stack.append(val) self.size += 1 print("Stack contents: " , self.stack) def pop(self):...
n = int(input()) res = 0 arr = [list(map(int, input().split())) for _ in range(n)] for i in range(n): #tmp=input().split() tmp = arr[i] # 정렬을 한다. tmp.sort() a,b,c = map(int, tmp) if a == b and b == c: money = 10000+a*1000 elif a == b or a == c: money = 1000+a*10...
from .anyapi import AnyAPI
#!/usr/bin/env python ''' Make flat ntuple from GEN data tier ''' # # Standard imports and batch mode # import ROOT import os, sys ROOT.gROOT.SetBatch(True) import itertools from math import sqrt, cos, sin, pi, acos import imp #RootTools from RootTools.core.standard import *...
from DataStructures.chapter05.排序.bubblesort import bubble_sort2, bubble_sort from DataStructures.chapter05.排序.selectionsort import selectionsort from DataStructures.chapter05.排序.insectionsort import insertion_sort from DataStructures.chapter05.排序.shellsort import shell_sort from DataStructures.chapter05.排序.归并排序 import ...
ejDBServer = "" ejDBUsername = "" ejDBPassword = "" ejDBDBName = "" ejMailHost = "" ejMailPort = ejMailUser = "" ejMailPassword = "" ejMailSender = "" ejMailReceiver = ""
#!/usr/bin/env python # -*- coding: utf-8 -*- import datetime from typing import Tuple, Union import pendulum def utcnow() -> datetime.datetime: return datetime.datetime.utcnow() def _utctoday(now: datetime.datetime) -> datetime.date: return now.date() def utctoday() -> datetime.date: now = datetime...
#03d: Greedy Motif Search #http://rosalind.info/problems/3d/ #Given: Integers k and t, followed by a collection of strings Dna. k = 3 t = 5 Dna = ['GGCGTTCAGGCA', 'AAGAATCAGTCA', 'CAAGGAGTTCGC', 'CACGTCAATCAC', 'CAATAATATTCG'] #If parsing from file: f = open('rosalind_3d.txt', 'r') contents = f.read().strip().split...
from django.contrib import admin from socials.models import Keyword @admin.register(Keyword) class KeywordModelAdmin(admin.ModelAdmin): list_display = admin.ModelAdmin.list_display + ( 'name', 'created_at', 'updated_at', ) list_filter = admin.ModelAdmin.list_filter + ( '...
import cv2 import numpy as np #/*! 为了绘制一个圆形,我们使用 cv2.circle 函数。我们传递 x,y,半径大小,RGB 颜色,深 */ #/*! 度作为参数*/ img = cv2.imread("image.jpg") print(img.shape) # cv2.circle(img,(x,y),radius,(R,G,B),THICKNESS) # x:距x轴的距离 # y:与y轴的距离 # radius:半径大小(整数) # R,G,B:RGB形式的颜色(255,255,0) # 厚度:矩形的厚度(整数) cv2.circle(img, (200, 130), 90, (255...
from .S2Identified import S2Identified from .terms import SBOL2 from rdflib import URIRef from rdflib.namespace import RDF class S2Attachment(S2Identified): def __init__(self, g, uri): super(S2Attachment, self).__init__(g, uri) @property def source(self): return self.get_uri_property(SB...
from wingedsheep.carcassonne.objects.actions.action import Action from wingedsheep.carcassonne.objects.coordinate import Coordinate from wingedsheep.carcassonne.objects.tile import Tile class TileAction(Action): def __init__(self, tile: Tile, coordinate: Coordinate, tile_rotations: int): self.tile = tile ...
from django.conf.urls import url, include from rest_framework import routers # import pdb;pdb.set_trace() from organization_test_task import views router = routers.DefaultRouter() router.register(r'companies', views.CompanyListViewSet, base_name='company') # Wire up our API using automatic URL routing. # Additionally...
class Solution: def runningSum(self, nums): res = [] for num in nums: if len(res) == 0: res.append(num) else: res.append(res[-1] + num) return res
""" use linked list to accomplish a queue ADT, store both head and tail pointers """ class Empty(Exception): pass class Node: __slots__ = '_element', '_next' def __init__(self, element, next): self._element = element self._next = next class QueueUseLinkedList: """a queue using linked...
import discord from discord.ext import commands from discord.voice_client import VoiceClient startup_extensions = ["Music"] bot = commands.Bot("xD") @bot.event async def on_ready(): print("bot online") print("Name " + bot.user.name) print("ID " + bot.user.id) class Main_Commands(): def __init__(s...
# -*- coding: utf-8 -*- """ Created on Sat Mar 2 10:03:31 2019 @author: saib """ dict1 = {'name':'Saikumar', 'id':1235, 'cell':92992992, 'extn':8768} print(dict1.keys()) print(dict1.values()) # Traverse dictionary using the key values for k in dict1.keys(): print(k, "=>",dict1[k]) print(dict1.items()) # Trave...
import requests import json from itty import * from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from tabledef import * #For SQL database engine = create_engine('sqlite:///brainSparkRequests.db', echo=False) # create a Session Session = sessionmaker(bind=engine) session = Session() ######...
# epochs 100적용 # validation_split, callback 적용 # early_stopping 5 적용 # Reduce LR 3 적용 # modelcheckpoint 폴더에 hdf5 파일 적용 import numpy as np from tensorflow.keras.models import Sequential, Model from tensorflow.keras.layers import Dense, Dropout, Input from tensorflow.keras.datasets import mnist (x_train, y_train), (x_...
"""project URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/3.1/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') Class-based...
# import sqlite3 package import sqlite3 def insert_db(): # sample data classroom_data = [(1, "Raj", "M", 70, 84, 92), (2, "Poonam", "F", 87, 69, 93), (3, "Nik", "M", 65, 83, 90), (4, "Rahul", "F", 83, 76, 89)] # open connection connecti...
from nose.tools import with_setup, ok_, eq_, assert_almost_equal, nottest, assert_not_equal import torch from gtnlplib.constants import * import numpy as np #7.1a def test_model_en_dev_accuracy1(): confusion = scorer.get_confusion(DEV_FILE,'model-dev-en.preds') acc = scorer.accuracy(confusion) ok_(acc > ....
from unittest import TestCase from src.d3_network import ip_provider class TestStaticIpProvider(TestCase): def test_given_host_ip_when_create_static_ip_provider_then_get_host_ip_return_host_ip(self): static_host_ip = '10.42.0.78' scanner = ip_provider.StaticIpProvider(static_host_ip) s...
#!/usr/bin/env python import pigpio from grove import grove_pwm_buzzer,grove_4_digit_display, grove_led, grove_slide_potentiometer from grove.grove_button import GroveButton servo_pin = 18 buzzer_pin = 12 disp = grove_4_digit_display.Grove(16,17, brightness=grove_4_digit_display.BRIGHT_HIGHEST) poti = grove_slide_pot...
from onegov.ballot.models import ElectionCompound from onegov.core.collection import Pagination from sqlalchemy import cast from sqlalchemy import desc from sqlalchemy import distinct from sqlalchemy import extract from sqlalchemy import Integer class ElectionCompoundCollectionPagination(Pagination): def __init_...
# Always prefer setuptools over distutils from setuptools import setup # To use a consistent encoding from codecs import open from os import path # Get the long description from the README file with open( path.join(path.dirname(__file__), "README.md"), encoding="utf-8" ) as f: long_description = f.read() # A...
import pytest import numpy as np from pathlib import Path from spikeinterface import NumpySorting from spikeinterface import download_dataset from spikeinterface import extract_waveforms from spikeinterface.core import get_noise_levels from spikeinterface.extractors import read_mearec from spikeinterface.sortingcompo...
#!/usr/bin/python #ref: http://stackoverflow.com/questions/14508906/sending-messages-between-class-threads-python #http://ja.pymotw.com/2/Queue/ import threading import Queue import time Trigger= False #global variable to communicate btwn the threads QTrigger= Queue.Queue() IsActive= True def Func1(): global IsAct...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models from usermanagement.models import * from patientmanagement.models import * from appointments.models import DoctorSlots from datetime import datetime from appointments.models import * # Create your models here. from django.util...
import common_vars as c_vars from sklearn.model_selection import train_test_split import pandas as pd df = pd.read_csv(c_vars.train_file).as_matrix() # df = pd.read_csv(c_vars.train_sample_file).as_matrix() df_train, df_val = train_test_split(df, test_size = 0.1, random_state = 42, stratify = df[:,-1]) df_train = pd....
from collections import defaultdict def percentage_commission_per_row(row): """ Each row is a list of results from cloud_sql.get_all_data_per_shop(), which represents one order promoted by one inf for one campaign and one shop the row is ordered in: subtotal_price, uid, campaign_id, commission, co...
import pytest from tests import config as conf from tests import experiment as exp @pytest.mark.nightly # type: ignore def test_cifar10_pytorch_accuracy() -> None: config = conf.load_config(conf.official_examples_path("cifar10_cnn_pytorch/const.yaml")) experiment_id = exp.run_basic_test_with_temp_config( ...
"""proxyserver URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.11/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Clas...
''' Analysis script for 1D 2l plots (RootTools) ''' #Standard imports import ROOT from math import sqrt, cos, sin, pi, acos import itertools,os import copy from operator import mul import argparse argParser = argparse.ArgumentParser(description = "Argument parser") argParser.add_argument('--logLevel', acti...
# Librerias Django from django.contrib.auth.models import User from django.db import models from django.urls import reverse from django.utils.translation import ugettext_lazy as _ # Librerias en carpetas locales from .submodels.department import PyDepartment from .submodels.employee import PyEmployee
import tensorflow_hub as hub import numpy as np import tensorflow_text # Some texts of different lengths. english_sentences = ["dog", "Puppies are nice.", "I enjoy taking long walks along the beach with my dog."] italian_sentences = ["cane", "I cuccioli sono carini.", "Mi piace fare lunghe passeggiate lungo la spiaggi...
""" only use + and //, write a recursion, calculate the integer part of log2(n). example: log2(50) => 5 log2(31) => 4 log2(32) => 5 log2(1) => 0 log2(16) => 4 # the input n should be > 0 """ def log2(n): """ return the integer part of the answer. method: count how many times can // 2, t...
def welcome(): print( '+------------------------------------------------+'+ '\nWELCOME TO TIC TAC TOE\n'+ '+------------------------------------------------+\n') def board(p): print( '+-------+-------+-------+\n'+ '| | | |\n'+ '| {} | {} | {} |\n'.format(p[0], p[1], p[...
# Copyright (C) 2016 Nokia Corporation and/or its subsidiary(-ies). """ Collection of helpers to run commands both on local and remote hosts. """ import datetime import os from logging import getLogger import subprocess import select import signal logger = getLogger(__name__) class Host(object): """A Host conta...
import allure import pytest, logging from allure_commons.types import AttachmentType from selenium import webdriver from selenium.webdriver.support.events import EventFiringWebDriver, AbstractEventListener FORMAT = '%(name)s : %(asctime)-15s : %(filename)s : %(levelname)s : %(message)s' logging.basicConfig(level=logg...
from django.conf.urls import include, url from rest_framework.routers import DefaultRouter from TestOnline.company.paper.views import * router = DefaultRouter() router.register(r'company/papers',PaperViewSet) urlpatterns = [ # url(r'^company/createPaper/$',createPaper) url(r"^company/getPapers/$",getPapers),...
# -*- coding: utf-8 -*- """ Created on Thu Sep 20 12:51:34 2018 @author: shams """ import numpy as np import pandas as pd from keras.preprocessing import sequence from keras.models import load_model from keras.layers import Dense, Input, LSTM from keras.models import Model import h5py user_file = pd.read_json('C:/Us...
import re import sys import numpy as np def readPFM(file): with open(file, 'rb') as f: header = f.readline().decode('utf-8') if 'PF' in header: color = True elif 'Pf' in header: color = False else: raise Exception('Not a PFM file.') ...
# -*- coding:utf-8 -*- from robot.models import Edu_School_Class, Edu_School_Class_User, Edu_School_Notice, EduWxRobotChatRoomData, \ EduWxRobotChatFriendData, EduWxRobotFriend, EduWxRobotChatRoom, EduWxRobotChatRoomMember, EduWxRobot, \ EduWxRobotChatRoomFiles, EduWxRobot from robot.dao import dao_common as ...
""" code test using 5.1 """ import sys data = [] for k in range(26): a = len(data) b = sys.getsizeof(data) print("Length: {0:3d}; Size in bytes: {1:4d}".format(a, b)) data.append(None) """ Length: 0; Size in bytes: 56 Length: 1; Size in bytes: 88 Length: 2; Size in bytes: 88 Length: 3; ...
""" Time/Space Complexity = O(N) """ #TLE class Solution: def rob(self, nums: List[int]) -> int: def rob(indx = 0, start = 0): if indx >= len(nums): return 0 if start == 0 and indx == len(nums) - 1: return 0 ...
#!/usr/bin/env python # encoding: utf-8 """ random_permutation.py Created by Jakub Konka on 2011-05-15. Copyright (c) 2011 University of Strathclyde. All rights reserved. """ from __future__ import division import sys import os import numpy as np import math from itertools import permutations def generate(n): # 1. ...
import sys import os import weakref import SocketServer from SimpleXMLRPCServer import SimpleXMLRPCServer from SimpleXMLRPCServer import SimpleXMLRPCRequestHandler sys.path.append(os.path.realpath('.')) sys.path.append(os.path.realpath('../')) from application.helpers.instrumentsmanager.instrumentmgr import Instrume...
class Compartment: """ A tuberculosis model compartment. """ SUSCEPTIBLE = "susceptible" EARLY_LATENT = "early_latent" LATE_LATENT = "late_latent" INFECTIOUS = "infectious" ON_TREATMENT = "on_treatment" RECOVERED = "recovered" BASE_COMPARTMENTS = [ Compartment.SUSCEPTIBLE, ...
import string class Solution: def __init__(self): self.keylist = {} self.res = [] self.find = False self.end = None self.can_trans_map = {} def can_trans(self, left, wordList): # if f"{left}_{right}" in self.can_trans_map: # return self.can_trans_ma...
""" base codec class with helpers for Sixteen Fourteen Hex Encoding """ class BaseBitCodec(object): @staticmethod def mask(num, masker): """ preserves only the bits of num that are set by the masker :param num: integer to be masked :param masker: integer whose bits indicate ...
#!/usr/bin/env python3 '''Reads emails generated by the filter script and submits patches/make comments''' import os import re import time import datetime from collections import namedtuple import git import gitlab import cfg import db_helper import mail_helper # Do some initialization early so we can abort in case ...
# __author__ = 'cjweffort' # -*- coding: utf-8 -*- from numpy import * """ 4 Fancy indexing and index tricks """ """ 4.1 Indexing with Arrays of Indices """ #对1维数组进行index选取 a = arange(12) ** 2 i = array([1, 1, 3, 8, 5]) print a[i] j = array([[3, 4], [9, 7]]) print a[j] #对2维数组进行index(一个维度)选取 palette = array([[0, 0, ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # ============================================================================= # Created By : Krikor Herlopian # Created Date: Wed May 12 2021 # Email Address: kherl1@unh.newhaven.edu # ============================================================================= sente...
import urllib2 as ur import re link = "http://www.pythonchallenge.com/pc/def/linkedlist.php?nothing=" data = "44827" while True: try: data = "".join(re.findall('\d+',ur.urlopen(link+data).read())) except: print data
# -*- coding:UTF-8 -*- from rest_framework.viewsets import GenericViewSet from rest_framework import mixins class CreateOnlyViewSet(mixins.CreateModelMixin, GenericViewSet): """ A viewset that provides default `create()` actions. """ pass class CreateListDeleteViewSet(mixins.CreateModelMixin, ...
import os import os.path import re import subprocess import datetime import sys import glob import math import logging import numpy as np import pyproj logger=logging.getLogger("pyfarms.util") def gitinfo(): try: git_ret=subprocess.Popen(['git','log','--pretty=%H','HEAD^..HEAD'], stdout=subpr...
# Generated by Django 2.2.1 on 2019-07-27 15:57 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('faculty', '0023_auto_201...
import random number = random.randint(1,10) tries=1 uname=input("Hello, What is ur user name?") print("Hello",uname+".",) question=input("Would you like to play a game(Y/N)?") if question == 'N' or question == 'n': print("Ok.. Bye") if question == 'Y' or question == 'y': guess=int(input("Can You guess...
import django import sys, os import pandas as pd #import matplotlib.pyplot as plt sys.path.append('/home/galm/software/django/tmv/BasicBrowser/') os.environ.setdefault("DJANGO_SETTINGS_MODULE", "BasicBrowser.settings") django.setup() from scoping.models import * q = Query.objects.get(pk=3771) docs = q.doc_set.all()...
from __future__ import print_function from googleapiclient.discovery import build from httplib2 import Http from oauth2client import file, client, tools import os SCOPES = 'https://mail.google.com/' DIR_ = "app/controllers/email/" def auth(token_): """ Authenticates user from a token.json file enabling get request...
from ftplib import FTP import pygame,os, datetime, time, fileinput import pygame.camera from pygame.locals import * print 'Starting DAQ' #---------------------------Loop for Repeat-------------------------------- while True: print 'Grabing Data' #-----------------------Set Desktop Path-------------------------...
from flask_wtf import FlaskForm from wtforms import TextAreaField from wtforms.validators import DataRequired, ValidationError from app.models import Comment from datetime import datetime def date_exists(form, field): date = Appointment.query.filter(Appointment.date == date).first() if date: raise Val...
from tkinter import * def doNothing(): print("Fine then...") root = Tk() # **** MAIN MENU **** # Add a menu menu = Menu(root) root.config(menu=menu) # Create sub menus and append them to the main menu. subMenu = Menu(menu) sub2Menu = Menu(menu) menu.add_cascade(label="Example", menu=subMenu) menu.add_casca...
import pytorch_lightning as pl import numpy as np import torch import torch.nn as nn import torch.functional as F import util from argparse import ArgumentParser #from dataset import get_dataloader from models import AutoEncoder class AutoencoderModel(pl.LightningModule): def __init__(self, hparams): supe...
import pandas as pd import matplotlib.pyplot as plt import numpy as np from scipy.optimize import curve_fit import os numSubsets = 10 def compute_d_N(df): lastRow = df.tail(1)['i'] lastRow = str(lastRow).split(" ") totalNumWords = int(lastRow[4]) #print(lastRow) #print(totalNumWords) df = df...
from selenium import webdriver from selenium.common.exceptions import NoSuchElementException from datetime import datetime category = ["소통", "팀워크", "도전", "능동", "성실", "정직", "인내심", "창의", "글로벌역량", "주인의식"]#10개 keyword = ["소통", "대화", "교류", "팀워크", "협력", "협동", "도전", "모험", "용기", "능동", "열정", "적...
class Solution(object): def twoSum(self, nums, target): num_dict = {} for i, x in enumerate(nums): if target - x in num_dict: return (num_dict[target - x], i) num_dict[x] = i if __name__ == '__main__': print "index1=%d, index2=%d" % Solution().twoSum((3, ...
from django.db import models from rest_framework import serializers # Create your models here. class OnlineUser(models.Model): #owner = models.ForeignKey(KxUser, to_field='email', db_column='ower_email') mac = models.CharField(max_length=100, primary_key=True) email = models.CharField(max_length=50) #...
#Programa: act8.py #Propósito: introducir nota edad y sexo y mostrar si esta aceptada o no #Autor: Jose Manuel Serrano Palomo. #Fecha: 17/10/2019 # #Variables a usar: # nota, edad y sexo son los datos a introducir por el usuario # #Algoritmo: # LEER nota, edad y sexo # si nota mayor o igual 5 y edad mayor o igual a 18 ...
from onegov.org.utils import annotate_html, remove_empty_paragraphs from onegov.form.fields import HtmlField as HtmlFieldBase class HtmlField(HtmlFieldBase): """A textfield with html with integrated sanitation and annotation, cleaning the html and adding extra information including setting the image size ...
from Actor import Actor # # A Tree object # Spawns fruit to eat # class Fruit(Actor): # Init def __init__(self, tree): Actor.__init__(self, "An apple", 0x147514) self.ignoreBlocking = True self.lifetime = 0 self.tree = tree self.edible = True self.hungerValue = 10 self.canPass = True # # Tick # ...
import json import os import praw import requests from list_of_subreddits import SUBREDDITS def set_environment_variables(): with open('config.json','rb') as f: environment_variables = json.loads(f.read()) for key,value in environment_variables.iteritems(): os.environ[key]=str(value) def handle(): set_e...
all_sqrt = [] max_num = 9 b = 1 for a, b in [[1, 2], [1,1]]: if a == b: print(a, ' ', b)
# Association Rules # Recommending books with support # Compute support for Hunger and Potter supportHP = np.logical_and(books['Hunger'], books['Potter']).mean() # Compute support for Hunger and Twilight supportHT = np.logical_and(books['Hunger'], books['Twilight']).mean() # Compute support for Potter and Twilight su...
#!/usr/bin/python import sys, re for line in sys.stdin.readlines(): line = re.sub("[0-4]", "<", line) line = re.sub("[6-9]", ">", line) print line
# Mad Libs # 확장 버전 noun = input("Enter a noun: ") verb = input("Enter a verb: ") adjective = input("Enter an adjective: ") adverb1 = input("Enter an adverb: ") adverb2 = input("Enter another adverb: ") print("Do you {0} your {1} {2} {3}? That's {4}!".format(verb, adjective, noun, adverb1, adverb2))