text
stringlengths
38
1.54M
import dns import dns.name import dns.query import dns.resolver import sys root_server_list = ['198.41.0.4', '192.228.79.201', '192.33.4.12', '199.7.91.13', '192.203.230.10', '192.5.5.241', '192.112....
"""solve module""" import ast import operator def solve(expr: str) -> int: """solve_""" binops = { ast.Add: operator.add, ast.Sub: operator.sub, ast.Mult: operator.mul, ast.Div: operator.floordiv, ast.Mod: operator.mod } node = ast.parse(expr, mode='eval') ...
#encoding: utf-8 ''' https://www.geeksforgeeks.org/find-minimum-difference-pair/ Find minimum difference between any two elements Given an unsorted array, find the minimum difference between any pair in given array. Examples : Input : {1, 5, 3, 19, 18, 25}; Output : 1 Minimum difference is between 18 and 19 In...
``` ################################################################################################################### ############################### Phase-2: Converting it into a classification Problem ############################## ####################################################################################...
from ..shimmer import shimmer from ..data import get_bigbed_data class BAISContig(object): def __init__(self,seqcache): self.seqcache = seqcache def contig_shimmer(self,chrom,leaf): return self._contig_full(chrom,leaf,True,False) def contig_normal(self,chrom,leaf,seq): return self...
from axiom.test.historic.stubloader import saveStub from xmantissa.people import AddPerson def createDatabase(s): AddPerson(store=s) if __name__ == '__main__': saveStub(createDatabase, 10664)
# CAPP 30254 Machine Learning for Public Policy # Homework 5 - Improving the Pipeline, Again # Pipeline Library - Preprocessing functions ######### # SETUP # ######### import math import datetime import numpy as np import pandas as pd from sklearn.model_selection import train_test_split ##################### # PRIM...
def shift(lst, steps): if steps < 0: steps = abs(steps) for i in range(steps): lst.append(lst.pop(0)) else: for i in range(steps): lst.insert(0, lst.pop()) a = [1,2,3,4,5,6,7,8] b = 8 shift(a,b)
import math from time import time def isPrime( n ): if n % 2 == 0 and n > 2: return False return all(n%i for i in range(3, int(math.sqrt(n))+1, 2)) guess=3 primeCount=1 t=time() while primeCount<10001: if isPrime(guess): primeCount+=1 if primeCount==10001:break guess+=2 print "time",time()-t,"\nanswer...
from . import SensorReader, MemorySensorObserver import grovepi import atexit import grove_rgb_lcd from collections import OrderedDict import math import smbus import RPi.GPIO as GPIO from grove_i2c_barometic_sensor_BMP180 import BMP085 class GroveSensorReader(SensorReader): def __init__(self, key, pin=None): ...
import socket import io import struct import time import subprocess import sys import threading import signal import Queue NUMBER_OF_THREADS = 2 JOB_NUMBER = [1,2] queue = Queue.Queue() class Client(object): def __init__(self): self.server_address = "" self.tcp_port = 6000 self.tcp_g...
# -*- coding: utf8 -*- from app.db import db_session, engine from app.db.room import Room, user_in_room, OneToOneRoom from app.db.message import Message from app.db.user import User from sqlalchemy import update from datetime import datetime def get(id): return db_session.query(Room).get(id) def findByName(name)...
with open("day8.txt", "r") as fin: data = fin.read().strip().split('\n') regs = {} for l in data: ll = l.split(' ') reg, op, val, target, cmp, cval = ll[0], ll[1], int(ll[2]), ll[4], ll[5], int(ll[6]) if reg not in regs: regs[reg] = 0 if target not in regs: regs[target] = 0 ok = False if cmp ...
# Generated by Django 3.0.4 on 2020-03-06 13:40 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('colegio', '0006_curso_profesor'), ] operations = [ migrations.CreateModel(...
import numpy as np import cv2 class CannyEdgeDetection: def __init__(self, path): """ :param path: Path of the image """ self.image = cv2.imread(path) # reading the image from path in OpenCV - format BGR # initialize number of channels self.n_channels = 0 ...
# Copyright (C) 2013 Sony Mobile Communications AB. # All rights, including trade secret rights, reserved. import os import sys import copy import traceback import json import ave.config from ave.relay.server import RemoteRelayServer from ave.relay.resource import Relay from ave.network.exceptions impor...
from math import sqrt from os import system import ROOT from ROOT import TFile,kRed,kBlue,TCanvas,TLegend,kWhite,kGreen,kFALSE,kBlack,kViolet,kOrange,TLine ROOT.gROOT.SetBatch() ROOT.gROOT.LoadMacro("tdrstyle.C"); ROOT.gROOT.ProcessLine( 'setTDRStyle();') #setTDRStyle() ROOT.gROOT.LoadMacro("CMS_lumi.C+"); #f=TFile('d...
# -*- coding: utf-8 -*- import datetime from south.db import db from south.v2 import SchemaMigration from django.db import models class Migration(SchemaMigration): def forwards(self, orm): # Adding field 'Bureau_Code.department' db.add_column(u'omb_codes_bureau_code', 'department', ...
# Generated by Django 2.2.6 on 2019-10-29 20:07 from django.db import migrations, models import django.utils.timezone class Migration(migrations.Migration): dependencies = [ ('g_golf', '0008_auto_20191029_1950'), ] operations = [ migrations.AddField( model_name='hole', ...
from __future__ import print_function from __future__ import division import tensorflow as tf import numpy as np import time import argparse from model import Model, Config import properties as p import utils def main(model): global config print('Testing task: %s ' % config.task_id) # create model ...
lineList = [line.rstrip('\n') for line in open('bip39_en_words.txt')] p = 31 #słowo startowe s = 78 #skok for i in range(24): try: print(i + 1, p, lineList[p - 1]) p += s except IndexError: print("poza zakresem, dostosuj parametry") break
import pygame,time,random pygame.init() display_width=800 display_height=600 black=(0,0,0) red=(255,0,0) white=(255,255,255) car_width=69 carImg=pygame.image.load("carImage.png") gameDisplay=pygame.display.set_mode((display_width,display_height)) pygame.display.set_caption('Avoid Game') clock=pygame.time.Clock() d...
from django.db import models from .question import Question class Choice(models.Model): question = models.ForeignKey( Question, on_delete=models.CASCADE, ) choice_text = models.CharField( max_length=200, ) votes = models.IntegerField( default=0, ) def __st...
# -*- coding: utf-8 -*- import multiprocessing, os from time import sleep, ctime def info(title): print ('title is %s' %title) print ('module name:', __name__) if hasattr(os, 'getppid'): print ('parent process:', os.getppid()) print ('process id:', os.getpid()) def music(name, time=3): ...
#!/usr/bin/env python # written by brady [r3dact3d] import tweepy, os from config import * # Set up OAuth and integrate with API auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET) auth.set_access_token(ACCESS_TOKEN, ACCESS_SECRET) api = tweepy.API(auth) def tweet(): cmd = 'fortune -sae' proc = os.popen...
#%% import numpy as np import pandas as pd from sklearn.feature_extraction.text import CountVectorizer import re import string import math #%% song1 = open(".\lab8\song1.txt","r").read() #%% song2 = open(".\lab8\song2.txt","r").read() # %% def word_count(document): word_count_dictionary = dict() # This ste...
from django.contrib import admin from products.models import * class CategoryInLine(admin.TabularInline): model=Category extra=1 #class IdentificationInLine(admin.TabularInline): # model=Identification # extra=1 class MarketInterestInLine(admin.TabularInline): model=MarketInterest extra=1 #class FeatureIntera...
#!/usr/bin/python # # This software is licensed to you under the GNU General Public License, # version 2 (GPLv2). There is NO WARRANTY for this software, express or # implied, including the implied warranties of MERCHANTABILITY or FITNESS # FOR A PARTICULAR PURPOSE. You should have received a copy of GPLv2 # along with...
import numpy as np import cv2 import glob import os os.chdir(".") default_save_dir = 'processed/' if not os.path.exists(default_save_dir): os.makedirs(default_save_dir) ##mouse callback function mode = 1 drawing = False # true if mouse is pressed def update_mask(event,x,y,flags,param): global drawing,mask...
import xlwt def write_to_xlsx(data: dict, column_headers: list, rows_headers: list): book = xlwt.Workbook(encoding="utf-8") sheet = book.add_sheet("Matching", cell_overwrite_ok=True) for x, column_header in enumerate(column_headers): sheet.write(0, x + 1, column_header) for y, rows_heade...
from address import Address from telephone import Telephone from contact import Contact import json import utils.attributes_values as utilsattr def show_menu(): print('''Menu 1) Show contact 2) New contact 3) Delete contact 4) Show all contacts 5) Exit''') def show_find_menu(): print('''Find contacts ...
import requests import json def get_commits(github_id, repo): """Retrieve the commits for a specific user repository, using the Github API""" url = 'https://api.github.com/repos/{}/{}/commits'.format(github_id, repo) response = requests.get(url) todos = json.loads(response.text) commit_...
from django.contrib.auth import authenticate from django.contrib.auth import login from django.contrib.auth.mixins import LoginRequiredMixin from django.contrib.auth.views import LoginView, PasswordChangeView, PasswordChangeDoneView from django.urls import reverse_lazy from django.views import generic from accounts.fo...
from .auth import CommonInterfaceAuth from .vnfpkgm import CommonInterfaceVnfPkgm from .nsd import CommonInterfaceNsd from .nslcm import CommonInterfaceNslcm from .nsfm import CommonInterfaceNsfm from .nspm import CommonInterfaceNspm from .sonpackage import CommonInterfaceSonPackage from .database import CommonInterfac...
# sympyをインポート import sympy # 記号xを定義 sympy.var('x y z d epsilon alpha x0 y0 z0') # f(x)を定義 dist = (d - x*x0 - y*y0 - z*z0) / epsilon theta = sympy.acos(x*x0 + y*y0 + z*z0) / alpha f = sympy.exp(-dist ** 2) + sympy.exp(-theta**2) # f(x)を偏微分 df_dx = sympy.diff(f, x, 1) df_dy = sympy.diff(f, y, 1) df_dz = sympy.diff(f,...
# importing the requests library import requests import json import time import pandas as pd import numpy as np import base64 #https://www.toptal.com/python/in-depth-python-logging#:~:text=Python%20Logging%20Best%20Practices&text=Here%20are%20the%20best%20practices,root%20logger%20behind%20the%20scene. import sys i...
from unittest import TestCase from algorithmRunners import launch path = "/tmp/parallelGA/examples" class TestParallel(TestCase): def testFineGrained(self): executable = "runFineGrainedExample.py" launch(["localhost"], 10, path, executable) def testCoarseGrained(self): executable = "...
import datetime def set_all_indicators(candle_list): set_candle_gain(candle_list) set_average_gain(candle_list) set_rs(candle_list) set_rsi(candle_list) set_ema(candle_list, 12) set_ema(candle_list, 26) set_macd(candle_list) set_avg_rsi_high(candle_list) set_avg_rsi_low(c...
# https://codingbat.com/prob/p117019 """ Given 2 int values greater than 0, return whichever value is nearest to 21 without going over. Return 0 if they both go over. blackjack(19, 21) → 21 blackjack(21, 19) → 21 blackjack(19, 22) → 19 """ def blackjack(a: int, b: int) -> int: valids = [i for i in [a, b] if 21 ...
import networkx as nx import matplotlib.pyplot as plt import random import copy import numpy as np import pylab import math import pickle # The following function creates a graph that creates a graph that follows the preferential attachment model. # networkx library comes with a different implementation of...
from enum import Enum class PurchaseType(Enum): ROAD = 0 SETTLEMENT = 1 CITY = 2 DEV_CARD = 3
notas = [] for x in range(3): while True: try: nota = float(input("ingrese nota" + " " + str(x+1) + "=")) if nota>10 or nota<0: print("solo numeros entre 0 y 10") continue else: notas.append(nota) break ...
def getMatrix(rotation, shear, height_zoom, width_zoom, height_shift, width_shift): # Convert data to radians rotation = math.pi * rotation / 180.0 shear = math.pi * shear / 180.0 def get_3x3_mat(lst): return tf.reshape(tf.concat([lst],axis=0), [3,3]) # Rotation matrix c1 = tf.math.cos(rotation)...
import requests import json import sys def postMessage(midi_file): authkey = "Bearer xoxp-672670374340-709681237543-701524491505-cd8aae979ae71c4809b442a821d59ccc" url = "https://slack.com/api/chat.postMessage" headers = {"Content-Type":"application/json", "Authorization":authkey} body = {'text':'sing ...
import json from random import randint from copy import deepcopy from netaddr import * import pathlib from deepdiff import DeepDiff DEBUG = False PDEBUG = False def convert_well_known_communities(community): """Convert well known communities from string to ASPLAIN""" comm_map = { "No-Export": "65535:...
import json import requests from bs4 import BeautifulSoup from flask import Flask from scraper.scraper import Scraper app = Flask(__name__) @app.route('/<string:term>') def get_result(term): # get links for 5 fiver results from Google result = Scraper.scrape_google(search_term=term) pages = [] for ...
import os import pickle as pkl import sys import bokeh import numpy as np import pandas as pd from bokeh.layouts import column, gridplot from bokeh.models import BoxZoomTool, HoverTool, ResetTool, TapTool from bokeh.models import ColumnDataSource from bokeh.models.callbacks import CustomJS from bokeh.plotting import F...
class User(object): def __init__(self, name, email): self.name = name self.email = email self.books = {} #dict is {Book(object): rating} def get_email(self): return self.email def change_email(self, address): self.email = address #takes in a ...
""" Bubble Sort é um algoritmo de ordenação que pode ser aplicado em Arrays e Listas dinâmicas. Se o objetivo é ordenar os valores em forma decrescente, então, a posição atual é comparada com a próxima posição e, se a posição atual for maior que a posição posterior, é realizada a troca dos valores nessa posição. Ca...
from gym_jsbsim.task import Task from gym_jsbsim.catalogs.catalog import Catalog as c from gym import spaces import math import random import numpy as np """ @author Joe Williams A task in which the agent must perform steady, level flight maintaining its initial heading. Once the agent has been on heading...
import os import sys import logging from logging.handlers import RotatingFileHandler from config import Config logger = logging.getLogger("Rotating Log") logger.setLevel(Config.LOG_LEVEL or "DEBUG") handler = None if Config.LOG_FOLDER and Config.LOG_NAME: try: os.makedirs(Config.LOG_FOLDER, exist_ok=True...
from .client import Rainforest, requests, RainforestError from mock import Mock from .models import TestRun from requests import Response from unittest import TestCase class TestRainforest(TestCase): def test_init(self): rainforest = Rainforest('CLIENT_TOKEN') self.assertEqual(rainforest.client_to...
import pytest from pages.login_page import LoginPage @pytest.fixture(scope='function') def open_login_page(get_driver): print('Opening main page') return LoginPage.open(get_driver) @pytest.mark.login @pytest.mark.parametrize("username,password", [("standard_user", "secret_sauce"), ("problem_user", "secret_s...
"""Select podcast file from the gui. Here is where the selection is happening. GUI can select or or more file at once. If selection is only 1 file, then its going to check for other podcast in the same directory comparing the file modification date. # TODO: should update this could do better # It also check whetever...
#!/usr/bin/env python # encoding: utf-8 # -*- coding:UTF-8 -*- import os import re import sys reload(sys) sys.setdefaultencoding("utf-8") import xlrd zhaohang = { "工商信息": [3, 33], "开庭公告": [34, 119], "裁判文书": [120, 149], "法院公告": [150, 151], "被执行人": [152, 173], "失信": [174, 174], "审判流程": [175, 179], "欠税信息": ...
#!/usr/bin/env python3 # # Author: Alfin Akhret <alfin.akhret@gmail.com> # Implementation of HTTP/1.0 and HTTP/1.1 class HTTPUtils(): def __init__(self): pass def check_host_header(self, request_header): """Host header is required in HTTP/1.1 Any request that came without it will get '...
from ..tools import convert_from, warning from ..wiki import wikipedia_to_dbpedia from .model import canton, collectivite, departement, region, arrondissement, commune, epci, iris from .model import contours_etalab, COMMUNES_START, openfla @arrondissement.extractor(openfla('arrondissements-20131220-100m')) def extra...
from django import forms from ap.apps.events.models import Event class EventManagementForm(forms.ModelForm): class Meta: model = Event fields = [ 'title', 'event_type', 'about', 'start', 'place_name', 'city', 'st...
import scraperwiki import lxml.html # next line uses the scrape function from the scraperwiki library, applies it to the url in "" and stores it as object in html html = scraperwiki.scrape("http://uk.soccerway.com/teams/netherlands/fortuna-sittard/") # print html # next line takes the fromstring function from the lx...
def quick_sort(array): if len(array) < 2: return array pivot = array[0] less = [] greater = [] #print("Length: ", len(array)) for lNum in array[1:]: if lNum < pivot: less.append(lNum) for gNum in array[1:]: if gNum > pivot: gre...
#! /usr/bin/env python3 # -*- coding: utf-8 -*- # vim:fenc=utf-8 # # Copyright © 2018 weihao <blackhatdwh@gmail.com> # # Distributed under terms of the MIT license. from sklearn.ensemble import AdaBoostClassifier from sklearn.externals import joblib def test(X): model = joblib.load('model.pkl') return model.p...
import tensorflow as tf import keras import pickle import argparse import random import numpy as np from pool import Pool parser = argparse.ArgumentParser() parser.add_argument("-gen", "--generate", help="Generate Workers") parser.add_argument("-sav", "--save", help="Save Directory") parser.add_argument("-rt", "--re...
import deluca def convert_sim(sim): sim.__class__ = deluca.lung.environments.StitchedSim sim.inspiratory_model.__class__ = deluca.lung.utils.sim.nn.InspiratoryModel sim.inspiratory_model.default_model.__class__ = deluca.lung.utils.sim.nn.SNN for key in sim.inspiratory_model.boundary_dict: if ...
# -*- coding: utf-8 -*- # ---------------------------------------------------------------------- # CISCO-PORT-CHANNEL-MIB # Compiled MIB # Do not modify this file directly # Run ./noc mib make_cmib instead # ---------------------------------------------------------------------- # Copyright (C) 2007-2018 The...
#!/usr/bin/env python #Copyright 2018 Google LLC # #Licensed under the Apache License, Version 2.0 (the "License"); #you may not use this file except in compliance with the License. #You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #Unless required by applicable law or agreed...
import curses import os import csv import time import hashlib import graficar class menu: def __init__(self, window): self.window = window def pintarmenu(self): self.window.addstr(15, 41, "1. INSERTAR BLOQUE") self.window.addstr(16, 39, "2. SELECCIONAR BLOQUE") self.window....
from flask import Blueprint, jsonify, request, session from flask_login import current_user, login_required import jieba, json, numpy as np from pypinyin import pinyin from app import db, admin_required from app.chinese import segment import app.mod_passages.errors as errors from app.mod_passages import Passage, Chine...
import requests import os import datetime as dt # -------------------- SETUP CONSTANTS -------------------- # USERNAME = "cloudbreak" pixela_token = os.environ.get("PIXELA_TOKEN") GRAPH_ID = "graph1" headers = { "X-USER-TOKEN": pixela_token } # -------------------- ACCOUNT CREATION PER API DOCUMENTATION --------...
# -*- coding: utf-8 -*- """ Created on Sat Aug 18 22:35:49 2018 @author: ashutosh Simple LSTM for Sequence Classification of Movie Reviews """ import numpy as np import pandas as pd from keras.datasets import imdb from keras.models import Sequential from keras.layers import Dense, LSTM from keras.layer...
# Wade Polo 2/10/14 # Starting out with Python pg. 78-79 #9 # Celsius to Fahrenheit Temperature Converter # Takes input of temperateures in Celsius, calculates the Fahrenheit conversion, then displays the result ctemp = float(input('What is the temperature in degrees Celsius? ')) #asks for celsius temp ftemp = (((9 / ...
# to reproduce Fig. 5.2 # plays blackjack with infinite deck # evaluates the policy of sticking on 20 or 21 # uses every visit monte carlo evaluation import gym import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D import pickle env = gym.make('Blackjack-v0') episodes = 3000000 nu...
# Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 import filecmp import os import shutil import tempfile from colcon_bundle.verb.utilities import update_shebang class TestUtilities: def setup_method(self, method): self.tmpdir = tempfile.mkdte...
import csv import json import logging import os import re import LittleSister.Database as Database import pandas from LittleSister.Database.DeputiesElection import DeputiesElection class DeputiesProbabilityTable(Database.Database): path = Database.path / "DeputiesProbabilityTable/" name_format = "{}_{}_{}.c...
import unittest, sys sys.path.append('..') from foursumII import Solution class TestFourSumII(unittest.TestCase): def setUp(self): self.s = Solution() def test_four_sum_count(self): case_one = [[1,2], [-2,-1], [-1,2], [0,...
import numpy as np import matplotlib.pyplot as plt import sklearn.linear_model as lm from sklearn.metrics import mean_squared_error from sklearn.preprocessing import PolynomialFeatures def non_func(x): y = 1.6345 - 0.6235*np.cos(0.6067*x) - 1.3501*np.sin(0.6067*x) - 1.1622 * np.cos(2*x*0.6067) - 0.9443*np.s...
import os import sys base = os.path.join(os.path.dirname(os.path.abspath(__file__)), '../') sys.path.append(base) from model_builder import ModelBuilder def test_resnet(): model_builder = ModelBuilder(10, pretrained=False) print(model_builder.available_models) model = model_builder['resnet50'] print...
import textract import PyPDF2 def read_pdf(file_name: str = '') -> str: """ Reader for .pdf files :param file_name: file name :return: text from a file """ pdf_reader = PyPDF2.PdfFileReader(file_name) page_obj = pdf_reader.getPage(0) raw_text = page_obj.extractText() return raw_tex...
name = "Jake" gender = "Male" color_eye = "Brown" color_hair = "Black" residence = "South Korea" occupation = "Teacher" hobby = "Fishing" specialty = "Shooting" favorite = "Movie" animal = "Dog"
from django.shortcuts import render,get_object_or_404 from .models import Blog # Create your views here. def index(request): var_1 = Blog.objects.all() return render(request, 'blog/index.html', {'var_1':var_1}) def detail(request, blog_id): detail_home = get_object_or_404(Blog, pk=blog_id) return re...
import tweepy import oauth """Script to move everyone you're following onto a list""" api = oauth.create() # pull list of friends friends_list = api.friends_ids() num_of_friends = len(friends_list) # figure out how many lists you need print 'number of friends: ', num_of_friends num_of_lists = int(round(num_of_frien...
# coding: utf-8 """ Masking API Schema for the Continuous Compliance Engine API # noqa: E501 OpenAPI spec version: 5.1.18 Generated by: https://github.com/swagger-api/swagger-codegen.git """ from __future__ import absolute_import import re # noqa: F401 # python 2 and python 3 compatibility...
#!/usr/bin/env python # -*- coding: utf-8 -*- # Autheur: Matthieu Riou <matthieu.riou@etu.univ-nantes.fr> # Version: v0.1 # Versions de python supportées: 3.3+ # Dépendances: icalendar, requests (pip install ; utiliser virtualenvwrapper) # Notes: Pour choisir les groupes, aller remplir la fonction à la toute # fin du ...
#!/usr/bin/python3 ''' This is the '10-my_github' module. 10-my_github takes your Github credentials (username and password) and uses the Github API: (https://developer.github.com/v3/users/#get-the-authenticated-user) to display your id Assignment Requirements: * You must use Basic Authentication to access to your i...
km = float(input('Qual é a distância do seu destino?\n')) if km <= 200: print('O valor de sua passagem é de R${:.2f}.'.format(km * 0.5)) else: print('O valor de sua passagem é de R${:.2f}.'.format(km * 0.45)) print('Boa Viagem!!')
# Import functions from cohortextractor import ( StudyDefinition, patients, codelist_from_csv, codelist, Measure ) # Import codelists from codelists import * from datetime import date start_date = "2020-12-07" end_date = "2021-04-30" # Specifiy study definition study = StudyDefinition( def...
import json import subprocess import sys import os try: distobjs = subprocess.check_output([sys.executable, '-m', 'pip', 'list', '--disable-pip-version-check', '--format=json']) distobjs = distobjs.decode("utf-8") distobjs = json.loads(distobjs) dists = {} for obj in distobjs: dval = {} ...
import torch from torch.autograd import Variable import numpy as np import random import torch.nn.functional as F import _pickle as cPickle import matplotlib.pyplot as plt import math # Custom functions from Buffer import Buffer, Episode_Buffer from RDQN_net import RDQN_net from GymScreenProcessing import GymScreenPr...
import numpy as np import operator import sys from math import log from collections import Counter
# Generated by Django 2.2.5 on 2019-09-18 18:05 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('articles', '0010_auto_20190916_1936'), ('articles', '0005_auto_20190914_2315'), ] operations = [ ]
print('-=' * 20) print('MAIOR OU MENOR?') print('-=' * 20) op1 = int(input('Digite um número inteiro: ')) op2 = int(input('Digite outro valor inteiro: ')) if op1 > op2: print('O PRIMEIRO número é o maior.') elif op2 > op1: print('O SEGUNDO número é o maior') else: print('Os dois números são ig...
#!/bin/python ###################################### # calculate using sklearn TruncatedSVD # # Author: Fabian Buske (13/01/2015) ###################################### from scipy.sparse import lil_matrix from scipy.sparse import csr_matrix import numpy import regex, os, sys, errno, re import argparse from sklearn.dec...
# -*- coding: utf-8 -*- """ Created on Fri Jul 20 10:31:30 2018 @author: adityanalge """ def allocate_half(x): return int(x//2) def num_teams(): while True: teams = input("Enter Number of Teams :\n") try: teams = int(teams) return teams break...
from __future__ import print_function, division import os import sys import time from glob import glob from collections import OrderedDict import numpy as np from keras import backend from keras.models import Input, Model, load_model from keras.optimizers import Adam from keras_contrib.layers.normalization import In...
import random from django.core.exceptions import ObjectDoesNotExist from django.db import IntegrityError from django.utils.datastructures import MultiValueDictKeyError from rank.models import Rank from rest_framework import status from rest_framework.decorators import api_view, permission_classes from rest_framework.p...
import random import re import datetime import json import hashlib class Valitsin: def __init__(self): self.commands = {} def getCommands(self): return self.commands def makeDecision(self, bot, update, alternatives): now = datetime.datetime.now() data = [ updat...
import re import os import sys import networkx as nx import matplotlib.pyplot as plt import matplotlib.backends.backend_pdf import logging import pylab from dag4pkg import * dag = Dag4pkg() deplist = [] namelist = [] nodes_set = set() nodes_set_two = set() def visual_dag(arg1, arg2): """Function to get dag as a g...
import simpy import random class SimuladorProcesos: def __init__(self, env): self.cpu = simpy.Resource(env, capacity=1) self.memoria_ram = simpy.Container(env, init=100) def generador_de_procesos(env, cantidad, intervalo_de_procesos, simulador_de_procesos): for i in range(cantidad):...
#!/usr/bin/env python # coding: utf-8 # In[7]: nums = [1,2,3,4,5] a=sum(nums)/len(nums) #리스트의 합을 구하는 sum과 리스트의 수를 구하는 len을 사용한다. print(a) # In[ ]:
class Character(object): def __init__(self, chrdes, name, talk, sectalk): self.name = name self.chrdes = chrdes self.talk = talk self.sectalk = sectalk self.hungry = True self.luck = False def eat(self): if self.hungry: print("You are eaten.")...
#!/usr/bin/python # -*- coding: utf-8 -*- """ The test of make dataset """ import os import numpy from pylearn2.gui import patch_viewer from pylearn2.utils import serial, string_utils from pylearn2.datasets import preprocessing from data import cifar10 """ get data """ # make output dir output_dir = os.path.abspath...