text
stringlengths
8
6.05M
from Training.Trainer import Trainer class Generative_Replay(Trainer): def __init__(self, model, args): super(Generative_Replay, self).__init__(model, args) def generate_dataset(self, ind_task,sample_per_classes, classe2generate, Train=True): if self.conditional: return self.mode...
import random articles = ('A', 'The') nouns = ('Boy', 'Girl', 'Bat', 'Ball') verbs = ('hit', 'saw', 'liked') prepositions = ('with', 'by') def sentence(): return nounPhrase() + ' ' + verbPhrase() def nounPhrase(): return random.choice(articles) + ' ' + random.choice(nouns) def verbPhrase(): return rando...
# functionality to make a climatology from the daily file made by SNAP through interpolation if __name__ == '__main__': import os import xarray as xr import numpy as np import argparse # parse some args parser = argparse.ArgumentParser( description='make a climatology NetCDF file of Sea Ice Co...
def fibonacci(n): """Returns None for 0, 0 for 1st sequence, 1 for 2nd sequence, or else returns the nth sequence of the series :param integer (nth sequence of series) :type integer :rtype integer """ return None if n <= 0 else 0 if n == 1 else 1 if n == 2 else (fibonacci(n-1)+fibonacci(n-2)) d...
import os import simplejson as json import re """ Helper functions used in various steps of websubmit/modify. Collect functions that are used in various stages of websubmit here, e.g. to handle the shuffeling of files necessary for websubmit, processing of hgf-structures to/from JSON. Note that curdir generally refer...
import pylab from numpy import * from numpy.fft import * max_t = 128e-15 #s num_p = 128 t_fwhm = 10e-15 #s GVD = 362e-30 #s t = arange(-max_t,max_t,2*max_t/num_p) #freqs = 2*pi*arange(-1/max_t/2.,1/max_t/2.,1/max_t/num_p) #freqs = roll(freqs,num_p/2) freqs = 2*pi*fftfreq(num_p,2*max_t/num_p) t_sigma = t_fwhm/2....
'''Cluster boxes to K centroids with K-means. Note: The actual anchor boxes used is from the Darknet config file: yolo-voc.cfg anchors = [(1.3221, 1.73145), (3.19275, 4.00944), (5.05587, 8.09892), (9.47112, 4.84053), (11.2364, 10.0071)] What I get: anchors = [(0.6240, 1.2133), (1.4300, 2.2075), (2.2360, 4.3081)...
import time import sys import os sys.path.append(os.path.dirname(os.path.abspath(__file__))) from utils import load_config from probe import SIPProbe try: configuration = load_config() inventory = configuration['inventory'] default_ping = configuration['ping'] default_ping_interval = default_ping['int...
from flask import Blueprint auth = Blueprint('auth',__name__) from . import views,forms from flask_login import LoginManager login_manager = LoginManager() login_manager.session_protection = 'strong' login_manager.login_view = 'auth.login'
import collections from importplotfunctionsCR import * from inputplotdataCR import inputplotdict plotlist = ['figBrms_m12fhr','figBrms_m12mhr'] #plotlist = ['figBrms_m12bhr','figBrms_m12chr'] for plotneed in plotlist: inputplotdict[plotneed]['_plotfunction'](inputplotdict[plotneed])
from django.contrib import messages from django.http import HttpResponseRedirect,HttpResponse from django.shortcuts import render from django.urls import reverse from django.utils.translation import ugettext_lazy as _ from apps.teams.decorators import login_and_team_required, team_admin_required from apps.teams.util ...
from onegov.core.orm import Base from onegov.core.orm.mixins import ContentMixin from onegov.core.orm.mixins import TimestampMixin from onegov.core.orm.mixins import UTCPublicationMixin from onegov.core.orm.types import UUID from onegov.file import AssociatedFiles from onegov.gis import CoordinatesMixin from onegov.sea...
import numpy as np import cv2 def print_image(name_image, image): cv2.imshow(name_image, image) cv2.waitKey(0) cv2.destroyAllWindows() def convert_image_to_RGB(image): height, width = image.shape channels = 3 img_rgb = np.zeros((height, width, channels)) for ch in range(channels): ...
import pygame from pygame.sprite import Sprite from sprites import X, Y, InvalidMoveException, BLUE from sprites.characters.tank import TankCharacter, TANK_WIDTH MOVE_DISTANCE = 10 MOVE_COUNT_MAX = 100 MAX_ANGLE = 180 MIN_ANGLE = 0 MAX_POWER = 150 MIN_POWER = 0 LEFT = 0 RIGHT = 1 class Tank(Sprite): def __init...
import os import glob import cv2 import pickle import matplotlib import matplotlib.pyplot as plt import matplotlib.cm as cm import gzip import numpy as np import cv2 from sklearn.ensemble import RandomForestClassifier from skimage.io import imread from sklearn.metrics import accuracy_score target = [] images = [] for ...
import json def loadData(): filename1 = './data/Albadi_2018/Hate_Speech/test.json' filename2 = './data/Albadi_2018/Hate_Speech/train.json' with open(filename1) as f: content = f.readlines() with open(filename2) as f: content2 = f.readlines() content.extend(content2) content = [j...
from django.conf.urls import url from .views import redirect_url,api_root urlpatterns = [ url(r'^api/short/new', api_root, name='POST URL'), url(r'^(?P<tiny_id>[-\w]+)/$', redirect_url, name='Redirect URL'), ]
# flake8: noqa from .base import * DEBUG = True
#!/usr/bin/env python import roslib import rospy import smach import smach_ros import random # Example state machine that attempts to complete all tasks # Init state # Returns whether initialization completed or failed class Init(smach.State): def __init__(self): smach.State.__init__(self, outcomes=['c...
from django.shortcuts import render,HttpResponse,redirect from apps.user.models import * from apps.goods.models import * from apps.order.models import * import re from django.urls import reverse #反向解析 from django.views import View from itsdangerous import TimedJSONWebSignatureSerializer as Serializer from itsdangerous ...
from flask_cors import CORS from controllers import quiz_controller, answers_controller, questions_controller, student_courses_controller, student_questions_controller from controllers import course_controller from controllers import user_controller def route(app): quiz_controller.route(app) course_controller...
# -*- coding: utf-8 -*- # @Author: lc # @Date: 2017-09-08 09:20:58 # @Last Modified by: lc # @Last Modified time: 2017-09-19 21:30:35 import os os.environ['TF_CPP_MIN_LOG_LEVEL']='2' os.environ["CUDA_VISIBLE_DEVICES"] = '0' # decide to use CPU or GPU import time import json from datetime import datetime import cv...
# noqa from libvirt import Libvirt # noqa from docker import Docker # noqa
import sys # 홀수 # 7개의 자연수 중 홀수인 것들의 합 # 이 7개의 홀수들 중에서 최솟값 number = [] odds = [] for _ in range(7): N = int(sys.stdin.readline().rstrip()) number.append(int(N)) sum = 0 for i in range(len(number)): if number[i] % 2 != 0: sum += int(number[i]) odds.append(int(number[i])) # ...
#!/usr/bin/python #\file plan_2d_grasp3.py #\brief Planning grasping on 2D. # Objects are given as polygons. # Gripper has two fingers that are rectangles. # Using plan_2d_grasp2.py, grasping parameter is planned with CMA-ES. #\author Akihiko Yamaguchi, info@akihikoy.net #\version 0.1 #\da...
""" _InsertComponent_ MySQL implementation of UpdateWorker """ __all__ = [] import time from WMCore.Database.DBFormatter import DBFormatter class UpdateWorker(DBFormatter): sqlpart1 = """UPDATE wm_workers SET last_updated = :last_updated """ sqlpart2 = """WHERE compon...
# -*- coding: utf-8 -*- import crochet import fido.exceptions import pytest from mock import Mock from bravado.fido_client import FidoFutureAdapter def test_eventual_result_not_cancelled(): mock_eventual_result = Mock() adapter = FidoFutureAdapter(mock_eventual_result) adapter.result() assert mock_e...
#TODO """ Likes and comment Create Index Page Email Verification Discussion """
# Librerias Future from __future__ import unicode_literals # Librerias Django from django.contrib.auth.mixins import LoginRequiredMixin from django.shortcuts import render from django.views.generic import DetailView, ListView # Librerias de terceros from apps.website.submodels.post import PyPost def index(request):...
from paste.deploy import loadapp import os from wsgiref.simple_server import make_server config = "python_paste.ini" appname = "common" wsgi_app = loadapp("config:%s" % os.path.abspath(config), appname) server = make_server('localhost',80,wsgi_app) server.serve_forever()
pygameWindowWidth = 600 pygameWindowDepth = 600
# -*- coding: utf-8 -*- import os from functools import partial from collections import defaultdict from irc3.utils import slugify from irc3.utils import maybedotted from irc3.dcc.client import DCCChat from irc3.dcc.client import DCCGet from irc3.dcc.client import DCCSend DCC_TYPES = ('chat', 'get', 'send') class DC...
""" Provides a trivial likelihood factory function for testing purposes. """ from . import lkmodule def build_likelihood(_): """Return an EmptyLikelihood object.""" return lkmodule.empty_likelihood()
def handle_page_timeout(driver): timeout_button = driver.find_elements_by_xpath("//a[contains(@onclick, 'location.reload(true);')]") if len(timeout_button) > 0: end_wait = random.randint(1, 60) start_wait = time.time() duration_wait = 0 while end_wait > duration_wait: duration_wait = time.time() - start_wa...
class Solution: def divide(self, dividend, divisor): """ :type dividend: int :type divisor: int :rtype: int """ if dividend == -2**31 and divisor == -1: return 2**31-1 if dividend > 2**31-1 or dividend < -2**31 or divisor > 2**31-1 or divisor < -2*...
import sys import pydot from grammars_utils import Grammar, is_regular_grammar, Epsilon, build_grammar from grammars_utils import Item class NFA: def __init__(self, states: int, finals: iter, transitions: dict, start=0): ''' :param states: representa en número de estados del autómata...
s1={1,2,3,4,5,66,11,83,76} prime=set() nonprime=set() for i in s1: if i>1: for j in range(2,i): if i%j==0: nonprime.add(i) break else: prime.add(i) print(prime) print(nonprime)
#!/usr/bin/python def func1(): print( "myModule1::mySubModule1::func1 called" ) def func2(): print( "myModule1::mySubModule1::func2 called" ) class myClass( object ): def run( self ): print( "myModule1::mySubModule1::myClass::Run method called" ) def printName( self ): print( "myModul...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Feb 27 11:05:07 2019 @author: 3602786 """ import numpy as np import time import os ########## Exercice 2 ########### def nb_VarProp(ne,nj): return nj*ne**2 def K(ne,nj,j,x,y): return j*(ne**2)+x*ne+y+1 def resolution(k,ne): j = (k-1)//(...
import webapp2 from gramp import Gramp class MainPage(webapp2.RequestHandler): def get(self): gramp = Gramp() idiom = gramp.get_idiom() self.response.headers['Content-Type'] = 'text/plain' self.response.write(idiom) app = webapp2.WSGIApplication([ ('/', MainPage), ], debug=True)
x = [[12,7,3], [4,5,6], [7,8,9]] y=[[1,2,3], [2,1,3], [6,7,8]] z=[[0,0,0], [0,0,0], [0,0,0]] for i in range(len(x)): for j in range(len(x[0])): z[i][j]=x[i][j]+y[i][j] for r in z: print(r)
##!/usr/bin/python # -*- coding: utf-8 -*- # @author: xxx #python library:什么是库???利用程序员之前的工作,就是使用库(其他人写过的代码)去做其他的程序。 #应用外部的库画了一个乌龟 import turtle#引入外部的库 def main(): #设置一个画面 windows=turtle.Screen() #设置背景 windows.bgcolor('pink') #生成一个黄色乌龟 bran=turtle.Turtle()#Turtle是一个类!!!引入Turtle,调用turtle里面的类,实例化,形成一个叫BRAN的乌龟 #一个...
# -*- coding: utf-8 -*- from odoo import fields, models class DiscountContractCloseReason(models.Model): _name = 'discount.contract.close_reason' _description = 'Discount Contract Close Reason' name = fields.Char(required=True, translate=True) active = fields.Boolean(default=True) sequence = fie...
from typing import List import math def checkio(a: int, b: int, c: int) -> List[int]: if a+b > c and a+c > b and b+c > a: angle1 = math.degrees(math.acos((a**2 + b**2 - c**2)/(2.0 * a * b))) angle2 = math.degrees(math.acos((a**2 + c**2 - b**2)/(2.0 * a * c))) angle3 = math.degrees(math.acos((c**2 + b**2 ...
"""A Flask-based api implemented with GraphQL and basic authentication. Usage: flask run Attributes: app: A flask Flask object creating the flask app """ import os from flask import Flask from auth import AuthGraphQLView from models import setup_db from schema import schema app = Flask(__name__) setup_db(app) ...
import re for _ in range(int(input())): s = input() if re.search(r'([A-Z].*){2}', s) and re.search(r'(\d.*){3}', s) \ and re.match(r'^[a-zA-Z\d]{10}$', s) and not re.search(r'(\w).*\1', s): print('Valid') else: print('Invalid')
#String a = "Mehedi" b = "Amin" #c = a + b print(a,b,100)
from django.shortcuts import render from django.shortcuts import render, redirect, get_object_or_404, render_to_response, HttpResponse from django.contrib.auth import authenticate, login from django.contrib.auth.decorators import login_required from django.template import RequestContext #Import Models from models impo...
# Copyright The OpenTelemetry Authors # # 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 to in ...
def do_delete(rq_id, rq_name, rq_activities): status = 200 d_json = {'id': rq_id, 'name': rq_name, 'activities': rq_activities, 'type' : 'person'} d_response = {'status': status, 'json': d_json} return d_response
N = int( input()) C = [ int( input()) for _ in range(N)] dp = [1]*(N+1) colors = [1]*(2*10**5+1) S = [-1]*(2*10**5+1) Q = 10**9+7 for i in range(N): if i >= 1: if C[i] == C[i-1]: dp[i+1] = dp[i] continue if S[C[i]] == -1: dp[i+1] = dp[i] S[C[i]] = 1 if i >...
from setuptools import setup #with open('requirements.txt') as f: #requirements = f.read().splitlines() setup( name='C3D_gait', author='Michael Jeffryes', author_email='mike.jeffryes@hotmail.com', url='', version='1.1.0', description='Extracts gait data from C3D files', #packages=['gps...
# Author : Xiang Xu # -*- coding: utf-8 -*- def filter_users_with_checkintimes(mintCheckinTimes): users = [] with open('checkintimes.txt', 'r') as f: for line in f: token = line.strip().split('\t') if int(token[1]) >= mintCheckinTimes: users.append(int(token[0])...
def answer(start, length): # define a function f(n) to calculate 1^2^3^...^n # because 4m+3 ^ 4m+2 = 1 and 4m+1 ^ 4m = 1 # 4m+3 ^ 4m+2 ^ 4m+1 ^ 4m = 0 # therefore f(4m+3) = f(3) = 0 # f(4m+2) = f(4m+3) ^ 4m+3 = 0 ^ 4m+3 = 4m+3 # f(4m+1) = f(4m+2) ^ 4m+2 = 4m+3 ^ 4m+2 = 1 # f(4m) = f(4m+1) ^ ...
from django.contrib import admin from .models import Person # Username: admin, Password: administrador. admin.site.register(Person)
from scipy import stats as s from scipy import special as ss import numpy as np from statsmodels.stats import multicomp, anova import pandas as pd df = pd.read_csv('/datasets/genetherapy.csv') df2 = pd.read_csv('/datasets/atherosclerosis.csv') """quartiles""" np.percentile([1,2,3], 50) """t-distribution""" stat, pva...
import math import collections def solve(data): ring = [1] * data solved = 0 while not solved: if ring.count(len(ring)) == 1: solved = 1 break for elf_num in range(len(ring)): elf = ring[elf_num] if elf == 0: pass e...
""" IN: s3://spark-job-cluster-bucket/input/customers.csv OP: s3://spark-job-cluster-bucket/output/ spark-submit --deploy-mode cluster --master yarn script.py s3://spark-job-cluster-bucket/input/customers.csv s3://spark-job-cluster-bucket/output/ """ from __future__ import print_function from pyspark.sql impo...
import sys import time import pyfirmata2 port = '/dev/ttyACM0' leonardo = { 'digital': tuple(x for x in range(14)), 'analog': tuple(x for x in range(6)), 'pwm': (3, 5, 6, 9, 10, 11, 13), 'use_ports': True, 'disabled': (0, 1) # Rx, Tx, Crystal } try: print("Initiali...
# https://www.reddit.com/r/dailyprogrammer/comments/wjzly/7132012_challenge_76_easy_title_case/ def titlecase(input, exception): words = input.split() output = [words[0].title()] for word in words[1:]: if word.lower() in exception: output.append(word.lower()) else: o...
#coding:utf-8 permission_required(perm, login_url=None, raise_exception=False) from django.contrib.auth.decorators import permission_required @permission_required('polls.can_vote') def my_view(request): #PermissionRequiredMixin from django.contrib.auth.mixins import PermissionRequiredMixin class MyView(Permiss...
''' Problem Statement # We are given an unsorted array containing ‘n’ numbers taken from the range 1 to ‘n’. The array has some duplicates, find all the duplicate numbers without using any extra space. Example 1: Input: [3, 4, 4, 5, 5] Output: [4, 5] Example 2: Input: [5, 4, 7, 2, 3, 5, 3] Output: [3, 5] ''' def ...
Import('env') Import('path') import os currentPath = path #VariantDir("..\\build", '.\\', duplicate=0) # Gets all the .cpp and.h files and puts them in a list srcs = os.walk(currentPath) #Array of objects objs = [] # Loops through source files for root, dirs, files in srcs: print("Files: " + str(files)) print(...
from flask import Flask, request, g, Response from auth import requires_auth import datetime, json, msgpack, os.path, sqlite3 app = Flask(__name__) app.config.from_object('config') insert_query = '''INSERT INTO utmp (host, user, uid, rhost, line, time, updated) VALUES (:host, :user, :uid, :rhost, ...
from ampel.pipeline.t0.DevAlertProcessor import DevAlertProcessor #from ampel.contrib.hu.t0.DecentFilter import DecentFilter from ampel.contrib.weizmann.t0.InfantFilter import InfantFilter from ampel.view.AmpelAlertPlotter import AmpelAlertPlotter import glob import json import logging import numpy as np import os imp...
import os from yacs.config import CfgNode as CN cfg = CN(new_allowed=True) # ---------------------------------------------------------------------------- # # TASK # 0->cls, 1->seg # ---------------------------------------------------------------------------- # cfg.TASK = CN(new_allowed=True) cfg.TASK.STATUS = 'train'...
from django.urls import path from products import views urlpatterns = [ path('list', views.product_list, name='create'), path('details/<int:id>', views.product_rud, name='details'), path('type', views.product_type_list, name='create'), path('prod_details/<int:id>', views.product_type_rud, name='create...
from typing import List from navmesh.polygon import Polygon class FloorPlan: def __init__(self, boundary: Polygon, obstacles: List[Polygon]): self.boundary = boundary self.obstacles = obstacles
## Author: shebang-rc import sys sys.setrecursionlimit(20000) # F(3223) is the limit before this thing crashes, so # that's why it takes the minimum of number specified # and 3223. def fibonacci(n, a=1, b=0): if n == 0: return b else: return fibonacci(n-1, a+b, a) def min(a, b): if a < b...
""" 如果你了解JavaScript或者PHP等,那么你一定对eval()所有了解。如果你并没有接触过也没关系,eval()函数的使用非常简单。 """ print(eval("1+1==2")) print(eval("'A'+'B'")) print(eval("1+2")) """ Python中eval()函数将字符串str当成有效的表达式来求值并返回计算结果。其函数声明如下: eval(expression[, globals[, locals]]) 其中,参数globals为字典形式,locals为任何映射对象,它们分别表示全局和局部命名空间。 如果传入globals参数的字典中缺少__builtins__的时...
from flask import request from flask_wtf import FlaskForm from wtforms import StringField, SubmitField, TextAreaField, SelectField, FloatField, BooleanField, IntegerField from wtforms.validators import ValidationError, DataRequired, Length from flask_babel import _, lazy_gettext as _l from app.models import User clas...
# #q1 not done dic1={1:10,2:20} dic2={3:30,4:40} dic3={5:50,6:60} dic4={} dic4.update(dic1) dic4.update(dic2) dic4.update(dic3) print(dic4)
from pkg_resources import resource_string from yandextank.common.interfaces import AbstractPlugin, AggregateResultListener, AbstractInfoWidget, GeneratorPlugin, AbstractCriterion from yandextank.plugins.Console import Plugin as ConsolePlugin from yandextank.plugins.Autostop import Plugin as AutostopPlugin from yandext...
'''Create test scene with plenty of example features to test. Created on 05/10/2019 @author: Bren ''' import os import fbx import FbxCommon from inspect import isclass from brenfbx.core import bfIO DUMP_DIR = r"D:\Repos\dataDump\brenfbx" TEST_EXPORT_FILE = os.path.join( DUMP_DIR, "brenfbx_test_scene_01.f...
#!/usr/bin/python # -*- coding: utf-8 -*- # @author: B17455 class day(): """docstring for day""" def __init__(self, day, time): self.day = day self.time = time def speed(self, distance,vehicle): speed = float(distance)/self.time print '------------------' print '%s骑%s去买菜,骑了 %s 小时,平均速度 %s km/h'%(self.day,...
# coding:utf-8 from pymongo import MongoClient import pymysql import numpy as np from publicMethods import * #载入汽车之家数据,并计算每辆车的提及数量以及构建共同提及矩阵 def loadCarCommentSet(carSet): client=MongoClient('47.92.211.251',30000) collection=client.new_carDataset.test totalCount=collection.find().count() print('一共包含数据%...
def gen(n): for i in range(n): yield i # g= gen(5) # # print(g.__next__()) # print(g.__next__()) # print(g.__next__()) # print(g.__next__()) # print(g.__next__()) # # s="Manan" # itr=iter(s) # print(itr.__next__()) # print(itr.__next__()) # print(itr.__next__()) # print(itr.__next__()) # print(itr.__next_...
class Square: def __init__(self, side): self.side = side def __add__(square_one, square_two): # special operator overloading method for + return (4 * square_one.side) + (4 * square_two.side) square_one = Square(5) # 5*4=20 square_two = Square(10) # 10*4=40 print("Sum of sides of both squa...
# Python 3.7 # File name: # Authors: Aaron Watt # Date: 2021-07-05 """Module to be imported for project settings.""" # Standard library imports from pathlib import Path # Third-party imports # Local application imports from . import tools # CLASSES -------------------------- class Paths: """Inner paths class ...
import pytest import torch from pytest_dl import model @pytest.fixture(scope="module", params=["cnn", "mlp"]) def net(request): if request.param == "cnn": return ( model.CNNVAE(input_shape=(1, 32, 32), bottleneck_dim=16), torch.randn(4, 1, 32, 32), ) elif request.param...
import logging logging.getLogger("scapy.runtime").setLevel(logging.ERROR) from scapy.all import * from support.Scapy_Control import * import sys, getopt if __name__== "__main__": dmac = GenerateRandomMac() smac = GenerateRandomMac() SIP = GenerateRandomIp() DIP = GenerateRandomIp() dport = 1812 ...
from django.db import models # Create your models here. class Message(models.Model): sender = models.CharField(max_length=50) text_message = models.TextField() sender_email = models.EmailField() sending_date = models.DateTimeField(blank=True, null=True) def __str__(self): return 'Сообщени...
#import urllib.request #import json import requests import pandas as pd pd.options.display.max_columns = 100 def get_park_list(key): headers = {"Authorization": key} endpoint = "https://developer.nps.gov/api/v1/parks" # Sample non-working Python code from # https://github.com/nationalparkservice/nps...
from functools import cached_property from onegov.org.request import OrgRequest class FsiRequest(OrgRequest): @cached_property def attendee(self): return self.current_user and self.current_user.attendee or None @cached_property def attendee_id(self): return ( self.attende...
import tensorflow as tf from tensorflow.python.ops.rnn_cell import GRUCell from tensorflow.python.platform import flags FLAGS = flags.FLAGS class LSTMAutoencoder(object): def __init__(self, hidden_num, input_num, cell=None, reverse=True, decode_without_input=False, name=None): self.name=name if c...
''' http://snowdeer.github.io/machine-learning/2018/01/09/recognize-mnist-data/ ''' from keras.datasets import mnist (X_train, Y_train), (X_validation, Y_validation) = mnist.load_data() print ("x_train shape : " , X_train.shape) def printTrainData(idx): for x in X_train[idx]: for i in x: ...
# A Floater is Prey; it updates by moving mostly in # a straight line, but with random changes to its # angle and speed, and displays as ufo.gif (whose # dimensions (width and height) are computed by # calling .width()/.height() on the PhotoImage # from PIL.ImageTk import PhotoImage from prey import P...
import random import datetime r = random.randint(1, 6) print(r) print(datetime.date.today()) import qrcode img = qrcode.make("http://kujiranand.com") img.save('qrcode-test.png')
import unittest from mongoengine.base.datastructures import StrictDict class TestStrictDict(unittest.TestCase): def strict_dict_class(self, *args, **kwargs): return StrictDict.create(*args, **kwargs) def setUp(self): self.dtype = self.strict_dict_class(("a", "b", "c")) def test_init(sel...
import pytest from raincoat.match import pypi def test_match_str(match): assert( str(match) == "umbrella == 3.2 @ path/to/file.py:MyClass (from filename:12)") def test_match_str_other_version(match): match.other_version = "3.4" assert( str(match) == "umbrella == 3.2 vs 3...
import cv2 import pcl import pcl.pcl_visualization import numpy as np import quaternion # camera intrinsics cx = 325.5 cy = 253.5 fx = 518.0 fy = 519.0 depthScale = 1000.0 colorImgs, depthImgs = [], [] pose = [] # read pose.txt pose = [] with open('pose.txt', 'r') as f: for line in f.readlines(): line = ...
list=["apple","banana","cherry","arange","kiwi","melon","mango",] list.clear() print(list)
import math class activationLayer: def __init__(self, activationFunc = None): print("New Activation Layer") if activationFunc == None: self.activation = activationLayer.empty else: self.activation = activationFunc def forwardPass(self, inputMat): return self.activation.forwardPass(inputMat) def com...
# -*- coding: utf-8 -*- """ Created on Thu Aug 5 13:34:57 2021 @author: Gustavo Godoy email: gustavogodoy85@gmail.com """ sentence = input('Por favor ingrese el texto a convertir en Geringoso: ') if sentence == '': sentence = 'Geringoso' word = '' new_sentence = sentence.split(' ') a_new_word = '' for word in ...
def _check_mode(mode): assert mode in ['training', 'inference'] def _check_shape(shape): ''' Image size must be dividable by 2 multiple times :param shape: (h, w) :return: None ''' h, w = shape if h / 2 ** 6 != int(h / 2 ** 6) or w / 2 ** 6 != int(w / 2 ** 6): raise Exception("...
from django.db import models # here my manager for registration come in action ''' class Any_Model_Manager(models.Manager): def search_box(self,keyword): for x in self.filter(name__icontains=str(keyword)): print(x) class Any_Model_Manager2(models.Manager): def search_acc_gender(self,gender...
#!/usr/bin/python # -*- coding: utf-8 -*- import smtplib def enviar(nombre, destinatario): msg = ''' Hola %s''' % nombre # Datos username = 'jose.vergara2104@gmail.com' password = 'slqiqlkgyeifcora' # Enviando el correo server = smtplib.SMTP('smtp.gmail.com:587') server.starttls() ...
import numpy as np from .base_policy import BasePolicy class MPCPolicy(BasePolicy): def __init__(self, env, ac_dim, dyn_models, horizon, N, **kwargs ): super().__init__(**kwargs) ...
import sys, aplpy import astropy.io.fits as fits import astropy.wcs import astropy.visualization as vis import matplotlib.pyplot as plt, numpy as np class FIGURE: def __init__(self, filename): self.filename = filename self.raw = fits.open(filename) self.data = self.raw[0].data self...
#!/bin/python import sys import copy import re import math infile = open(sys.argv[1], "r") dim = 0 NORTH = 0 EAST = 1 SOUTH = 2 WEST = 3 class Tile: def __init__(self, name, data): self.name = name self.north = data[0] self.south = data[-1] self.east = "" self.west = ""...