text
stringlengths
38
1.54M
import re from collections import defaultdict reg = defaultdict(int) subt = { 'inc': '+=', 'dec': '-=', 'if': 'if' } with open('input.txt') as file: for line in file: line = re.sub(r'^(.+)(if.+)$', r'\2:\1', line) line = re.sub(r'\b([a-z]+)\b', lambda m: subt.get(m.group(1), 'reg["{}"]...
from typing import List from collections import defaultdict class Solution: def countSubTrees(self, n: int, edges: List[List[int]], labels: str) -> List[int]: """ William's solution treat this tree as a undiredted graph """ edge_dict = defaultdict(list) for a, b in...
first = "Josephia" last = "Jones" bros = 2 sises = 1 print(first + last) print(bros+sises) # this throws an error print(first + bros)
from django.shortcuts import render,HttpResponse from rest_framework import generics from .serializer import EmpSerializer,AccountSerializer from .models import Emp,Account def home(request): return HttpResponse("<h1>Welcome To Django RestProject</h1>") # Insert Data class CreateEmp(generics.CreateAPIView): s...
class OMG : def print() : print("Oh my god") >>> >>> myStock = OMG() # OMG.print(mystock) 가 돼야함. >>> myStock.print()
#! /usr/bin/env python import i3ipc import time hide_border_delay = .1 i3 = i3ipc.Connection() def on_window_focus(i3, event): window_id = event.container.props.id i3.command('[con_id=' + str(window_id) + '] border pixel 1') time.sleep(hide_border_delay) i3.command('[con_id=' + str(window_id) + '] border...
from abc import ABC, abstractmethod class Gate: def __init__(self, gate_id, attendent): self.gate_id = gate_id self.attendent = attendent class EntranceGate(Gate): def __init__(self, gate_id, attendent): super().__init__(gate_id, attendent) def process_ti...
# This function is used to calculate the size of a given sbox def SboxSize(sbox): s = format(len(sbox), "b") num_of_1_in_the_binary_experission_of_the_len_of_sbox = s.count("1") assert num_of_1_in_the_binary_experission_of_the_len_of_sbox == 1 return (len(s) - 1) # Return the value of the bitproduct function Pi_u...
from datetime import date from django.core.exceptions import ValidationError from django.test import TestCase from apps.general_services.validators import person_validation, id_validators, general_validation class TestValidation(TestCase): # GENERAL VALIDATION def test_valid_phone_number_1(self)...
#!/usr/bin/env python import os import sys import commands BLOCK_SIZE = 4096 #AdjustPartitionSizeForVerity.results = {} def GetVerityMetadataSize(partition_size): cmd = "./bin/build_verity_metadata.py -s %d" cmd %= partition_size status, output = commands.getstatusoutput(cmd) if status: print output ...
from math import* p=int(input("Insira a vida inicial:")) D1=int(input("Insira o primeiro valor do dado:")) D2=int(input("insira o segundo valor do dado:")) a= (sqrt(5*D1)) + ((pi)**(D2/3)) dano= p-a+1 print(int(dano))
# -*- coding: utf-8 -*- """ Created on Tue Oct 6 20:12:50 2020 @author: Erika Montana """ from ..utils import sql_utils as sql def main(conn, label_config, table_name, start_date, end_date, preprocessing_prefix): """ Creates table in destination schema containing the primary key and t...
import os import csv # You will be give a set of poll data called election_data.csv. The dataset is composed of three columns: #Voter ID, County, and Candidate. Your task is to create a Python script that analyzes #the votes and calculates each of the following: #The total number of votes cast #A complete list of ca...
from typing import List class Solution: def maxProfit(self, prices: List[int], fee: int) -> int: size = len(prices) hold, free = [0] * size, [0] * size hold[0] = -prices[0] for i in range(1, size): hold[i] = max(hold[i - 1], free[i - 1] - prices[i]) free[i] =...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Feb 16 13:06:18 2018 @author: jlaplaza """
# dictionaries: uses key-value pairs myCat = {'size': 'fat', 'color': 'gray', 'disposition': 'loud'} myCat['size'] # 'fat' 'My cat has' + myCat['color'] + 'fur.' # 'My cat has gray fur.' spam = {12345: 'Luggage combination', 42: 'The Answer'} # dictionaries are different than lists [1, 2, 3] == [3, 2, 1] # F...
""" Test suite for the django_project.context_processors module """ import pytest from django.contrib.auth.models import User from django.core.urlresolvers import reverse from django.test import RequestFactory from django_project import context_processors pytestmark = pytest.mark.django_db class LDAPUserMock: ld...
from datetime import datetime class Util: @staticmethod def iso_to_unix(dt_format: str) -> int: utc_dt = datetime.strptime(dt_format, '%Y-%m-%dT%H:%M:%S.%fZ') # Convert UTC datetime to seconds since the Epoch timestamp = (utc_dt - datetime(1970, 1, 1)).total_seconds() return i...
''' Тестові варіанти для лінійного алгоритму пошуку ''' import timeit import numpy as np test = [[np.array([5, 8, 9, 3, 7, 6, 4, 2, 1]), 7], [np.array([1, 7, 6, 9, 10, 3, 4, 5]), 8], \ [np.array([1, 18, 15, 7, 13, 11, 6, 2, 0, 9, 11, 10, 17, 15, 20, 3, 4, 5]), 20], \ [np.array([9, 7, 14, 3, 4, 17, 20, 1...
import multiprocessing import time import gym import gym3 import numpy as np from gym.vector import make as make_vec_env from procgen import ProcgenGym3Env population_size = 112 number_env_steps = 1000 def run_episode_full(u): env = gym.make('procgen:procgen-heist-v0') obs = env.reset() reward = 0 ...
#!/usr/bin/env python # -*- coding: utf-8 -*- import json from alipay.aop.api.constant.ParamConstants import * class PointLibResult(object): def __init__(self): self._balance = None self._library_id = None self._library_name = None self._status = None self._sum_point = No...
def solve(x1, x2, v1, v2): if v1 <= v2: return False t = float(x1-x2)/float(v2-v1) if t-int(t) == 0 and t > 0: return True return False x1, v1, x2, v2 = map(int,raw_input().split()) print solve(x1, x2, v1, v2)
import pandas as pd import os from main import loadProjects,loadUsers from build_network import filterProjects,controlGroupAffiliation,filterNodes,generateNework def main(): net_path = 'results/cytoscapeFiles' people = loadUsers() groupAfilliation = controlGroupAffiliation(people)[['USERNAME','ML_GROUP']] pis = ...
from iinsta.entities.Asset import Asset from mongoengine.queryset import DoesNotExist from iinsta.mongo import db class AssetFacade(object): @staticmethod def get_by_ids(ids): return db.page.find({ '_id': {'$in': ids} }) @staticmethod def get(**kwargs): try: ...
import matplotlib.pyplot as plt lang=['Java', 'Python', 'PHP', 'JavaScript', 'C#','C++'] popularity=[22.2,17.6,8.8,8,7.7,6.7] plt.bar(lang,popularity,color=(0.2, 0.4, 0.6,0.6),edgecolor='blue') plt.xlabel('programing Languages') plt.ylabel('Popularity(%)') plt.title('Programing Language bar representation') plt.show(...
import sys import argparse parser = argparse.ArgumentParser() parser.add_argument('refs') args = parser.parse_args() ref_file = open(args.refs) sent_id = None ref = None j = 0 # index into the kbest list sent_count = 0 # count of sentences seen so far. This is usually equal to sent_id + 1, but not always! done = Fal...
from django.shortcuts import render,redirect from django.contrib import messages from django.contrib.auth.decorators import login_required from django.contrib.auth.models import User, auth from admin.song.models import Song # Create your views here.@login_required(login_url = 'user.login') def register(request): ...
#!/usr/bin/python3 """ Routing definitions for handling different urls """ from flask import Flask, render_template app = Flask(__name__) @app.route('/', strict_slashes=False) def say_hello(): """ Returns a string Returns: "Hello, HBNB!" """ return "Hello, HBNB!" @app.route('/h...
import random import matplotlib.pyplot as plt from ch9.knapsack.individual import Individual from ch9.knapsack.random_set_generator import random_set_generator from ch9.knapsack.toolbox import mutation_bit_flip def mutate(ind): mutated_gene = mutation_bit_flip(ind.gene_list) return Individual(mutated_gene) ...
from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm from .models import Profile class StudentRegisterForm(UserCreationForm): email = forms.EmailField() department=forms.CharField() roll_no=forms.IntegerField() course=forms.CharFie...
from num_user_movie import * from shuffle import * from train_test import * from id_map import * from build_matrix import * from fill_matrix import * from column_mean import * from normalize import * from numpy.linalg import svd from S_to_matrix import * from trim_rating import * from predict_ratings import ...
import argparse import torch def parse_args(): parser = argparse.ArgumentParser() parser.add_argument('--text', help='checkpoint file') parser.add_argument('--image', help='checkpoint file') parser.add_argument('--video', help='checkpoint file') parser.add_argument('--audio', help='checkpoint fil...
class Solution: def wiggleSort(self, nums: List[int]) -> None: """ Do not return anything, modify nums in-place instead. """ sorted_nums = list(sorted(nums)) i ,j = len(nums)-1, 1 while j < len(nums): nums[j] = sorted_nums[i] i, j = i-1, j+2 ...
# S3 details accessKey = "<your-amazon-access-key>" secretAccessKey = "<your-secret-amazon-access-key>" # a test bucket for running software tests on (i.e. it doesn't matter if tests delete or alter data in it) testBucket = "<your-test-bucket>"
# # @lc app=leetcode.cn id=179 lang=python3 # # [179] 最大数 # # https://leetcode-cn.com/problems/largest-number/description/ # # algorithms # Medium (36.27%) # Likes: 305 # Dislikes: 0 # Total Accepted: 32.1K # Total Submissions: 88.3K # Testcase Example: '[10,2]' # # 给定一组非负整数,重新排列它们的顺序使之组成一个最大的整数。 # # 示例 1: # #...
class Solution: def sortedSquares(self, A: List[int]) -> List[int]: if len(A) == 0: return [] neg = pos = 0 while pos < len(A): if A[pos] < 0: pos += 1 continue neg = pos - 1 break res = [] whil...
lista = [] for c in range(0,10): lista.append (int(input('Digite o número: ')) ) print(lista)
#!/usr/bin/env python """ Install treediff lib in local env: pip install requests git+https://github.com/learningequality/treediffer then run ./ricecookerdifferpoc.py to generate the detailed tree diff JSON and and print the diff in terminal. """ import argparse from contextlib import redirect_stdout impo...
class RDF: def __init__(self, filename=''): self.in_filename = filename self.fd = open(filename,'r') self.urls_serial = 0 self.read_urls = [] self.topics = {} def __enter__(self): #print 'Enter RDF' return self def __exit__(self, type, value, traceb...
def classify(values): """*values* should be a list of numbers. Returns a list of the same size with values 'even' or 'odd'.""" return ['odd' if value % 2 else 'even' for value in values]
""" Downloads image thumbnails from google image search. Please note that this is a quite simple implementation with some limitations. First of all it is only possible to download low res thumbnails. Also, you can download 20 thumbnails at max. If you need a more advanced solution please take a look at the serpAPI http...
from models.vae.cvae import CVAE from models.contrastive_learning.cl_encoder import ContrastiveLearningEncoder import torch from torch.nn import functional as F from torch.nn.utils import clip_grad_norm from torch.utils.data import DataLoader from torch.optim import Adam import wandb from tqdm import tqdm import time i...
# -*- coding: utf-8 -*- """ Created on Thu Mar 25 17:19:58 2021 @author: Alvin Set Manipulation – Part 1 Sedikit berbeda dengan tipe data list dan tuple, pada tipe data set terdapat cukup banyak fitur yang disediakan oleh bahasa Python. Tugas: Ketikkan potongan kode pada kolom Contoh Penggunaan di live code editor. ...
n=int(input()) s="123456789" for i in range(n):print("+"*i+s[:n-i]) for i in range(n):print(s[:n-i].rjust(n,"+"))
''' 2차원 평면 위의 점 N개가 주어진다. 좌표를 x좌표가 증가하는 순으로, x좌표가 같으면 y좌표가 증가하는 순서로 정렬한 다음 출력하는 프로그램을 작성하시오. 첫째 줄에 점의 개수 N (1 ≤ N ≤ 100,000)이 주어진다. 둘째 줄부터 N개의 줄에는 i번점의 위치 xi와 yi가 주어진다. (-100,000 ≤ xi, yi ≤ 100,000) 좌표는 항상 정수이고, 위치가 같은 두 점은 없다. solve) x,y 좌표를 2차원 배열에 매칭 시켜서 순환해서 찍는 것도 방법인듯 그냥 sorted를 사용하면 알아서 순서대로 정렬해주지만 lambda사용법을 익혀...
from __future__ import print_function import time from learning.utils import * from learning.log import * from torch.autograd import Variable import torch def train_loop_npn(models, data_loader, optimizers, lr_schedulers, epoch, args): for model in models: model.train() set_dropout_mode...
import os, json from flask import Flask, request, Response, send_file, make_response, jsonify from flask import render_template, url_for, redirect, send_from_directory from werkzeug import secure_filename from imanip import app, helpers def allowed_file(filename): return '.' in filename and \ filename.rsplit('.', 1...
import typing from typing import Any, Optional, Text, Dict, List, Type from rasa.nlu.components import Component from rasa.nlu.config import RasaNLUModelConfig from rasa.shared.nlu.training_data.training_data import TrainingData from rasa.shared.nlu.training_data.message import Message from spellchecker import SpellCh...
import pygame import os, sys import time import csv class bar(object): def __init__(self, amplitude, min_frequency, max_frequency, screen_height, color = [50, 50, 50]): """ Creates a rectangular bar object """ self.amplitude = amplitude self.min_frequency = min_frequency self.max_frequency = max_frequ...
#................................. image denoising .............................................................# def imageDenoising(gray): import numpy import cv2 from matplotlib import pyplot as plt # h : parameter deciding filter strength. Higher h value removes noise better, but removes details...
from setuptools import setup setup( name="wimpy", version="0.6", description="Anti-copy-pasta", long_description=open('README.rst').read(), url="https://github.com/wimglenn/wimpy", author="Wim Glenn", author_email="hey@wimglenn.com", license="MIT", packages=["wimpy"], options={"...
import numpy as np from numba import njit from numba.core.errors import TypingError import unittest from numba.tests.support import TestCase, force_pyobj_flags def build_map(): return {0: 1, 2: 3} def build_map_from_local_vars(): # There used to be a crash due to wrong IR generation for STORE_MAP x = Tes...
def check(r, c, size): return r >= 0 and r < size and c >= 0 and c < size def DFS(r, c, n): arr[r][c] = n x = [0, 0, -1, 1] y = [1, -1, 0, 0] for i in range(4): if check(r+x[i], c+y[i], N) and arr[r+x[i]][c+y[i]] == 1: DFS(r+x[i], c+y[i], n) N = int(input()) arr = [list(map(in...
# -*- coding: utf-8 -*- __author__ = 'florije' from api.basic_service import BaseService from api.models import TaskModel from api.schemas import TaskSchema from api.custom_exception import InvalidAPIUsage class TaskService(BaseService): def create_task(self, **params): new_task = TaskModel(title=params.g...
# Save the face of the user in encoded form # Import required modules import time import os import sys import json import configparser import builtins import cv2 import numpy as np from threading import Timer import csv import boto3 # Try to import dlib and give a nice error if we can't # Add should be the first poin...
# Copyright (c) OpenMMLab. All rights reserved. import unittest from unittest import TestCase import torch from parameterized import parameterized from torch import Tensor from mmdet.models.roi_heads.mask_heads import HTCMaskHead class TestHTCMaskHead(TestCase): @parameterized.expand(['cpu', 'cuda']) def t...
from tkinter import * from PIL import Image, ImageTk root = Tk() canvas = Canvas(width=500, height=500, bg='white') canvas.pack() image = Image.open("Trollface.jpg") photo = ImageTk.PhotoImage(image) canvas.create_image(250, 250, image=photo) root.mainloop()
#Building DataFrames with broadcasting ''' You can implicitly use 'broadcasting', a feature of NumPy, when creating pandas DataFrames. In this exercise, you're going to create a DataFrame of cities in Pennsylvania that contains the city name in one column and the state name in the second. We have imported the names of ...
from StringIO import StringIO import re from PIL import Image from django.conf import settings from django.db import models from django.core.urlresolvers import reverse from django.contrib.contenttypes.models import ContentType from django.contrib.contenttypes import generic from south.modelsinspector import add_intr...
# # @lc app=leetcode.cn id=865 lang=python3 # # [865] 具有所有最深节点的最小子树 # # https://leetcode-cn.com/problems/smallest-subtree-with-all-the-deepest-nodes/description/ # # algorithms # Medium (64.22%) # Likes: 122 # Dislikes: 0 # Total Accepted: 7.4K # Total Submissions: 11.5K # Testcase Example: '[3,5,1,6,2,0,8,null,...
"""generic training helpers. training.py and training_aux.py are mostly for CNN. """ import os.path import os from shlex import quote from collections import OrderedDict from tempfile import NamedTemporaryFile import h5py import numpy as np import os.path import time from . import dir_dictionary from . import io from ...
import sys import csv import StringIO import json # Usage: python process_kbp_data.py <input_file> <output_file> input_filename = sys.argv[1] output_filename = sys.argv[2] mapping = { "per:country_of_death" : 0, "per:schools_attended" : 1, "per:other_family" : 2, "per:city_of_birth" : 3, "org:top...
import gzip import re import csv import pickle import pprint if __name__ == "__main__": pp = pprint.PrettyPrinter(indent=4) filenames = [ "ydata-fp-td-clicks-v1_0.20090501", "ydata-fp-td-clicks-v1_0.20090502", "ydata-fp-td-clicks-v1_0.20090503", "ydata-fp-td-cli...
from django.urls import path from .views import register_user from .views import login_user from .views import edit_user from .views import list_user urlpatterns=[ path('register/',register_user,name="register_user"), path('login/',login_user,name="login_user"), path('edit/<int:pk>/',edit_user,name="edit_user"), path(...
from bs4 import BeautifulSoup import requests session = requests.Session() def gather_spark_scala_html_files(): spark_scala_html = session.get('{}{}'.format(spark_scala_base_url, "index.html")) soup = BeautifulSoup(spark_scala_html.text, 'html.parser') links = soup.find_all('a') for link in links: href =...
from __future__ import print_function import sys import Pyro4 if sys.version_info < (3, 0): input = raw_input uri = input("enter async server object uri: ").strip() proxy = Pyro4.Proxy(uri) print("* normal call: (notice the delay)") print("result=", proxy.divide(100, 5)) print("\n* async call:") proxy._pyroAsy...
import cv2 import numpy img = cv2.imread("4.jpeg") retval,threshold=cv2.threshold(img,12,255,cv2.THRESH_BINARY) grayimg=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) retval,threshold2=cv2.threshold(grayimg,12,255,cv2.THRESH_BINARY) gaus=cv2.adaptiveThreshold(grayimg,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C,cv2.THRESH_BINARY,115,1)...
# coding: utf-8 # In[10]: #last digit of partial sum of Fibonacci number a = [int(x) for x in input().split()] def Fn3(a): f0 = 0 f1 = 1 if a <= 1: return a else: rem = a % 60 if(rem == 0): return 0 for i in range(2, rem + 3): f =(f0 + f1)% 60 f0 = ...
from . import app, login_manager from flask_restplus import Api, Resource from flask import send_file, abort, request, Response, render_template from werkzeug.datastructures import FileStorage import logging import os import uuid import subprocess from OpenSSL.crypto import FILETYPE_PEM, Error as crypto_Error, load_c...
from django.contrib import admin from dungeon.models import * admin.site.register(Dungeon, admin.ModelAdmin) admin.site.register(Square, admin.ModelAdmin) admin.site.register(Character, admin.ModelAdmin)
from socket import * s_scoket = socket(AF_INET,SOCK_STREAM) address = ("127.0.0.1",4721) s_scoket.bind(address) s_scoket.listen(3) while True: print("等待连接中。。") coon, addr = s_scoket.accept() print("连接来自",addr) while True: data = coon.recv(1024) print("服务端接收的数据是",data) if not dat...
from . import SentenceEvaluator, SimilarityFunction from torch.utils.data import DataLoader import torch import logging from tqdm import tqdm from ..util import batch_to_device import os import csv from sklearn.metrics.pairwise import paired_cosine_distances, paired_euclidean_distances, paired_manhattan_distances from...
# Generated by Django 3.0.7 on 2021-01-10 09:01 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('jobads', '0021_auto_20210110_0848'), ] operations = [ migrations.AlterField( model_name='jobad', name='max_salary', ...
import threading import numpy as np from lidar import Lidar from gps import GPS from cameras import Cameras # py vesc import tty.usbserial # load lidar #lidar = Lidar('/dev/tty.SLAB_USBtoUART') #load GPS #gps = GPS('/dev/tty.usbserial-1A1330', 4800, 5) cameras = Cameras(1, 2, 0) cameras.start() #t1 = threading.Thr...
""" Project:DeepRating Author: Raphael Abbou Version: python3 """ import pandas as pd import numpy as np import matplotlib.pyplot as plt CUT_OFF_DATE = "201803" orig_col = ['fico','dt_first_pi','flag_fthb','dt_matr','cd_msa',"mi_pct",'cnt_units','occpy_sts',\ 'cltv','dti','orig_upb','ltv',...
import cStringIO import csv import re from google.appengine.api import users from google.appengine.ext import ndb from models import Student, GradeEntry import utils import webapp2 class BulkStudentImportAction(webapp2.RequestHandler): def post(self): user = users.get_current_user() if len(self.request.ge...
from pageObjects.LoginPage import LoginPage from utilities.BaseTest import BaseTest from utilities.TestData import TestData class Test_001_Login(BaseTest): def test_homepage_title(self): self.logger = self.get_logger() # get_logger is designed in base test class self.logger.info('***************...
from typing import List, Union import sys from collections import deque class BrainFuckMachine: array: List _pointer: int code: str stack: deque ip: int nf: bool stdin: str stdin_p: int stdout: str do_print: bool def __init__(self, do_print: bool = True): self.ar...
class CraftyAPIRoutes(object): HOST_STATS = '/api/v1/host_stats' SERVER_STATS = '/api/v1/server_stats' ADD_USER = '/api/v1/crafty/add_user' DEL_USER = '/api/v1/crafty/del_user' GET_LOGS = '/api/v1/crafty/get_logs' SEARCH_LOGS = '/api/v1/crafty/search_logs' class MCAPIRoutes(object...
import os from selenium import webdriver import telebot from telebot import types from flask import Flask, request from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions from selenium.webdriver.support.wait import WebDriverWait from config import * import pickle import sc...
#!/usr/bin/env python3 def print_message(message): return message def sum(parcel1, parcel2): # pragma: no cover sum = parcel1 + parcel2 return sum def multiply(factor1, factor2): # pragma: no cover return factor1 * factor2 def main(): print("test") if __name__ == "__main__": main()
def bfs(graph,startnode,visited): q = [startnode] while q: v = q.pop(0) if not v in visited: visited = visited+[v] q = q+graph[v] return visited graph = {} num_nodes = int(input("Enter the number of nodes : ")) nodes = [x for x in input("Enter the nodes : ...
# read in the list # create score matrix # use a score matrix import numpy as np from common import loaders def read_moves(): moves = loaders.load_string() return moves def calculate_score(moves): # (1 for Rock A X, 2 for Paper B Y, and 3 for Scissors C Z) # plus # (0 if you lost, 3 if the roun...
import boto3 MTURK_SANDBOX = 'https://mturk-requester-sandbox.us-east-1.amazonaws.com' MTURK_PROD = 'https://mturk-requester.us-east-1.amazonaws.com' ak_ai2 = '<access-key>' sak_ai2 = '<secret-access-key>' mturk = boto3.client('mturk', aws_access_key_id = ak_ai2, aws_secret_access_key = sak_ai2, region_name=...
import numpy as np, xarray as xr, rpxdock as rp, rpxdock.homog as hm from rpxdock.search import hier_search, grid_search from rpxdock.filter import filters def make_cyclic_hier_sampler(monomer, hscore, **kw): ''' :param monomer: :param hscore: :return: 6 DOF - 2: Sampling all 3D space + moving in and out f...
input = open('input.txt', 'r') output = open('output.txt', 'w') text = dict() a = input.read().split() for elem in a: if elem not in text: text[elem] = 0 else: text[elem] += 1 print(text[elem], end = ' ', file = output) input.close() output.close()
# -*- coding: utf-8 -*- """ Created on Tue Dec 1 18:43:45 2020 @author: dennis """ from itertools import permutations with open('data/day1.txt') as f: report = [int(x) for x in f.readlines()] for perm in permutations(report, 2): if sum(perm) == 2020: break print(f'Part 1: {perm[0] * perm[1]}') for...
import numpy as np import matplotlib.pyplot as plt import matplotlib.animation as animation # further reading https://mattmazur.com/2015/03/17/a-step-by-step-backpropagation-example/ # y = mx + c m = 5000 c = 0 my_feature = [n for n in range(1, 10)] my_label = [m*n + c for n in range(1, 10)] label_name =...
import numpy as np import cv2 import os import sys import time import torch from torch import nn from models.yolo import * from models.hrnet import * from utils.detector import * def predict(file_path, pred_path, module_dir, draw_bbox=False, box_tr=0.7): # file_path - absolute path to file # pred_path - abs...
#LeetCode problem 692: Top K Frequent Words class Solution: def topKFrequent(self, words: List[str], k: int) -> List[str]: d=dict() a=[] for i in words: d[i]=d.get(i,0)+1 res=sorted(d.items(),key=lambda item: (-item[1], item[0])) for i, j in res: a.app...
# #Artificially Destined #============= #by SoapDictator # import pygame, sys, math from pygame.locals import * sys.path.append('/AD/obj') sys.path.append('/AD/managers') sys.path.append('/AD/utils') from managers import event, window, input, unit, map class Main(object): #singleton implementation instance = Non...
import numpy as np from trajectory import Step, Trajectory class MemoryBuffer: """ Implementation of a transition memory buffer """ def __init__(self, max_memory_size): self.max_memory_size = max_memory_size self._top = 0 # Trailing index with latest entry in env self._size...
# APPLE """ SOLVED -- LEETCODE#303 Create a class that initializes with a list of numbers and has one method called sum. sum should take in two parameters, start_idx and end_idx and return the sum of the list from start_idx (inclusive) to end_idx` (exclusive). You should optimize for the sum method. """ class ...
import numpy as np from liegroups.numpy import SE3, SO3 from pyslam.problem import Options, Problem from collections import OrderedDict, namedtuple from pyslam.losses import L2Loss, TDistributionLoss, HuberLoss from pyslam.residuals import PoseResidual, PoseToPoseResidual, PoseToPoseOrientationResidual from pyslam.uti...
#!/usr/bin/env python import sys import os import re import xml.dom.minidom import StringIO import random from mmap import mmap from multiprocessing import Process from os import rename, listdir def main(): fnames = listdir('.') for oldfname in fnames: if re.match("[0-9][0-9][0-9] .*", oldfname): ...
import unittest2 import responses import dwollav2 class TokenShould(unittest2.TestCase): client = dwollav2.Client(id='id', secret='secret') access_token = 'access token' refresh_token = 'refresh token' expires_in = 123 scope = 'scope' account_id = 'account id' more_headers = {'idempotency...
import datetime from collections import OrderedDict import pandas as pd from google.cloud import bigquery CLIENT = None PROJECT_ID = None def insert_date_range(sql, date_range): start, end = date_range if start is None and end is None: return sql if start is None: return sql + ' WHERE `date` <= ...
from Tkinter import * from os import * class GUI(Frame): def __init__(self, parent, *args, **kwargs): Frame.__init__(self, parent, *args, **kwargs) #VARIABLES self.filelist=[] self.file="" ############################## self.win = parent self.win.geometry("1024x...
""" Copyright (c) 2018 Intel Corporation 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 wri...
import random class RockPaperScissors: def __init__(self): self.all_options = ['rock', 'fire', 'scissors', 'snake', 'human', 'tree', 'wolf', 'sponge', 'paper', 'air', 'water', 'dragon', 'devil', 'lightning', 'gun'] self.default_options = ['rock', 'scissors', 'paper'] ...