text
stringlengths
38
1.54M
import logging from json_builder import JSONObjectBuilder, JSONObject from string_functions import to_json, from_json if __name__ == '__main__': logging.basicConfig( format='%(asctime)s %(levelname)s [%(name)s] %(message)s', level=logging.INFO ) to_json([{"foo": [1, 2, '2']}]) from_js...
import os HEADERS = {'X-Requested-With': 'XMLHttpRequest'} IP = "http://121.42.15.146:9090" ABS_PATH = os.path.abspath(__file__) DIR_NAME = os.path.dirname(ABS_PATH)
from collections import Counter import random import nltk from nltk import trigrams, bigrams from nltk.util import ngrams from collections import Counter, defaultdict f = open('book2.txt', 'r') new = f.read() new = new.strip('\n').lower().replace(',', '') new = new.split() resultwords = [word for word in new] result...
#!/usr/bin/python """ Provides curl like functionality. The script is provided to upgrade agent where curl is not available. It provides the minimum functionality curl-install.sh requires to download and install the agent. """ __copyright__ = '(c) Webyog, Inc' __author__ = 'Vishal P.R' __email__ = 'hello@sealion.com...
from watson_developer_cloud.natural_language_understanding_v1 import * from ..models import Article from ..logic.doctree import DocTree, LinkedIndex from watson_developer_cloud import NaturalLanguageUnderstandingV1 import json MIN_TEXT_LENGTH = 30 def init_nlu_engine(): url = "https://gateway.watsonplatform.net/...
"""Utils for candidate data and recruitment data""" from faker import Faker HIGHSCHOOL_TYPE = ["Liceum", "Technikum"] FACULTIES = ["WIET", "WEAIB", "WIMIC", "WIMIR", "WZ", "WIMIP"] DEGREE = ["BACHELOR", "MASTER"] MAJORS = open("field_of_studies").read().splitlines() MODE = ["PART_TIME", "FULL_TIME"] faker = Faker('pl_...
class Jungle(object): def __init__(self): self.amazon = "Amazon" def show_jungle(self): print(self.amazon) class MangoOrchid(object): def __init__(self): self.myOrchid = "Dasheri" self.fromForest = Jungle() def show_orchid(self): self.fromForest.show_jungle() ...
from django.shortcuts import render from rest_framework.generics import ListAPIView from rest_framework_extensions.cache.mixins import ListCacheResponseMixin from .serializers import SKUSerializer from .models import SKU from . import constants # Create your views here. class HotSKUListView(ListCacheResponseMixin, ...
from django.db import models from django.conf import settings User = settings.AUTH_USER_MODEL class Profile(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null = True, blank = True) address = models.CharField(max_length=50, blank=True, null=True) OIB = models.CharField(max_leng...
# Pytorch import copy from torch.autograd import grad class ModelWrapper(): """ Simple model wrapper to hold pytorch models plus set up the needed hooks to access the activations and grads. """ def __init__(self, model=None, bottlenecks={}): """ Initialize wrapper with model and set up the ho...
import os from abc import ABC from typing import BinaryIO, Optional, NoReturn, IO, ClassVar import numpy as np from yuv.com_def import BitDepth, Format, Component from yuv.com_def import Sequence, Frame, _get_uv_wh class YuvIO(object): def __init__(self, seq: Sequence, mode: str): assert 'b' in mode ...
"""Unit Test for otx.algorithms.detection.adapters.mmdet.utils.config_utils.""" # Copyright (C) 2023 Intel Corporation # SPDX-License-Identifier: Apache-2.0 # import math import tempfile from typing import List import pytest from mmcv.utils import Config, ConfigDict from otx.algorithms.common.adapters.mmcv.utils imp...
# A function is a block of code which runs when it is called. # In python, we do not use parameters and curly brackets, we use indentation with tabs or spaces # Create Function def sayHello(): print('Hello World') def sayName(name): print('Hello ' + name) # With default value def say_Name(name = 'Sam'): ...
from PIL import Image from torch import nn, optim import torch import torch.nn.functional as F import torchvision import torchvision.transforms as transforms from torchmetrics.functional import accuracy from tqdm import tqdm from sklearn.cluster import KMeans import numpy as np import resnet import barlow import d...
import numpy as np # linear algebra import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv) import cv2 as cv import os import sklearn.model_selection as model_selection from sklearn.metrics import accuracy_score from keras.models import Sequential from keras.layers import Dense,MaxPooling2D,Activation,F...
from models import SwapRequest from emails import sendEmail # Don't let a user submit identical have/want request def process(input_req): input_req.save() cycle = input_req.find_cycle() if cycle != None: req_strs = [] for req in cycle: req_strs.append(unicode(req)) for ...
import itertools import copy import numpy as np from collections import Counter INITIAL_FLOOR_PLAN = 'inputs/11_input.txt' def pad_with(vector, pad_width, iaxis, kwargs): """ String padder utility function. https://stackoverflow.com/questions/49049852/numpy-string-array-pad-with-string """ pad_...
from rest_framework import permissions class IsOwnerOrAdminOrReadOnly(permissions.BasePermission): def has_object_permission(self, request, view, obj): if request.method in permissions.SAFE_METHODS: return True if request.user.is_staff: return True return obj.nick == request.user.username
import requests import pandas as pd from pandas.io.json import json_normalize import json import highchartssample from dateutil.parser import parse import analyticsutils from functools import reduce from datetime import datetime, date, time, timedelta today=datetime.today().strftime('%Y-%m-%d') yesterday=(datetime.tod...
# -*- coding: utf-8 -*- from interface import implements from .generics.interfaces import UI import os import re import sys import json import hashlib import datetime import binascii import operator import itertools from datetime import timezone from functools import reduce from Cryptodome.PublicKey import RSA fro...
from datetime import datetime, time import requests import tkinter as tk from tkinter import ttk, messagebox from tkcalendar import DateEntry import re class AddPatientPopup(tk.Frame): """ Popup Frame to Add a Student """ def __init__(self, parent, close_callback): """ Constructor """ self.i...
from flask import Flask, jsonify, request, Response import json import jwt, datetime from validBookObject import * from settings import * from BookModel import * from UserModel import * from functools import wraps app.config['SECRET_KEY'] = 'jellyfish' books = Book.get_all_books() DEFAULT_PAGE_LIMIT = 3 def token_...
# -*- coding: utf-8 -*- # Generated by Django 1.11.4 on 2017-09-02 00:07 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('member', '0005_auto_20170901_2008'), ] operations ...
from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from bs4 import BeautifulSoup as soup import time from selenium.webdriver.common.keys import Keys driver = webdriver.Chrome...
import numpy as np from scipy.io.wavfile import read from scipy.io.wavfile import write import cv2 import math import queue from threading import Thread import time ### def png_encode(list):#pass a list of size 3; 1. 2D, signed, 16bit integer array 2. image hieght 3. image length : converts to a BGR array to b...
name = 'Erik' print('Hoi ' + name + ', wil je vandaag iets over Python leren?') print (name.upper()) print (name.lower()) print (name.title()) famous_person=" Albert Einstein " quote= "If you can't explain it simple, you don't understand it well enough." message = famous_person.strip() + ' zei ooit: ' + '"' + quo...
# Generated by Django 2.2.2 on 2019-09-09 13:39 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('ReclamaCaicoApp', '0016_auto_20190909_0304'), ] operations = [ migrations.RemoveField( model_name='reclamacao', name='foto',...
from typing import Dict, Optional, List, Union class LabelEncoder(object): def __init__(self, initial_dict: Optional[Dict] = {}) -> None: self.label2id = initial_dict self.id2label = {idx: label for idx, label in enumerate(self.label2id)} def add(self, label: Union[str, int]): if labe...
from django.db import models from django.contrib.auth.models import User from django.conf import settings User = settings.AUTH_USER_MODEL class vote_count(models.Model): UserName= models.CharField(max_length=50,blank=False,default="") Number_Of_Votes_You_Cast = models.IntegerField(blank=True,default=0) ...
#!/usr/bin/python3 import requests import time import argparse from concurrent.futures import ThreadPoolExecutor class User: def __init__(self, hub_url, username, password): self.hub_url = hub_url self.username = username self.password = password self.session = requests.Session() ...
def jaccord_similarity(q1, q2): set1 = set(q1) set2 = set(q2) intersection = set1.intersection(set2) union = set1.union(set2) return len(intersection)/len(union) if __name__ == "__main__": q1 = "怎么用百度" q2 = "怎么登陆百度" print(f'score:{jaccord_similarity(q1, q2)}')
from woof.partitioned_producer import PartitionedProducer import socket import time import logging import threading log = logging.getLogger("kafka") woof_tls = threading.local() class TransactionLogger(object): def __init__(self, broker, vertical, host=socket.gethostname(), async=False): self.broker = br...
from app import start def test_parse_line(): parsed_line = start.parse_line( '208.115.111.72 - - [16/Mar/2019:16:16:40 +0000] "GET /robots.txt HTTP/1.1" 200 - "-" "Mozilla/5.0 (compatible; Ezooms/1.0; help@moz.com)"' ) assert parsed_line parsed_line = start.parse_line( '46.105.14.53 ...
from rdflib import Namespace, Graph, Literal, RDF, URIRef from rdfalchemy.rdfSubject import rdfSubject from rdfalchemy import rdfSingle, rdfMultiple, rdfList from brick.brickschema.org.schema._1_0_2.Brick.Cooling_Max_Discharge_Air_Flow_Setpoint import Cooling_Max_Discharge_Air_Flow_Setpoint from brick.brickschema.org....
# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% # =========================================================================================================== # Load Imports and data # =========================================================================...
from person import Person # instantiate Person objects john = Person("john", 28) amy = Person("amy", 32) # print objects (uses the __str__ method) print(john) print(amy)
#!/usr/bin/env python # -*- coding: utf-8 -*- __author__ = 'WindSing' ####################################### 一些说明 ####################################################################### ####################################### 导入模块 ####################################################################### import sys impo...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ This code calculates the reconstructions for the MUSIC dataset using ODL library and ADMM TV. each energy channels is reconstucted separately and number of iterations is set to 2000, and regulatization to 0.8. """ import numpy as np import matplotlib.pyplot as plt im...
# 滑动窗口,从字典里找下一个窗口的start class Solution: def lengthOfLongestSubstring(self, s: str) -> int: d = {} start = 0 r = 0 for i, c in enumerate(s): if c in d and d[c] >= start: start = d[c] + 1 d[c] = i else: d[c] = i ...
from django.db import models # Create your models here. These will be created in the sql database. # for each of these I can set an option of primary_key=True in order to make that field the unique identifier. class Site(models.Model): account_name = models.CharField(max_length=250) # account/site name account_id ...
#!/usr/bin/env python import sys import numpy as np import math import itertools import matplotlib.pyplot as plt vcf = open(sys.argv[1]) freq = [] for i in vcf: if i.startswith("#"): continue line = i.rstrip("\t\n").split() af = line[7].split(";") af1 = af[3][3:] if "," in af1: a...
#MULTILEVEL INHERITANCE class Parent: def assign_name(self,name): self.name=name def show_name(self): return self.name class Child(Parent): def assign_age(self,age): self.age=age def show_age(self): return self.age class GrandChild(Child): def assign_gender(self,gen...
#encoding=utf-8 import threading import random import time from Queue import Queue from collections import deque MAX_NUM = 3 cond = threading.Condition() class Producer(threading.Thread): def __init__(self, threadname, queue): threading.Thread.__init__(self, name = threadname) self.sharedata = queue ...
from typing import Optional from flask import request from flask_login import current_user # type: ignore from peewee import fn # type: ignore from lms.lmsdb.models import ( Comment, CommentText, Exercise, Role, Solution, SolutionFile, User, ) from lms.models import solutions from lms.models.errors import ( ...
import random import requests from flask import request as req, redirect, session, url_for from flask_oauth import OAuth from settings import * oauth = OAuth() facebook = oauth.remote_app('facebook', base_url='https://graph.facebook.com/', request_token_url=None, access_token_url='/oauth/access_token', ...
""" @author: Nathanael Jöhrmann """ import glob import os from enum import Enum, auto from pathlib import Path import numpy as np import pi88reader.tdm_importer as tdm def main(): """ Called at end of file, if __name__ == "__main__" """ import pi88reader.pi88_to_pptx as pi88_to_pptx # import PI88To...
# Generated by Django 2.2.4 on 2019-09-09 03:57 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('labo...
from demo_opts import get_device from luma.core.render import canvas import time device = get_device() import smbus import math def read_byte(adr): return bus.read_byte_data(address, adr) def read_word(adr): high = bus.read_byte_data(address, adr) low = bus.read_byte_data(address, adr+1) val = ((high...
import logging class MailBox: def __init__(self): # {entity: {message_key: value}} # {entity: {message_key: []} self.inbox = {} self.outbox = {} def drop(self): if self.outbox: logging.error(f"Outbox should be empty: {self.outbox}") self.outbox ...
from flask import current_app, request from datetime import datetime from itsdangerous import TimedJSONWebSignatureSerializer as Serializer import hashlib from recommendation import db, login_manager, bcrypt from flask_login import UserMixin @login_manager.user_loader def load_user(user_id): return User.query.ge...
#----------------------------------------------------------------------------- """ Command Line Interface Implements a CLI with: * hierarchical menus * command tab completion * command history * context sensitive help * command editing Notes: Menu Tuple Format: (name, submenu, description) - submenu (name, leaf...
#!/usr/bin/env python # # Copyright 2010 Google Inc. # # 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 o...
from django.shortcuts import render,redirect from .forms import CompanyForm,EmployeeForm,StudentResultForm,StudentDetailsForm from .models import Employee,Company,StudentResult,StudentDetails from .utils import get_plot from django.contrib import messages from django.contrib.auth.models import User,auth #Home page...
# coding: utf-8 import cv2 import numpy as np import sys #defino el video your_path=sys.argv[1] your_destiniy_path=sys.argv[2] vidcap = cv2.VideoCapture(your_path) #calculo la cantidad de frames total_frames = str(int(vidcap.get(cv2.CAP_PROP_FRAME_COUNT))) #los nombres de las imagenes deben tener las misma cantidad d...
""" Author: Soumil Ramesh Kulkarni Question: There are 3 types of edits that can be performed on a string, 1) Insert a character, 2) Delete a character, 3) Replace a character. Given 2 strings, write a function to check if they are one edit away (or zero edit away) eg: pale, ple -> true pales, pale -> true p...
def arithmeti(first_number, second_number, operation): if operation == "+": return first_number + second_number elif operation == "-": return first_number - second_number elif operation == "*": return first_number * second_number elif operation == "/": retur...
from django.shortcuts import get_object_or_404 from django.http import HttpResponseForbidden from django.views.generic import ListView, DetailView, CreateView, UpdateView from django.contrib.auth.mixins import LoginRequiredMixin from django.db.models import Max from django.db.models.functions import Coalesce from djang...
import os import json from flask import Flask import feature_Prediction import feature_reachability import sentimental_analysis app = Flask(__name__) @app.route("/") def index(): """ Home page """ chart_data = {} return chart_data @app.route("/feature_pred/") def feature_pred(): chart_data ...
# plug encoder velocities (with different base vel) to balance controller from dynamic_graph.sot.core.operator import Selec_of_vector, Stack_of_vector # robot.q_fd = create_chebi2_lp_filter_Wn_03_N_4('q_filter', robot.timeStep, 36) from dynamic_graph.sot.torque_control.filter_differentiator import FilterDifferentiator...
import ssc32 import math import time ssc = ssc32.SSC32('/dev/ttyAMA0', 115200) ssc[2].position = 1300 ssc[2].min = 600 ssc[2].max = 2400 ssc[2].deg_max = +90.0 ssc[2].deg_min = -90.0 ssc[2].degrees = -45.0 ssc.showversion() ssc.commit(time=2000) while not ssc.is_done(): time.sleep(0.1) ssc[2].degrees = 0 ssc.comm...
#!/usr/bin/python3 from sys import argv import requests import json import getpass from apscheduler.schedulers.blocking import BlockingScheduler id = 0 def get_user_info(): key = input('\nVisit: https://intranet.hbtn.io/dashboards/my_tools\nand enter your API Key from the bottom of the page: \n') print() user_i...
from tensorflow.keras.models import load_model from tensorflow.keras.preprocessing.image import load_img, img_to_array import numpy as np from flask import Flask, request, render_template from werkzeug.utils import secure_filename import os, sys, glob, re app = Flask(__name__) model_path = "SoilNet_93_86...
import pytest from notifications import email class NotificationMissingProperties(email.NotificationBase): pass def test_notification_base_rejects_if_required_properties_missing(): with pytest.raises(TypeError) as exc_info: NotificationMissingProperties() assert exc_info.exconly() == ( ...
import DBMS ############### ### Расходы ### ############### #%% Создаем сообщение. raw_message = 'Бананы - 150' # Проверка на наличие такого продукта в БД. product = DBMS.product_exist(raw_message) # Если БД пустая, то вернётся товар с полем category=None. print(product) #%% Добавляем категорию для данного товара ...
import serial from car import AutonomousCar from pin_declarations import * import pickle from functions import * import RPi.GPIO as GPIO GPIO.setmode(GPIO.BCM) for pin in MOTORL_PINS: GPIO.setup(pin, GPIO.OUT) for pin in MOTORR_PINS: GPIO.setup(pin, GPIO.OUT) ser = serial.Serial('/dev/ttyS0', 9600, timeout...
def bintree(n): global cnt if n <= N: bintree(n*2) tree[n] = cnt cnt += 1 bintree(n*2+1) T = int(input()) for tc in range(1, T+1): N = int(input()) tree = [0 for _ in range(N+1)] cnt = 1 bintree(1) print(f'#{tc} {tree[1]} {tree[N//2]}')
# NOTE: CREATE INSERT STATEMENTS FOR THE LOGGING DATA # INSERT FUNCTION def insert_function_basic_transcript_info_table(mydb, url, pub_date, ticker, title, text): mycursor = mydb.cursor() sql_command = '''INSERT INTO BASIC_TRANSCRIPT_INFO (URL, PUBLICATION_DATE, TICKER, TITLE, TEXT...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ The color detector module ========================= Used to manage the detection of the color of the road. """ import cv2 import numpy as np class ColorFilter: """ This class provides a simple method for color filtering based on the HSV color...
t = int(input()) for qq in range(t): l1 = list(map(int, input().split())) l2 = list(map(int, input().split())) incorrect = [] signMismatch = 0 # checking move-less success if l1 == l2: print("0") continue possByAdd = True possByMulti = False for i in range(3): ...
import pytest from taichi.lang.misc import get_host_arch_list import taichi as ti from tests import test_utils @test_utils.test() def test_fibonacci(): @ti.kernel def ti_fibonacci(n: ti.i32) -> ti.i32: a, b = 0, 1 # This is to make the inner for loop serial on purpose... for _ in rang...
""" The ISONet module, which is based on the ResNet module, from https://github.com/HaozhiQi/ISONet/blob/master/isonet/models/isonet.py (based on https://github.com/facebookresearch/pycls/blob/master/pycls/models/resnet.py) """ import numpy as np import torch import torch.nn as nn import torch.nn.functional as F # St...
import serial from transform import Transform class Move: def __init__(self, b, c, port='/dev/ttyUSB0', baudrate=19200): self.m1 = 0 self.m2 = 0 self.m3 = 0 self.offset_m1 = 0 self.offset_m2 = 24 - 90 # 90 self.offset_m3 = 180 - 61 # 180 self.ser = serial....
# Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. import os from pathlib import Path from typing import Any import pytest import timm import torch import torch.nn as nn import torchvision from hydra.utils import instantiate from lightning.pytorch import Trainer from omegaco...
# pylint: disable=unused-argument # pylint: disable=redefined-outer-name # pylint: disable=line-too-long import pytest from helpers.cluster import ClickHouseCluster cluster = ClickHouseCluster(__file__) node = cluster.add_instance( "node", main_configs=["configs/remote_servers.xml"], stay_alive=True ) @pytest...
import matplotlib.pyplot as plt import numpy import os import pylab import sys from mpl_toolkits.mplot3d import Axes3D from matplotlib import cm from matplotlib.ticker import LinearLocator, FixedLocator, FormatStrFormatter absolute_error_path_pattern = "/misc/projects/whisker/results/GWhiskerTracker_n=%i_p=%i_a=%i_g=%...
import pygame from collision.collision_shapes import CollisionRect from collision.collision_handling import CollisionNoHandler # Bullet class class Bullet(pygame.sprite.Sprite): def __init__(self, position, heading, angle, shooter, ttl, velocity, stage, image_map, collision_grid, collide_type, t...
from django.contrib import admin # Register your models here. from .models import personalInfo admin.site.register(personalInfo)
from distutils.core import setup from Cython.Build import cythonize setup( # ext_modules=cythonize("atoi_cython.pyx") ext_modules=cythonize("external_cython.pyx") )
import django.utils from django.contrib import admin from django.utils.encoding import force_text from django.forms.models import model_to_dict import main.models import main.utils from django.db.models import Q # This file is part of https://github.com/cpina/science-cruise-data-management # # This project was program...
from template.config import * '''The Page class provides low-level physical storage capabilities. In the provided skeleton, each page has a fixed size of 4096KB. This should provide optimal performance when persisting to disk as most hard drives have blocks of the same size. You can experiment with different size...
import codecs import numpy class Data_holder: def find_all(self, a_str, sub): start = 0 while True: start = a_str.find(sub, start) if start == -1: return yield start start += len(sub) # use start += 1 to find overlapping matches def __init__(s...
""" using constant to calculate the area of a circle """ import py200325.py200408.myconst as const # PI # P # PAI # calculate area # PI * r * r r = 6400 # area = py200325.py200408.myconst.PI * r * r area = const.PI * r * r print("area = ", area) # area = 128614400.0 # area = 128676618.24000001
import datetime import itertools class Note: last_id = itertools.count() def __init__(self,memo,tags=''): self.memo = memo self.tags = tags self.creation_date = datetime.date.today() self.id =next(self.last_id) def match(self,filter): list_words = self.memo.split() ...
# Generated by Django 3.1.4 on 2020-12-27 15:54 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('main', '0002_auto_20201227_1415'), ] operations = [ migrations.AlterField( model_name='booking', name='created_at', ...
import math N,K= list(map(int,input().split())) a = int(N/K) a1 = a*K a2 = (a+1)*K if N % K ==0: Num = 0 else: if abs(N%K) < abs((N%K)-K) : Num = abs(N%K) else: Num = abs((N%K)-K) print(Num)
#-*-coding:utf-8-*- import sys reload(sys) sys.setdefaultencoding('utf8') """ 给定一个无序的列表,求解topk个元素输出 input: [1,3,6,3,4,7,9],3 output:[6,7,9] """ def qSort(arr): if len(arr) > 0: return qSort([i for i in arr[1:] if i <= arr[0]]) + \ [arr[0]] + qSort([i for i in arr[1:] if i >= arr[0]]) else: ...
# usage: # python PrintHeapMax.py -l 50 xxx.heap # print liveBytes >= 50 bytes callstacks import sys import argparse import HeapProfileParser import HeapProfileAddressTable if __name__ == '__main__': ap = argparse.ArgumentParser(description='Print callstacks that liveBytes >= LIMIT Bytes') ap.add_argument('-l'...
# Copyright (c) ONNX Project Contributors # # SPDX-License-Identifier: Apache-2.0 import numpy as np import onnx from onnx.backend.test.case.base import Base from onnx.backend.test.case.node import expect class Conv(Base): @staticmethod def export() -> None: x = np.array( [ ...
# Author: Dylan Tong, AWS import json import os from time import gmtime, sleep, strftime, time from urllib.parse import urlparse import boto3 class TaskTimedOut(Exception): pass class AutoMLManager() : def __init__(self, drivers=None) : if not drivers : drivers = { "s3":...
from keras.models import Sequential from keras.layers.core import Flatten, Dense, Dropout from keras.layers.convolutional import Convolution2D, MaxPooling2D, ZeroPadding2D from keras.optimizers import SGD import cv2 import numpy as np import h5py import os def VGG_16_pretrain(weights_path=None, img_width=128, img_heig...
import codecs import db import logging import sys import re logger = logging.getLogger('peewee') logger.setLevel(logging.CRITICAL) logger.addHandler(logging.StreamHandler()) def add_date(): db.Date(date_id="%s-%s-%s" % (year, month, day)).save() def add_items(items): date = db.Date.get(date_id="%s-%s-%s...
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import unicode_literals import re import sys from sh import git, ErrorReturnCode from .colors import red, green, highlight from .core import FILE_TYPES from .plugins import Command _HOOKS = {} class MetaHook(type): def __new__(mcs, name, bases, att...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Python 3.5.3 from math import sin, pi import matplotlib.pyplot as plt import numpy as np def trapezoidal(f, a, b, n): h = float(b - a) / n result = 0.5 * (f(a) + f(b)) for i in range(1, n): result += f(a + i * h) result *= h return result ...
import pandas as pd import numpy as np from smurf2_headers import * from smurf2_utills import * import os import traceback import pandas as pd from optparse import OptionParser, OptionGroup import sys import matplotlib.pylab as pylab params = {'legend.fontsize': 12, 'figure.figsize': (15, 5), 'axes...
socketio = require('socket.io') io = socketio.listen(3000) def on_connection(socket): def on_send_message(msg): nonlocal socket socket.broadcast.emit('newMessage', msg) console.log('Sending message', msg) def on_disconnect(): console.log('user disconnected') ...
i = 1 while True: n = int(input()) if n == 0: break maiores = [] maior = 0 for j in range(n): codigo, media = map(int, input().split()) if media > maior: maiores.clear() maiores.append(codigo) maior = media ...
# -*- coding: utf-8 -*- """ Created on Thu Apr 9 14:55:30 2020 @author: WFS """ import numpy as np import pandas as pd from preparets import preparets import argparse import tensorflow as tf from sklearn import preprocessing from train_test_split_meta1 import train_test_split_meta1 import matplotlib.pypl...
# demo.py from model import * from player import Game from card import * NUMBER_CLUE = 0 COLOR_CLUE = 1 RED = 1 GREEN = 2 BLUE = 3 def live_demo(): print("Possible cards: R1 x 3, R2 x 2, R3 x 1, G1 x 3") print("Give a starting hand with 6 of the possible cards:") hands = input() g, model = init2(hands) # highe...
def divisible(): lis=[] for i in range(2000,3200): if i%7==0 and i%5!=0: lis.append(i) return lis if __name__=="__main__": l=divisible() print l
#!/usr/bin/env python import numpy as np import cv2 if __name__ == '__main__': arr = np.random.rand(512, 512) * 255 print("arr {} | {} -- {} | {}".format(arr.shape, np.amin(arr), np.amax(arr), arr.dtype)) cv2.imwrite("arr.jpg", arr)