text
stringlengths
38
1.54M
import pandas as pd df = pd.read_csv('train/images.csv') num_classes = len(pd.unique(df['label'])) numbers_to_classes = {} classes_to_numbers = {} for n, plankton_cat in enumerate(df['label'].unique()): numbers_to_classes[n] = plankton_cat classes_to_numbers[plankton_cat] = n list = ['image'] for n, values in e...
import sqlite3 from datetime import date def conectar_banco(nome_bd): return sqlite3.connect(nome_bd) def criar_cursor(conexao): return conexao.cursor() def criar_tabela_computador(cursor): comando = \ 'CREATE TABLE IF NOT EXISTS' \ ' computador (' \ ' codigo INTEGER PR...
from matplotlib import pyplot as plt from sklearn.metrics import precision_recall_curve, roc_curve def evaluating_models( y_test, y_predicted, name): ######################################################################################################################## # ####### ...
# # Copyright 2017-2019 B-Open Solutions srl. # Copyright 2017-2019 European Centre for Medium-Range Weather Forecasts (ECMWF). # # 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://ww...
import sys sys.path.insert(1, 'D:\Sync\Advanced Database Topics\FinalProject\Max Repo\ADTFinalProject\src\MongoDBAtlasAPI') import pandas as pd import datetime import time from MongoDBAtlasAPIAuthentication import MongoDBAtlasAPIAuthentication if __name__ == "__main__": mdbaa = MongoDBAtlasAPIAuthentication() ...
# This Task is the base task that we will be executing as a second step (see task_piping.py) # In order to make sure this experiment is registered in the platform, you must execute it once. from clearml import Task # Initialize the task pipe's first task used to start the task pipe task = Task.init('examples', 'Toy B...
import json from typing import Iterable from confluent_kafka.cimpl import Producer from pk_kafka.consumers.exceptions import MessageValueException class KafkaProducer: """ Start a new Producer to publish message to topic """ def __init__(self, broker_address, handle_json_message_data=True): ...
#coding: utf-8 from os import remove as rm from os.path import basename, dirname, join as path_join, realpath, isdir from sh import unzip import tempfile from osext.filesystem import rmdir_force, sync as dir_sync import httpext as http import os import langutil.php as php class WordPressError(Exception): pass ...
# External module imports import RPi.GPIO as GPIO import time import led_control as ledc from play_song import play_song """ Pin list: GND - black wire) - 6 LED Control - green - GPIO18 - 12 Computer - purple - GPIO17 - 11 Motor 1 - yellow - GPIO23 - 16 Motor 2 - orange - GPIO24 - 18 Power Str...
import pandas # load all necessary libraries import pylab as pl from sklearn.cluster import KMeans from sklearn.decomposition import PCA # loading data variables = pandas.read_csv(r'C:\Users\bsidd\Downloads\Python_Lesson6\Python_Lesson6\sample_stocks.csv') #load returns, dividendyield to x,y Y = variables[['returns']] ...
from django.conf.urls import patterns, url from .views import FsAuth, FsCallback urlpatterns = patterns('', # Receive OAuth token from 4sq. url(r'^callback$', FsCallback.as_view(), name='oauth_return'), # Authenticate with 4sq using OAuth. url(r'^auth$', FsAuth.as_view(), name='oauth_auth'), )
class Solution: def minAbsoluteSumDiff(self, nums1: List[int], nums2: List[int]) -> int: modulo = 10**9 + 7 abs_diff = [abs(nums1[i] - nums2[i]) for i in range(len(nums1))] ans = sum(abs_diff) #if len(set(abs_diff)) == 1: if ans == 0: # i.e. all diff are 0 ...
#!/usr/bin/env python import rospy from std_msgs.msg import Float32 from geometry_msgs.msg import TwistWithCovarianceStamped from PID import Controller def main(): rospy.init_node('blimp_controller', anonymous=True) rate = rospy.Rate(10) # 10hz controller = Controller() while not rospy.is_shutdown(): ...
class Module: """ ネットワークの構造に入るも """ def __init__(self): pass def build(self, inputs_shape): return inputs_shape def forward(self, inputs): return inputs def backward(self, delta): return delta class Layer(Module): """ 重みの更新が必要なもの """ d...
json_file = "manage.json" guild_id = 582705077572075535 schedule_channel_id = 598833688402198528 #カリンさんを動かすのに必要 zatsudan_channel_id = 582956584624324618 minerva_id = 634687198842716160 clan_dicts = [{"role_id":582952905653485568, "command_channel":607602971512930345, "remain_totsu_channel":63691388...
import os import numpy as np import h5py import argparse import time import logging import keras import keras.backend as K from sklearn import metrics from keras.models import Model from keras.optimizers import Adam from keras.layers import Input, Dense, BatchNormalization, Dropout, Lambda, Activation, Concatenate #fr...
from abc import abstractproperty from vmanage.entity import HelperModel,Model,ModelFactory from vmanage.policy.model import Definition,CommonDefinition,SequencedDefinition from vmanage.policy.model import Policy,GUIPolicy,CLIPolicy from vmanage.policy.model import DefinitionApplication,SequencedDefinition from vmanag...
# -*- coding: Cp1250 -*- from data import locations from data.turnus_type import TurnusType from data.general import DataContainer import os import sys import csv def input_turnus_types(): FILES_DIR = os.path.join('persistence', 'data', 'start_data') FILE_NAME = 'vrste_turnusov.csv' ...
import torch from torch.utils.data import Dataset import os import numpy as np import cv2 import matplotlib.pyplot as plt class KneeMRI(Dataset): def __init__(self, target_dir, noise_dirs): self.target_dir = target_dir self.noise_dirs = noise_dirs self.target_files = [] self.noise...
from django.contrib import admin admin.site.site_header = 'BYTEME Admin' admin.site.site_title = 'BYTEME Admin'
# Restart 28. 특정 문자열로 끝나는 가장 긴 부분 문자열 찾기 ''' Not solve this problem by myself. So see this again ''' def solution(myString, pat): answer = myString[:len(myString) - myString[::-1].index(pat[::-1])] # print(myString[:len(myString)]) # print(myString[::-1]) # print(myString[::-1].index(pat[::-1])) # ...
from bs4 import BeautifulSoup from urllib.request import urlopen import re pages = set() def get_links(page_url): global pages html = urlopen('http://en.wikipedia.org' + page_url) bs_obj = BeautifulSoup(html.read(), 'html.parser') try: print(bs_obj.h1.get_text()) print(bs_obj.find(id...
#! /usr/bin/env python # -*- coding: utf-8 -*- """ Module that contains consts definitions used by libraries """ from __future__ import print_function, division, absolute_import from Qt.QtCore import Signal, QObject from Qt.QtGui import QColor # class LibraryItemSignals(QObject, object): # """ # Class that...
#!/usr/bin/env python3 """ Run an adversarial attack """ import os import json import scipy import joblib import argparse import numpy as np from os.path import join from keras import backend as K from inception_v3 import InceptionV3 from keras.preprocessing import image from keras.utils.data_utils import get_file fr...
from itertools import combinations import sys def get_score(arr, team): score = 0 for a, b in combinations(team, 2): score += arr[a][b] + arr[b][a] return score n = int(sys.stdin.readline().strip()) arr = [list(map(int, sys.stdin.readline().strip().split())) for _ in range(n)] best_score = float(...
from __future__ import print_function from neural_network import NeuralNetwork from nn_img2num import NnImg2Num from my_img2num import MyImg2Num import numpy import random import torch import torchvision from torch.autograd import Variable def test(): #prepare sample input for forwad() train_loader = torchvision.da...
"""Store the data in a SQLite database. Usage: $ python make_db.py # Drop DB and verbose output $ python make_db.py -d -v """ import os import time import logging import argparse import pandas as pd import sqlalchemy as sa from argparse import RawDescriptionHelpFormatter logger = logging.getLogger(__nam...
# -*- coding: utf-8 -*- from binance.client import Client from binance.enums import * from binance.websockets import BinanceSocketManager import time from datetime import datetime import prettytable as pt from settings import MarginAccount from settings import BinanceKey1 api_key = BinanceKey1['api_key'] api_secret ...
import random def ia(boxes): if (random.randint(0, 1)): return ('G') else: return ('D')
from bs4 import BeautifulSoup import requests from win32com.client import Dispatch import win32com.client as wincl import datetime import time # def speak(text): # male voice # speak = Dispatch("SAPI.SpVoice") # speak.Speak(text) def speak(text): # female voice speaker_number ...
from bs4 import BeautifulSoup import requests import re response = requests.get('https://en.wikipedia.org/wiki/Neighborhoods_in_New_York_City') soup = BeautifulSoup(response.text, 'html.parser') table = soup.table.find_all('td') count = 4 n = [] while count < len(table): content = str(table[count]) content = c...
# -*- coding: utf-8 -*- """ ------------------------------------------------- File Name: testKafka Description : Author : ZWZ date: 18-6-15 ------------------------------------------------- Change Activity: 18-6-15: ------------------------------------------------- "...
# -*- coding: utf-8 -*- """ Spyder Editor This is a temporary script file. """ import numpy as np mat1=np.zeros((4,4),dtype=int) print(mat1) #Negate all values which are more than 5 in a row arr1=np.arange(11) arr1[arr1>5]=-arr1[arr1>5] arr1[6:]=-arr1[6:] mat1 = np.array([['abc','A'],['def','B'],['ghi','C'],...
business_names = [ "burger king", "McDonald's", "super duper burger's", "subway", "pizza hut","pizza fateh"] searchTerm = "duper bur" res = [] for i in business_names: split_name = i.split() searchtermsplit = searchTerm.split() count = 0 for words in split_name: for search1 in searchte...
# -*- coding: utf-8 -*- # Generated by Django 1.11.1 on 2018-03-18 23:21 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('terrainapp', '0006_auto_20180318_1413'), ] ...
import sys from io import BytesIO import urllib.request from bs4 import BeautifulSoup import telegram from flask import Flask, request, send_file from time import sleep; from fsm import TocMachine #API_TOKEN = '488582332:AAE7swIh7w7ZM0sRUstZqubH5LKvHjz0Is0' API_TOKEN='510481981:AAEZsN2FIDJLE7DCaM69BWDuzxguM5A-h_Q' la...
__author__ = 'apavlenko' import random from model.contact import Contact def test_modify_contact_db(app, db, check_ui): old_contacts = db.get_contact_list() if len(old_contacts) == 0: app.contact.add_new_wo_group(Contact(firstname=app.firstname, middlename=app.middlename, lastname=app.lastname)) ...
#!/usr/bin/env python3 ######################################################## ### Grading Script for CSE 231 ### ### Built by Cody Littley ### ### First used January 2014 ### ######################################################## import sys...
class Solution(object): def wiggleMaxLength(self, nums): """ :type nums: List[int] :rtype: int """ if len(nums) <= 1: return len(nums) i = 1 while i < len(nums) and nums[i] == nums[i - 1]: i += 1 if i == len(nums): r...
from encoder.params_model import model_embedding_size as speaker_embedding_size from utils.argutils import print_args from utils.modelutils import check_model_paths from synthesizer.inference import Synthesizer from encoder import inference as encoder from vocoder import inference as vocoder from pathlib import Path fr...
import reversion from django.conf import settings from django.contrib.gis.db import models from django.contrib.postgres.fields import JSONField from django.core import validators from django.core.exceptions import ValidationError from django.utils.functional import cached_property from base.fields import AutoUUIDField...
# Generated by Django 3.1.2 on 2020-10-08 12:46 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('webgui', '0002_auto_20201008_1150'), ] operations = [ migrations.AddField( model_name='booking', name='token', ...
# cook your dish here # from math import * #for _ in range(int(input().strip())): x,y,z=map(int,input().split()) print((x-z)//(y+z))
#Steven Brown #Assignment_3 # 25 FEB 2016 from __future__ import print_function import unittest import sys trace = False '''A dictionary class implemented by hasing and chaing. The set is represented internally by as list of lists. The outer list is initialized to all None's. When multiple values hash to...
from x1scr.apps.news.models import News from django import template register = template.Library() @register.inclusion_tag('news.html') def pull_latest_news(howmany=3): news = News.objects.filter(published=True).order_by('-date_published')[:howmany] return dict(news=news)
# Copyright (C) 2019-2025 by # ATTA Amanvon Ferdinand <amanvon238@gmail.com> # All rights reserved. # BSD license. # # Author: ATTA Amanvon Ferdinand (amanvon238@gmail.com) """ Ce module recoit les paramètres utiles aux cycles de simulation . Ces paramètres lui servent à créer la topologie à utiliser ...
import asyncio import logging import struct import sys from aiohttp import web from .run_exec import run_exec FMT_ID = b'\x01T91\x1d' HEADER_STRUCT = '>5s2B2I' MAX_LEN = 128 * 1024 logger = logging.getLogger('t9_exec_server') logger.setLevel(logging.DEBUG) handler = logging.StreamHandler() handler.setLevel(logging.D...
import time print("Welcome User \nCreated by:- Simarjot Singh") def myAlarm(): try: myTime = list(map(int, input("Enter in hh mm ss format: ").split())) if len(myTime) == 3: total = myTime[0]*3600 + myTime[1]*60 + myTime[2] time.sleep(total) for i in range(10): print('\a') ...
import boto3 import re from datetime import datetime,timedelta from botocore.exceptions import ClientError import boto3.session def check_volume(volume_id): if not volume_id: return '' try: volume=client.describe_volumes(VolumeIds=[volume_id]) if not volume['Volumes'][0]['VolumeId']: ...
""" Module to work with raw voltage traces. Spike sorting pre-processing functions. """ from pathlib import Path import numpy as np import scipy.signal import scipy.stats import pandas as pd from joblib import Parallel, delayed, cpu_count from iblutil.numerical import rcoeff import spikeglx import neuropixel import ...
#python3 import sys def money_change_greedy_util(money, coins): count = 0 for coin in coins: if(money <= 0): break if(money >= coin): count += money // coin money = money % coin return count def money_change_greedy(money): return money_change_greedy...
import unittest from tdasm import Runtime from sdl import Shader, StructArg, IntArg, Ray, Vector3 from renlgt.sphere import Sphere from renlgt.hitpoint import HitPoint from renlgt.shp_mgr import ShapeManager from renlgt.linear import LinearIsect class LinearIsectTests(unittest.TestCase): def test_linear(self): ...
from django.db import models from django.contrib.auth.models import AbstractUser # Create your models here. class Author(models.Model): name = models.CharField(max_length=20) email = models.EmailField() description = models.TextField() def __str__(self): return self.name class Tag(models.Mo...
from django.contrib import admin from login.models import UserProfile @admin.register(UserProfile) class UserProfileAdmin(admin.ModelAdmin): list_display = ("pk", "user") list_display_links = ("pk", "user") search_fields = ("user__username",) readonly_fields = ("user",)
import webbrowser class Movie(): """File - media.py class Movie This file used to create the movie blueprint. There are 5 constructors for the movie object.These are: title, poster_image_url, trailer_youtube_url, rating and movie storyline. File - entertainment_center.py In this file object...
import os import asyncio # noqa: F401 import discord import logging from discord.ext import commands from cogs.utils.dataIO import dataIO from cogs.utils import checks import json import random class Quote: """Simple quote cog""" __author__ = "pitikay" __version__ = "0.1" def __init__(self, bot): ...
import os import re import subprocess from Queue import Queue, Empty from threading import Thread import uuid import os import shutil import sys from celery import Celery from celery.contrib import rdb from ovirt_imageio_common import directio from kombu import Queue as kqueue import json import random import logging...
# str1 = input() str1='abcdefghijklmnopqrstuvwxyz' print(str1[2]) # третий символ этой строки; print(str1[-2]) # предпоследний символ этой строки; print(str1[:5]) # первые пять символов этой строки; print(str1[:-2]) # всю строку, кроме последних двух символов; print(str1[::2]) # все символы с четными индексами; pr...
from .firefly_task import Model from .firefly_task import dynamics #from .env_utils import pos_init from .env_utils import * #from .env_variables import * """ # these are for gym from .gym_input import true_params from gym.envs.registration import register register( id ='FireflyTorch-v0', #entry_point ='Firef...
#!/usr/bin/env python # coding: utf-8 from tests.common import TestCase from tests.common import BASEDIR from clocwalk.libs.detector.cvecpe import cpe_compare_version class CPETestCase(TestCase): def setUp(self): pass def test_compare(self): self.assertTrue(cpe_compare_version(rule_version...
# Description: Calculate yearly averages from monthly files. # # Author: André Palóczy # E-mail: paloczy@gmail.com # Date: January/2018 import numpy as np import matplotlib from glob import glob from os import system from datetime import datetime from netCDF4 import Dataset, num2date from pandas impor...
from odoo import models, fields, api # 借出人表,一对多,一个人可借出多个资产 class User(models.Model): _name = 'assets.manager' _description = '资产借出人' name = fields.Char('资产借出人', required=True) card_number = fields.Char('联系电话') email = fields.Char('电子邮箱') desc_detail = fields.Text('备注') # 使用人备注 # user_ids ...
# 撰寫一程式,檔案名稱 ttt_check_position.py # 定義棋盤格狀態變數 cell_1 ~ cell_9 如下, # 提示使用者輸入棋子位置(整數 0-9 ),保存在變數 position, # 檢查該棋盤格位置是否可以落子(可以放棋子在上面), # 如果不行,顯示 '錯誤,此位置已經有棋子了,結束程式',並退出程式 # 棋盤格變數:保存棋盤狀態的變數 # 變數編號對應的棋盤位置如下 # 1 | 2 | 3 # ---+---+--- # 4 | 5 | 6 # ---+---+--- # 7 | 8 | 9 cell_1 = ' ' cell_2 = ' ' cell_3 = 'o' cell_4...
from flask_classful import FlaskView, route from applicatioin import db from flask import render_template, request from flask import redirect, url_for from applicatioin.forms.forms import InputForm from fuzzywuzzy import fuzz import re from applicatioin.Builders.ModelBuilder import * class InputView(FlaskView): def c...
def FirstNotRepeatingChar(s): # write code here map = {} for i in range(len(s)): map[s[i]] = map.get(s[i], 0) + 1 for i in range(len(s)): if map[s[i]] == 1: return i return -1 print(FirstNotRepeatingChar('abac')) # ½â·¨¶þ # -*- coding:utf-8 -*- class Solution: def F...
import numpy as np from typing import Dict from sklearn.mixture import GaussianMixture from alibi_detect.od.sklearn.base import SklearnOutlierDetector class GMMSklearn(SklearnOutlierDetector): def __init__( self, n_components: int, ): """sklearn backend for the Gaussian Mixture Model ...
########################################################################## # # Copyright (c) 2022, Cinesite VFX Ltd. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions ...
API_VERSION = '1.6' USER_AGENT = 'cmtt-python-wrapper' CALLS_LIMIT = 3 LOG_FORMAT = '%(asctime)s - %(name)s - %(levelname)s - [%(filename)s:%(lineno)d] - %(message)s'
# Standard Library Imports import urllib2 import re # Core Django Imports from django.core.management.base import BaseCommand from django.template.defaultfilters import slugify from django.utils.encoding import smart_str # Third Party App Imports import bs4 # This App Imports from main.models import CIAWFBFieldInfo,...
#Creating a racing turtle game using loops and drawing a race track from turtle import * from random import randint speed(10) penup() goto(-140,140) for step in range(25): write(step, align='center') right(90) forward(10) pendown() forward(150) penup() backward(160) left(90) forward(20) #ada ada = T...
from aiorequest import Credentials from tests.markers import asyncio, unit pytestmark = [unit, asyncio] async def test_username(credentials: Credentials) -> None: assert await credentials.username == "superuser" async def test_password(credentials: Credentials) -> None: assert await credentials.password ==...
#!/bin/python3 import sys S = input() try: x = int(S) except ValueError: print("Bad String") else: print(x)
from django.db import models # Create your models here. class NewsInfo(models.Model): Title = models.CharField(max_length=100) Url = models.CharField(max_length=100) Author = models.CharField(max_length=20) Time = models.CharField(max_length=50) Reading = models.CharField(max_length=20) Comm...
# import the necessary packages from enum import Enum import numpy as np import imutils import cv2 import time from Agent import Agent, AgentType from KinematicsAgent import * from Entities import Color, Block, Polygon class SensorAgent(Agent): def __init__(self, agentType): Agent.__init__(self, agentTy...
#!/usr/bin/env python # coding: utf-8 from setuptools import setup, find_packages from io import open d = 'Integrates peewee and bottle to produce JSON API compatible web services.' version = '0.0.1' setup( name='corkscrew', version=version, description=d, long_description=open('README.rst', 'r', enc...
import asyncio import json import threading import websockets import secrets import time from .RainbowSocksClient import RainbowSocksClient from .RainbowSocksServer import RainbowSocksServer #loop = asyncio.get_event_loop() #loop.run_until_complete(run_test(loop))
#!/usr/bin/python # -*- coding: utf-8 -*- ''' 2.13 字符串连接及合并 Created on 2016年7月29日 @author: wang ''' parts = {'IS', 'Chicago', 'Not', 'Chicago?'} print ' '.join(parts) print ','.join(parts) print ''.join(parts) a = 'Is Chicago' b = 'Not Chicago?' print a + ' ' + b print('{} {}'.format(a,b)) print...
from datetime import datetime as dt from dateutil.relativedelta import relativedelta import numpy as np import pandas as pd FOLDS = [ { "train": [ ("2005-01-01", "2015-12-31"), ("2018-01-01", "2020-06-30"), ], "test": [ ("2020-06-01", "2020-12-31"), ] }, { "trai...
import os all_file = [] def get_all_files(path): all_file_list = os.listdir(path) for file in all_file_list: file_path = os.path.join(path, file) if os.path.isdir(file_path): get_all_files(file_path) all_file.append(file_path) return all_file #使用walk()函数 def getallfiles(path): for dirpath, dirname, ...
import numpy as np import matplotlib.pyplot as plt # autor: backup_python.dev theta = np.linspace(0,2*np.pi) r = 5 + 50*theta plt.style.use('Solarize_Light2') plt.figure(figsize=(10, 6), dpi=90) #theta = np.linspace(0,2*np.pi,1000) #r = 4**2*np.sin(2*theta) plt.subplot(111, projection="polar") p...
# my solution def reverse(self, x: int) -> int: stri = "" negative = False if x < 0: negative = True stri = str(x)[1:] else: stri = str(x) new = "" for i in stri: new = i + new if int(new) > pow(2, 31) - 1: return 0 i...
from django.db import models # Create your models here. class User(models.Model): user_name = models.CharField(max_length=20) user_email = models.EmailField(max_length=50) user_phone = models.IntegerField() def __str__(self): return self.user_name
import moviepy.editor as mpy from tensorflow.python.keras import activations from tensorflow.python.keras import backend as K import tensorflow as tf import cv2 from matplotlib import cm try: from vis.utils import utils except: raise Exception("Please install keras-vis: pip install git+https://github.com/autoro...
import bisect from collections import Counter def binary_in(arr, el, start): pos = bisect.bisect_left(arr, el, start) return pos < len(arr) and arr[pos] == el class Solution(object): def threeSum(self, nums): """ :type nums: List[int] :rtype: List[List[int]] """ n...
from rest_framework.routers import DefaultRouter from . import viewsets router = DefaultRouter() router.register( r"topics", viewsets.TopicViewSet, basename="topics" ) router.register( r"evaluations", viewsets.EvaluationViewSet, basename="evaluations" ) router.register( r"solutions", v...
# level 2 solving strategies # functions here: # from level2 import Naked_Multiple,Hidden_Multiple,Lines_2,NT,NT_chains,Y_Wing, def Naked_Multiple(unit): found = False for mult in range(3,8): done = [] for cell in range(len(unit)): if type(unit[cell]) == str: if len...
#using memoization n = int(input()) dp = [0,1,2,4,7] if n < 5: print(dp[n]) print('the program ended') for i in (5,n): dp.append(dp[i-3]+dp[i-2]+dp[i-1]) print(dp[-1])
import sys cardTypes = {"T": 0, "C": 0, "G": 0} for i in sys.stdin: cardsInput = i.strip("\n") result = 0 for card in cardsInput: cardTypes[card] += 1 for card in cardTypes: totalCardsType = cardTypes[card] result += totalCardsType*totalCardsType zeroLess = False while ...
from collections import defaultdict, deque rr = lambda: input() rri = lambda: int(input()) rrm = lambda: list(map(int, input().split())) INF=float('inf') def solve(N,K,B): groups = defaultdict(list) # alice, bob, both books for time,alike,blike in B: if alike and blike: groups['c'].append(time) elif alike: ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Jan 24 23:21:25 2019 @author: trosales """ from sklearn.model_selection import train_test_split from sklearn.neighbors import KNeighborsClassifier from sklearn.neighbors import KNeighborsRegressor import pandas as pd #import matplotlib.pyplot as plt ...
import tensorflow as tf from tensorflow.keras.layers import Dense, Input, Conv1D, LSTM, Reshape, Flatten, GRU,SimpleRNN import tensorflow.keras.backend as K from tensorflow.keras import Model from tensorflow.keras.optimizers import Adam import numpy as np tf.set_random_seed(2212) class Actor: def __init__(self, s...
def solution(n, money): dp = [0] * (n + 1) for m in money: if m > n: continue for i in range(m, n + 1): if i == m: dp[i] += 1 else: dp[i] += dp[i - m] return dp[n]
#!/usr/bin/env python import os import json import sys from elasticsearch import Elasticsearch es = Elasticsearch() if not (len(sys.argv) == 2): print "USAGE:", sys.argv[0], "<path to dir with .json files>" sys.exit(1) for base, subdirs, files in os.walk(sys.argv[1]): for name in files: if name....
# -*- coding: utf-8 -*- """ Created on Sat Jan 4 11:53:10 2020 TF-functions copied from https://github.com/Hvass-Labs/TensorFlow-Tutorials/blob/master/14_DeepDream.ipynb """ import PIL as PIL import numpy as np import tensorflow as tf import utils as utils import tensorflow.compat.v1 as tfc import math im...
# -*- coding: utf-8 -*- import scrapy import redis from scrapy_splash import SplashRequest from standalone.items import StandaloneItem from scrapy.spiders import CrawlSpider from urllib.parse import urlparse from scrapy.linkextractors.lxmlhtml import LxmlLinkExtractor import re hostip='127.0.0.1' job_redis = redis.Red...
menu = { 'Appetizers': ['Wings', 'Cookies', 'Spring Rolls'], 'Entrees': ['Salmon', 'Steak', 'Meat Tornado', 'A Literal Garden'], 'Desserts': ['Ice Cream', 'Cake', 'Pie'], 'Drinks': ['Coffee', 'Tea', 'Unicorn Tears'], } def print_welcome(): print('*' * 38 + '\n' + '*' * 2 + ' ' * 4 + 'Welcome to the Snakes Ca...
import FWCore.ParameterSet.Config as cms process = cms.Process("PROD2") process.Tracer = cms.Service('Tracer', dumpContextForLabels = cms.untracked.vstring('intProducer'), dumpNonModuleContext = cms.untracked.bool(True) ) process.MessageLogger = cms.Service("...
# -*- coding: utf-8 -*- # Define your item pipelines here # # Don't forget to add your pipeline to the ITEM_PIPELINES setting # See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html from scrapy.spiders import Spider import re from scrapy import Request from scrapy.pipelines.images import ImagesPipeline from ...
n = int(input('Podaj liczbę od 1 do 10: ')) for i in range(1, 11, ): print(n, 'x', i, '=', n * i)
# Generated by Django 2.0.5 on 2018-05-21 20:51 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('room', '0001_initial'), ] operations = [ migrations.AddField( model_name='tile', name='desc', field=mode...