text
stringlengths
8
6.05M
import numpy as np from keras.layers import Input,Dense, Activation from keras.models import Model from keras.utils.generic_utils import get_custom_objects # this function is just for example of usage of keras functional API def XOR_train_fully_keras(): #Since Q1 (XOR) only asks for drawing, in the code, I used ...
"""LoaderPool class. ChunkLoader has one or more of these. They load data in worker pools. """ from __future__ import annotations import logging from concurrent.futures import ( CancelledError, Future, ProcessPoolExecutor, ThreadPoolExecutor, ) from typing import TYPE_CHECKING, Callable, Dict, List, O...
import sys import argparse from misc.Logger import logger from core.awschecks import awschecks from core.awsrequests import awsrequests from core.base import base from misc import Misc class securitygroup(base): def __init__(self, global_options=None): self.global_options = global_options logger....
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def reverseList(self, head): """ :type head: ListNode :rtype: ListNode """ prev = None curr = head ...
# settings.py import os import djcelery djcelery.setup_loader() # 加载 djcelery BROKER_URL = 'pyamqp://guest@localhost//' BROKER_POOL_LIMIT = 0 CELERY_RESULT_BACKEND = 'djcelery.backends.database:DatabaseBackend' CELERY_RESULT_BACKEND = 'django-db' CELERY_CACHE_BACKEND = 'django-cache' ALLOWED_HOSTS = os.environ.g...
#!/usr/bin/python3.4 # -*-coding:Utf-8 adress = """{nom}, {prenom}, {ville} ({pays})""".format(prenom="Anthony", nom = "TASTET", ville = "Bayonne", pays = "FRANCE") print(adress)
from Classes import Property, Note from General import Functions class Person: def __init__(self, data_dict): self.data_dict = data_dict self.property_list = self.get_property_list() self.note_list = self.get_note_list() def get_property_list(self): return [ Pr...
""" Created on Sat Nov 18 23:12:08 2017 @author: Utku Ozbulak - github.com/utkuozbulak """ import os import numpy as np import torch from torch.optim import Adam from torchvision import models from misc_functions import preprocess_image, recreate_image, save_image class CNNLayerVisualization(): """ Prod...
import gzip import string import numpy as np from collections import defaultdict def get_sentences(corpus_file): """ Returns all the (content) sentences in a corpus file :param corpus_file: the corpus file :return: the next sentence (yield) """ # Read all the sentences in the file with ope...
import os class BaseConfig(object): """Base config class""" BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SECRET_KEY = 'AasHy7I8484K8I32seu7nni8YHHu6786gi' TIMEZONE = "Africa/Kampala" SQLALCHEMY_TRACK_MODIFICATIONS = True UPLOADED_LOGOS_DEST = "app/models/media/" U...
from nipype.pipeline.engine import Node, Workflow import nipype.interfaces.utility as util import nipype.interfaces.fsl as fsl import nipype.interfaces.c3 as c3 import nipype.interfaces.freesurfer as fs import nipype.interfaces.ants as ants import nipype.interfaces.io as nio import os def create_coreg_pipeline(name='c...
#! /usr/bin/env python3 import pandas as pd, pandas import numpy as np import sys, os, time, fastatools, json, re from kontools import collect_files from Bio import Entrez # opens a `log` file path to read, searches for the `ome` code followed by a whitespace character, and edits the line with `edit` def log_editor...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Feb 20 15:06:23 2020 @author: thomas """ #MODULES import os,sys import numpy as np import pandas as pd from mpl_toolkits import mplot3d import matplotlib as mpl #mpl.use('Agg') import matplotlib.pyplot as plt from matplotlib.ticker import (MultipleLoca...
# coding: utf-8 # # Part 1 of 2: Processing an HTML file # # One of the richest sources of information is [the Web](http://www.computerhistory.org/revolution/networking/19/314)! In this notebook, we ask you to use string processing and regular expressions to mine a web page, which is stored in HTML format. # **The ...
# -*- coding: utf-8 -*- import numpy as np import mat4py import matplotlib.pyplot as plt import matplotlib.colors as colors import sys from sklearn import preprocessing def distance(pointA, pointB): return np.linalg.norm(pointA - pointB) def getMinDistance(point, centroids, numOfcentroids): min_distance = sys...
# Generated by Django 2.2.6 on 2019-10-19 13:34 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('food', '0001_initial'), ] operations = [ migrations.AlterField( model_name='food', name='CO2', field=mod...
from flask import Flask, jsonify, render_template, send_file app = Flask(__name__, template_folder='templates') from crawler import getFileNames, searchInternet import os, pdfkit @app.route("/search=<query>") def search(query): searchInternet(query) resp = jsonify({"data": "Success"}) resp.headers['Acces...
from pandas import * from ggplot import * import pprint import datetime import itertools import operator import brewer2mpl import ggplot as gg import matplotlib.pyplot as plt import numpy as np import pandas as pd import pylab import scipy.stats import statsmodels.api as sm import pandasql from datet...
import datetime import os import requests from mastodon import Mastodon from bitcoin_acks.database.session import session_scope from bitcoin_acks.models import PullRequests from bitcoin_acks.models.toots import Toots MASTODON_CREDPATH = os.environ['MASTODON_CREDPATH'] MASTODON_APPNAME = os.environ['MASTODON_APPNAME'...
from keras.models import Sequential from keras.layers import LSTM from legacy import AttentionDecoder model = Sequential() model.add(LSTM(150, input_shape=(20,1), return_sequences = True)) model.add(AttentionDecoder(150, 3)) model.summary() model.compile(optimizer='rmsprop', loss='categorical_crossentropy', metri...
from django.conf.urls import patterns, include, url from storefront import views from tastypie.api import Api from storefront.api import StoreResource,AlbumResource store_resource = StoreResource() v1_api = Api(api_name='v1') v1_api.register(StoreResource()) v1_api.register(AlbumResource()) # Uncomment the next two...
import data_cruncher, sqlite3 from aocmm_functions import insert_probabilities conn = sqlite3.connect("data.db") c = conn.cursor() ## Gets data from user lines = [] while True: line = raw_input() if line: lines.append(line) else: break typing_data = "".join(lines) typing_data = typing_da...
#!/usr/bin/python # -*- coding: utf-8 -*- import hashlib import ConfigParser import datetime import sys sys.path.append("/SysCollect/class/config") import db import logMaster class Auth(object): def __init__(self): config = ConfigParser.ConfigParser() config.read('/SysCollect/class/config/config.c...
from rest_framework import generics, serializers from .models import PointTable from .serializers import PointTableSerializer class PointsTableApi(generics.ListAPIView): """ api to return list of teams """ model = PointTable serializer_class = PointTableSerializer def get_queryset(self): ...
from tfcgp.config import Config from tfcgp.chromosome import Chromosome from tfcgp.problem import Problem import numpy as np import tensorflow as tf from sklearn import datasets c = Config() c.update("cfg/base.yaml") data = datasets.load_iris() def test_creation(): p = Problem(data.data, data.target) print(p....
class Routes: endpoints = "/products/"
from train import start_training import argparse def parse_args(): parser = argparse.ArgumentParser(description='Model that learns method names.') group = parser.add_mutually_exclusive_group(required=True) group.add_argument('--train', '-t', action='store_true', help='train the model') group.add_argum...
import tkinter as tk window_main = tk.Tk() window_main.title("Keypress Viewer") window_main.iconbitmap("favicon.ico") window_main.geometry("500x500") text_to_display = tk.StringVar(window_main) display_label = tk.Label(window_main, textvariable=text_to_display, font="none 60 bold") display_label.config(anchor="center...
def volboite(x1=10 , x2=10, x3=10): v = x1 * x2 * x3 return(v) def maximum(n1, n2, n3): m=0 if n1>n2 and n1>n3: m = n1 if n2>n1 and n2>n3: m = n2 if n3>n1 and n3>n2: m = n3 return(m) print(volboite(5.2, 3))
#!/usr/bin/python3 import pymongo ''' Read a text file and seed it's contents into a collection ''' uri = 'mongodb+srv://user:password@host' client = pymongo.MongoClient(uri) collection = client.collectionname # Insert one record into the collection def seed(content, category): collection.insert_one( { ...
from fabdefs import * from fabric import api import os python = "%s/bin/python" % env_dir pip = "%s/bin/pip" % env_dir def deploy(): with api.cd(code_dir): api.run("git pull origin master") api.run("%s install -r %s/deploy/production.txt --quiet" % (pip, code_dir)) with api.cd(os.path.joi...
# Clase que controla el uso de los distintos # avatares disponibles para el usuario # Dependiendo de su 'score' tendrá acceso # a más o menos avatares import os PWD = os.path.abspath(os.curdir) avatars = os.listdir(PWD + r"/aplicacion/static/avatars") avatars.remove("default_avatar.png") # Los ficheros cuyo nombre ...
import sys import math class SetOfStacks: #define the size of EACH individual stack CHUNK = 7; def __init__(self, input_data=[]): self.size = 0; self.stack_count = 0; self.stack_stack = []; self.extend(input_data); #write data onto those stacks ...
import argparse import asyncio import base64 import collections import json import math import os import pprint import websockets DEFAULT_HOST = 'localhost' DEFAULT_PORT = 3000 class FileTreeNode: def __init__(self, path, is_file, size=None, children=None): self.path = path self.base_name = os.pa...
# Fit the Lotka-Volterra with prey density dependence rR(1 - R/K), plot and save population dynamics between consumer and resource with input from command line # import packages import scipy as sc import numpy as np import scipy.integrate as integrate import matplotlib.pylab as p import sys # define a function that r...
import requests from lxml import etree import time import random import pymysql class FundSpider: def __init__(self): self.url = 'http://www.southmoney.com/fund/' self.headers = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.75 Safari/537.3...
#NOVA #by TheDerpySage import discord from discord.ext import commands import asyncio import nova_config import db_functions import email_functions from datetime import datetime desc = '''NOVA-BOT A planner robot.''' bot = commands.Bot(command_prefix='n$',description=desc) #This is a buffer for the messages sent. ...
# hello.py """ Usage: $ python hello.py manage.py """ import sys import os from django.conf import settings from django.urls import path from django.http import HttpResponse from django.shortcuts import render ALLOWED_HOSTS = os.environ.get('ALLOWED_HOSTS', 'localhost').split(',') BASE_DIR = os.path.dirname(...
import numpy as np import tensorflow as tf from boxes import get_boxes, get_final_box from constants import real_image_height, real_image_width, feature_size from models.classifier import Classifier from models.feature_mapper import FeatureMapper from models.regr import Regr from models.roi_pooling import RoiPooling f...
#!/usr/bin/env python # Copyright (c) 2012 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. """ Verifies that the global xcode_settings processing doesn't throw. Regression test for http://crbug.com/109163 """ import TestGyp impor...
import os import uuid from time import sleep from datetime import datetime, timedelta from flask import Flask, request, flash, redirect, url_for, send_from_directory, g, render_template from flask_analytics import Analytics from peewee import * from fisheye import FisheyeVideoConverter import concurrent.futures impo...
#!/bin/env python # Copyright 2021 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agre...
from .Factorial import Factorial import unittest class TestFactorial(unittest.TestCase): def test_one(self): self.assertEqual(Factorial(1), 1) def test_five(self): self.assertEqual(Factorial(5), 120) def test_fifteen(self): self.assertEqual(Factorial(15), 1307674368000) if __name...
#!/usr/bin/env python import RPi.GPIO as GPIO import signal import sys sys.path.append('/home/pi/Desktop/smartScan/RFID_BarCodeRpi') from scanRFID import SimpleMFRC522 from scanRFID import MFRC522 continue_reading = True def barcodeReader(): shift = False hid = { 4: 'a', 5: 'b', 6: 'c', 7: 'd', 8: 'e', 9: 'f...
import unittest from katas.kyu_7.thinking_and_testing_something_capitalized import \ testit as solution # py.test seems to have issues when function name has 'test' in it class SomethingCapitalizedTestCase(unittest.TestCase): def test_equals(self): self.assertEqual(solution(''), '') def test_equ...
from datetime import datetime from django.core.paginator import EmptyPage, PageNotAnInteger, Paginator from django.db.models import Prefetch, Q from django.http import Http404 from django.views.generic import ListView, TemplateView from elections.models import Election from organisations.models import Organisation c...
import math as m def distance(lat1, lat2, long1, long2): #haversine formula r = 6371.009 #km lat1, lat2, long1, long2 = map(m.radians,[lat1,lat2,long1,long2]) inner = (m.sin((lat2-lat1)/2)**2)+(m.cos(lat1)*m.cos(lat2)*(m.sin((long2-long1)/2)**2)) inside = m.sqrt(inner) d = 2*r*m.asin(inside) return d
class Personne: def __init__(self,nom,prenom,age,moyenne): #constructor self.nom = nom self.prenom = prenom self.age = age self.moyenne = moyenne def Say(self): #methode return "Hello "+self.nom+" "+self.prenom def Age(self): if(self.age>40): ...
''' By Real2CAD group at ETH Zurich 3DV Group 14 Yue Pan, Yuanwen Yue, Bingxin Ke, Yujie He Editted based on the codes of the JointEmbedding paper (https://github.com/xheon/JointEmbedding) As for our contributions, please check our report ''' import argparse import json from typing import List, Tuple, Dict import os...
noodlephrase = '<b>GIVE ME NY NOODLES BACK, U GODDAMN SON OF A BITCH!</b>\nOtherwise im gonna do nothing.' \ ' Thanks.\n\n<code>P.S. This aint gonna stop till u will give me my lovely noodles back. This messages ' \ 'are sent by a fully autonomous AI that is so advanced, that you cant even...
import requests cfg = { "time": "2019-05-01T00:00:00Z", "driver": "bsync_driver.BuildingSyncDriver", "mapping_file": "data/buildingsync/BSync-to-Brick.csv", "bsync_file": "data/buildingsync/examples/bsync-carytown.xml" } resp = requests.post('http://localhost:5000/get_records', json=cfg) print(resp.js...
import graphene from architect.document.models import Document from graphene import Node from graphene_django.filter import DjangoFilterConnectionField from graphene_django.types import DjangoObjectType class DocumentNode(DjangoObjectType): widgets = graphene.List(graphene.types.json.JSONString) class Meta:...
# !/usr/bin/python # -*- coding:utf-8 -*- import multiprocessing as mp import tensorflow as tf from sub_tree import sub_tree from sub_tree import node import sys import logging import time import Queue import numpy as np from treelib import Tree import copy from utils import compute_bleu_rouge from utils import norma...
from django.conf import settings from confapp import conf from pyforms.basewidget import segment from pyforms_web.web.middleware import PyFormsMiddleware from pyforms_web.widgets.django import ModelAdminWidget from finance.models import ExpenseCode class ExpenseCodeListApp(ModelAdminWidget): TITLE = 'Expense c...
"""Plot source space NDVars with mayavi/pysurfer.""" # Author: Christian Brodbeck <christianbrodbeck@nyu.edu> from ._brain import (activation, cluster, dspm, stat, surfer_brain, annot, bin_table, copy, image, p_map, annot_legend)
import speech_recognition as sr import pyaudio import wave from pydub.playback import play from pydub import AudioSegment import numpy as np import struct import time sr.__version__ FORMAT = pyaudio.paInt16 LEN = 10**100 PASS = 5 CHANNELS = 1 RATE = 44100 CHUNK = 1024 RECORD_SECONDS = 3 MIN_STRING_LIST_LENGTH = 9 WAVE...
#!/usr/bin/env python # Copyright (c) 2012 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. """ Verifies that VS variables that require special variables are expanded correctly. """ import sys import TestGyp if sys.platform == 'wi...
import turtle import math a = 200 b = 100 pop = turtle.Turtle() pop.hideturtle() pop.speed(5) for i in range(33): if i == 0: pop.up() else: pop.down() pop.setposition(a*math.cos(i/10), b*math.sin(i/5)) pop.setposition(a*math.cos(i/10), b*math.sin(...
# -*- coding: utf-8 -*- """ Created on Thu Sep 26 14:15:25 2013 @author: bejar """ import scipy.io import numpy as np from scipy import signal def zeroedRange(freq,length,limi,limf): nqfreq=freq bins=nqfreq/length rlimi=limi/bins rlimf=limf/bins return(int(rlimi),int(rlimf)) def filterSignal(d...
# NO IMPORTS! ############# # Problem 1 # ############# def runs(L): """ return a new list where runs of consecutive numbers in L have been combined into sublists. """ runs = [] current_run = [] if len(L)>0: current_run = [L[0]] for i in range(len(L)-1): if L[i]+1==L[i+1]: ...
# -*- coding: utf-8 -*- # This code is initially based on the Kaggle kernel from Sergei Neviadomski, which can be found in the following link # https://www.kaggle.com/neviadomski/how-to-get-to-top-25-with-simple-model-sklearn/notebook # and the Kaggle kernel from Pedro Marcelino, which can be found in the link bel...
# -*- coding: UTF-8 -*- # Filename : helloworld.py # author by : Jay print('Hello world') num1 = input('input first number:') num2 = input('input second number:') sum = float(num1) + float(num2) print('sum of num {0} and num{1}: {2}'.format(num1, num2, sum)) # 平方根 num3 = input('input third number:') num_sqt = f...
# -*- coding: utf-8 -*- # Generated by Django 1.9 on 2016-01-01 10:26 from __future__ import unicode_literals from django.db import migrations import tinymce.models class Migration(migrations.Migration): dependencies = [ ('main', '0002_auto_20160101_0918'), ] operations = [ migrations.R...
class Signin: account_ID = 0 account_name = "" account_height = 0 account_weight = 0 account_birthday = "" account_level = 0 account_address = "" account_pass = "" def __init__(self, account_ID, account_name, account_height, account_weight, account_birthday, account...
# change url to channel.zip --> download a zip file that contains a readme.txt import re import zipfile channel_zip_file = zipfile.ZipFile("channel.zip") file_name = str(90052) commentList = [] while file_name != "": f = open("channel/"+ file_name + ".txt", "r") data = f.read() print(data) number = r...
#!/usr/bin/python # -*- coding: UTF-8 -*- import re line = "Cats are smarter than dogs"; matchObj = re.match(r'dogs',line,re.M|re.I) if matchObj: print "match --> matchObj.group() : ",matchObj.group() else: print "No match!!" matchObj2 = re.search(r'dogs',line, re.M|re.I) if matchObj2: print "search -...
#!/usr/bin/env python # coding=utf-8 import torch import torch.nn as nn import torch.nn.functional as func class MultiLabelLoss(nn.Module): def __init__(self): super(MultiLabelLoss,self).__init__() return def forward(self,input,target): batch_size = input.size()[0] loss = func...
#!/usr/bin/env python # encoding: utf-8 import urllib import logging from tornado.gen import coroutine from tornado.httpclient import AsyncHTTPClient from settings import ALERT_SMS_API, ALERT_SMS_TOKEN @coroutine def sender(mobiles, content): """ TODO: 这里使用的sms接口,是根据voice猜出来的,所以实现方式 与voice一模一样也能发送,只是接口...
from django.contrib import admin # Register your models here. from .models import Question, Choice ''' => admin.site.register(Question) => admin.site.register(Choice) Ao registrarmos o modelo de Question através da linha admin.site.register(Question), o Django constrói um formulário padrão para representá-lo. ...
import torch from torch import nn from torch.nn import functional as F from torch.nn.parameter import Parameter AdaptiveAvgPool2d = nn.AdaptiveAvgPool2d class AdaptiveConcatPool2d(nn.Module): def __init__(self, sz=None): super().__init__() sz = sz or (1, 1) self.ap = nn.AdaptiveAvgPool2d(...
__author__ = 'pg1712' # The MIT License (MIT) # # Copyright (c) 2016 Panagiotis Garefalakis # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitatio...
from aiogram import types choice = types.InlineKeyboardMarkup( inline_keyboard=[ [ types.InlineKeyboardButton(text="vk", url="https://vk.com/papatvoeipodrugi"), types.InlineKeyboardButton(text="trello", url="https://trello.com/b/zStEwgMk/%D0%BF%D0%BE%D0%BC%D0%BE%D1%89%D0%BD%D0%B8%...
from fabric.api import local, task repos = ( { 'name': 'gch-content', 'path': 'content', 'url': 'git@github.com:zombie-guru/gch-content.git', 'branch': 'master', }, { 'name': 'gch-theme', 'path': 'theme', 'url': 'git@github.com:zombie-guru/gch-theme....
import os from easydict import EasyDict as edict cfg1 = edict() cfg1.PATH = edict() cfg1.PATH.DATA = ['/home/liuhaiyang/dataset/CUB_200_2011/images.txt', '/home/liuhaiyang/dataset/CUB_200_2011/train_test_split.txt', '/home/liuhaiyang/dataset/CUB_200_2011/images/'] cfg1.PATH.LABEL = '/home/liuhaiyang/da...
# Generated by Django 3.2.7 on 2021-09-22 16:31 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='OCRJob', fields=[ ...
from salem.api import AppsFlyerAPI, AppsFlyerDataLockerAPI from salem.reporting import AppsFlyerReporter, AppsFlyerDataLockerReporter
import tkinter as tk from tkinter import * from tkinter import ttk #import defs_common LARGE_FONT= ("Verdana", 12) class PageEnvironmental(tk.Frame): def __init__(self, parent, controller): tk.Frame.__init__(self, parent) self.parent = parent self.controller = controller label =...
#!/usr/bin/env python # Copyright (C) 2012 STFC # # 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 applicab...
from lib.Color import Vcolors from lib.Urldeal import urldeal
#!/usr/bin/python3 #Author: n0tM4l4f4m4 #Title: solver.py import struct import codecs import binascii from pwn import * context.arch = "x86_64" context.endian = "little" str_v = 'NIIv0.1:' game_1 = 'TwltPrnc' game_2 = 'MaroCart' game_3 = 'Fitnes++' game_4 = 'AmnlXing' shell_ = asm(shellcraft.sh()) checksum = 0 f...
# coding: utf-8 # In[22]: import pandas as pd # In[23]: df = pd.read_csv("/Users/naveen/Documents/python_code/Test/dataset-Sg/singapore-citizens.csv") print(df.head(2))
from django.db import models class Ad(models.Model): class Status: NEW = 1 APPROVED = 2 UNAPPROVED = 100 choices = ( (NEW, 'New'), (APPROVED, 'Approved'), (UNAPPROVED, 'Unapproved'), ) posted_at = models.DateTimeField(auto_now_add=T...
import sys sys.path.append('/starterbot/Lib/site-packages') import os import time import requests from slackclient import SlackClient from testrail import * # settings project_dict = {'Consumer Site': '1', 'Agent Admin': '2','Domain SEO': '5', 'Mobile Site': '6', 'Find An Agent': '10', 'Digital Data': '11'} ...
# Generated by Django 3.0.7 on 2020-09-27 15:07 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('API', '0009_remove_respondentprofile_respondentsurveytopics'), ] operations = [ migrations.RenameField( model_name='respondentprofile', ...
#!/usr/bin/env python """ TODO: parse the tables found in ~/scratch/simbad_classes_ptf_sources/*.tab - create, have a table which contains this information, including the (sn,09), (agn,10).... columes - also have a col for the tcp srcid. - also have a column that the tcp has completely ingested that source TODO:...
# -*- coding: utf-8 -*- class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def findMode(self, root): def _findMode(current, previous, count, max_count, result): if current is None: return previous...
# --- # jupyter: # jupytext: # formats: ipynb,py:light # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.3.3 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # + import numpy as np im...
from __future__ import print_function, division import numpy as np import matplotlib.pyplot as plt import thinkplot from matplotlib import rc rc('animation', html='jshtml') import warnings import matplotlib.cbook warnings.filterwarnings("ignore", category=matplotlib.cbook.mplDeprecation) from thinkstats2 import Ra...
import numpy as np import torch import yaml from tqdm import tqdm def kmean_anchors(path='./data/coco128.yaml', n=9, img_size=640, thr=4.0, gen=1000, verbose=True): """ Creates kmeans-evolved anchors from training dataset Arguments: path: path to dataset *.yaml, or a loaded dataset ...
import nltk, os def get_documentos(): documentos = [] path = "/home/mateus/Documents/TESIIII/GameOfTESI-2-master/DataBase/episodesTXT" for i in range(1, 7): season_path = path + "/season_" + str(i) for filename in os.listdir(season_path): documentos.append(season_path ...
def yes_or_no(question): while True: answer = input(question + " [y or Enter/n]: ").lower() if answer.startswith('y') or not answer: return True elif answer.startswith('n'): return False print("Invalid answer. Please enter either 'yes', 'y', 'no', 'n'.") def ...
from rest_framework import serializers from billings.models import Invoice,BillType,Payment from djmoney.money import Money import datetime class BillTypeSerializer(serializers.ModelSerializer): class Meta: model = BillType fields=( 'id', 'name', ) class PaymentSeria...
import requests from bs4 import BeautifulSoup import re import urllib prefix = ".//{http://www.tei-c.org/ns/1.0}" xml = ".//{http://www.w3.org/XML/1998/namespace}" start = 5016 # 1は除く end = 5071 index = 1 #1 は除く seq = 1 info = requests.get("https://genji.dl.itc.u-tokyo.ac.jp/data/info.json").json() map = {} count...
from string import Template import os CHUNCK = 1024 ARM_LOGIN_URL = Template( "https://www.archive.arm.gov/armlogin/doLogin.jsp?uid=$username&ui=iop" ) SIPAM_LOCAL_PATH = Template( os.path.join( '/'.join(os.path.abspath(os.path.dirname(__file__)).split(os.sep)[:-1]), 'datasets/sipam/$year/$mo...
#!/usr/bin/env python # encoding: utf-8 ''' Find MST for facilities problem. ''' import glob import json import itertools from operator import attrgetter import os import random import sys import math import networkx as nx import numpy import random as Random #Returns an array of the shortest path between any two p...
from django.apps import AppConfig class MisperrisdjConfig(AppConfig): name = 'misPerrisDJ'
import pygame import sys def Intersect(x1, x2, y1, y2, db1, db2): if (x1 > x2 - db1) and (x1 < x2 + db2) and (y1 > y2 - db1) and (y1 < y2 + db2): return 1 else: return 0 window = pygame.display.set_mode((800, 670)) pygame.display.set_caption('Menu') screen = pygame.Surface((800, 640)) info =...
from poker.card import Card from poker.deck import Deck from poker.game import Game from poker.hand import Hand from poker.player import Player deck = Deck() cards = Card.create_standard_52_cards() deck.add_cards(cards) i = 0 hands = [] players = [] player_num = int(input("Enter the number of players: ")) while i < pl...
def load_doc(filename): file = open(filename, 'r') text = file.read() file.close() return text def save_doc(lines, filename): data = '\n'.join(lines) file = open(filename, 'w') file.write(data) file.close() raw_text = load_doc('gg_gut.txt') tokens = raw_text.split() raw_text = ' '.join(tokens)...
# -*- coding:utf8 -*- # !/usr/bin/env python # Copyright 2017 Google Inc. All Rights Reserved. # # 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...