text
stringlengths
8
6.05M
import numpy as np class shape: def __init__(self, coordinates, rgba=(0,0,0,1), closed_shape=True): self.coordinates = coordinates self.rgba = rgba self.closed_shape = closed_shape class point(shape): pass class line(shape): pass class polygon(shape): pass class Bezier(s...
import frag_tracker tracker = frag_tracker.FragTracker() tracker.execute()
import os from datetime import time from html_dloader import HtmlDLoader class HtmlOutputer: def __init__(self): self.dLoader = HtmlDLoader() pass def output_cont(self, title, cont): if title is None: title = time.time() fout = open('%s.txt' % title, 'w') ...
import argparse import os import shutil import sys import zipfile #getAll()-It is a generator that's looking for all the files and directories from 'root' and will exclude #the files that have the prefix == 'exclude'. def getAll(root,exclude): list=os.listdir(root) for item in list: path=os.path.join(...
import exputils import autodisc as ad import numpy as np import os def calc_statistic_space_representation(repetition_data): # load representation data = [] config = ad.representations.static.PytorchNNRepresentation.default_config() config.initialization.type = 'load_pretrained_model' config.init...
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 07/02/2018 6:21 PM # @Author : Lee # @File : binary_search.py # @Software: PyCharm def binary_search(lists, target): l = 0 r = len(lists) - 1 while l <= r: mid = l + (r - l) // 2 if lists[mid] == target: return mid...
import time from goto import with_goto from temp import * def open_dairy(dairy): f=open(f"{dairy}.txt","a+") ch=0 while(ch!=3): ch=int(input("\nWelcome to your dairy:\n\t1.Read \n\t2.Write \n\t3.Exit\n\t\t")) if ch==1: f.seek(0) a=f.readlines() ...
x = float(input('Qual o valor da casa? ')) y = float(input('Qual o salário do comprador? ')) z = int(input('Em quantos anos vai ser pago? ')) tp = (x / z) / 12 v = (30 * y) / 100 if tp > v: print('Pra pagar uma casa de R${} em {} anos, a prestação será de R${:.2f}'.format(x, z, tp)) print('Empréstimo NEGADO') e...
#-*-coding:utf-8-*- """ @author: liaoxingyu @contact: sherlockliao01@gmail.com """ from bisect import bisect_right import torch import torch.optim.lr_scheduler as lr_scheduler import torch import torchvision import matplotlib.pyplot as plt # FIXME ideally this would be achieved with a CombinedLRScheduler, # separat...
#!/usr/bin/env python import yaml import sys print(yaml.safe_load(open(sys.argv[1])))
#!/usr/bin/python import sys def filestats(f): lines = 0 words = 0 chars = 0 for line in f: lines += 1 w = line.split() words += len(w) for word in w: chars += len(list(word)) print 'Lines:', lines print 'Words:', words print 'Characters:', chars...
from datetime import datetime,timedelta from django.core.management.base import BaseCommand, CommandError from django.contrib.auth.models import User from garmin.models import UserGarminDataSleep from quicklook.tasks import generate_quicklook class Command(BaseCommand): ''' Management command to generate raw data ...
import win32com.client import pythoncom class XASessionEvents: logInState = 0 def OnLogin(self, code, msg): print("OnLogin method is called") print(str(code)) print(str(msg)) if str(code) == '0000': XASessionEvents.logInState = 1 def OnLogout(self): prin...
import logging from flask import Flask app= Flask(__name__) @app.route('/') def hello(): #print("Hello Falsk") return "Hello Youtube" if __name__=="__main__": app.run(host='127.0.0.1',port=8080,debug=True)
import math from datetime import datetime from pymongo import MongoClient from threading import Thread CRIME_CATEGORIES = { "MISCELLANEOUS": 1, "LARCENY": 3, "FRAUD": 0, "DAMAGE TO PROPERTY": 4, "ASSAULT": 5, "MURDER/INFORMATION": 6, "AGGRAVATED ASSAULT": 6, "WEAPONS OFFENSES": 2, ...
import collections import glob import os import random from tqdm import tqdm random.seed(12345) # import numpy as np # np.set_printoptions(threshold=np.nan) def read_voxceleb_structure(directory, test_only=False, sample=False): voxceleb = [] speakers = set() for subset in os.listdir(directory): ...
from sqlalchemy import create_engine, Column, Integer, VARCHAR, Sequence from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker engine = create_engine('sqlite:///newfeatures.db') Base = declarative_base() # Builds the table class Features(Base): __tablename__= 'features'...
print('{==============calculadora============') num = int(input('Digite um número:')) print('{} x 1 = {}\n{} x 2 = {}\n{} x 3 = {}'.format(num, num*1, num, num*2, num, num*3)) print('{} x 4 = {}\n{} x 5 = {}\n{} x 6 = {}'.format(num, num*4, num, num*5, num, num*6)) print('{} x 7 = {}\n{} x 8 = {}\n{} x 9 = {}'.format(n...
# -*- coding: utf-8 -*- # Python Keyphrase Extraction toolkit: unsupervised models from __future__ import absolute_import from supervised.api import SupervisedLoadFile from supervised.feature_based.kea import Kea from supervised.feature_based.topiccorank import TopicCoRank from supervised.feature_based.wingnus import...
import numpy as np from scipy.misc import imread def load_images(): """ Load the HST images and make them presentable.""" im1 = imread('lens1.jpg') im1 = [ im1[:,:,2], im1 ] im1[0][300:450,400:550] = im1[0].mean() im1[0]=im1[0][100:-100,100:-100] im1[1] = im1[1][100:-100,100:-100,:] im2 = imread('lens2.jpg')...
import socket HEADER_LENGTH = 3 IP = socket.gethostname() PORT = 2000 #Set up client details my_username = input("Please enter your USERNAME: ") username = my_username.encode("utf-8") username_header = f"{len(username):<{HEADER_LENGTH}}".encode("utf-8") client_socket = socket.socket(socket.AF_INET, socket.S...
charity_search_key = "98d8c2f044592075251da6b0b146ef2e" just_giving_appid = "98927271" charity_navigator_key = "8186b309"
# Copyright 2019 Open Source Robotics Foundation, 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...
import urllib2 import re symbolfile = open('nasdaqlisted.txt') symbolslist = symbolfile.readlines() symbolslist = [x.split('|')[0] for x in symbolslist] print symbolslist i = 0 while i < len(symbolslist): htmlfile = urllib2.urlopen("http://finance.yahoo.com/q?s=%s&ql=1" % symbolslist[i]) htmltext = htmlfile.r...
from typing import List from leetcode import TreeNode, test, new_tree, sorted_list def binary_tree_path(root: TreeNode) -> List[str]: if not root: return [] stack, results = [], [] def helper(node: TreeNode) -> None: nonlocal stack, results stack.append(node.val) if not...
""" HPGL2のデータ用クラス """ from typing import List, Tuple, Optional, Union import math from fig_package.format.ynf.element.cYnfElment import cYnfElement from ..ynf import cYnf from ..ynf import cYnfText, cYnfLine, cYnfPolyline, cYnfBox, cYnfCircle, cYnfArc BP_PIC_NAME = 'BP Picture name' PS_LENGTH = 'PS Length' PS_WIDTH...
from flask import jsonify from psycopg2 import IntegrityError from app.DAOs.PhoneDAO import PhoneDAO from app.DAOs.ServiceDAO import ServiceDAO import phonenumbers PHONETYPEKEYS = ['E', 'L', 'F', 'M'] SERVICEPHONEKEYS = ['numbers'] def _buildPhoneResponse(phone_tuple): """ Private Method to build phone numbe...
import os import json path = "/mnt/SC/ASC/task3/ELE/dev/" files = os.listdir(path) map_ans = {'A':0,'B':1,'C':2,'D':3} multi_file = [] def is_multi(candidate): for j in candidate: if len(j.split()) >= 2: return True return False # 找出 multi_file for file in files: with open(path+file,"...
# -*- coding: utf-8 -*- import os import os.path import requests import shutil import time from behave import given, then from subprocess import check_output, CalledProcessError, STDOUT def copytree(src, dst): """Variant of shutil.copytree() that works when ``dst`` already exists.""" print('Copying tree "...
lis=[] def menu(): print(format("menu","=^35")) print("1.To Add new element") print("2.To Delete element") print("3.To Find node value") print("4.To Exit program") print(format("=====","=^35")) def add(element): lis.append(element) def delet(element): lis.remove(element) ...
from rest_framework import routers from .views import DeviceViewSet, PositionView from django.urls import path, include router = routers.SimpleRouter(trailing_slash = False) router.register(r'devices', DeviceViewSet, basename = 'device') urlpatterns = [ path(r'', include(router.urls)), path(r'position', Po...
import datetime # Simulation de données que l'on pourrait récupérer d'une base de données data = [ ["Josette", "Martin", 25, False], ["Robert", "Durand", 45, True], ["Lucien", "Pinard", 33, True], ] # Modèle permettant de créer des objets (instances) représentant des personnes class Person: # Propriét...
#!/usr/bin/env python import ROOT import joblib import pandas as pd import mputils def scale_by_bw(h): print(h.GetName()) h.Sumw2() for ib in range(1, h.GetNbinsX()+1): v = h.GetBinContent(ib) h.SetBinContent(ib, v / h.GetBinWidth(ib)) e = h.GetBinError(ib) h.SetBinError(ib, e / h.GetBinWidth(ib)) def plo...
from googlevoice import Voice import time from googlevoice.util import input voice = Voice() voice.login() for x in xrange(0,10): for y in xrange(0,10): voice.send_sms("5555512%s%s" % (`x`,`y`), "Add your message here") time.sleep(10) #so Google won't rate limit
def get_a_down_arrow_of(n): output = '' for x in range(n,0,-1): output += ' '*((x-n)*-1) for i in range(1,x): output += str(i%10) for k in range(x,0,-1): output += str(k%10) output += '\n' return output[:-1] ''' Given a number n, make a down arrow sh...
from Conv_Net.two_dim_resnet import make_two_dim_resnet from Transformer_Net import Prot_Transformer import torch.nn as nn import torch from torch.utils.checkpoint import checkpoint_sequential as cp_seq, checkpoint as cp class Final_Net(nn.Module): '''Putting the whole model together.''' def __...
import cdutil,cdms2 import cdtime import numpy as np from mpi4py import MPI from regrid2 import Regridder modelFolder = '/Users/joshsims/gcModels/maurer_daily' outfolder = '/Users/joshsims/gcModels/extremes/' realization = '01' tempFileDict = {} tmaxFileDict = {} tminFileDict = {} precipFileDict = {} tmaxDict = {} tmin...
n=int(input("Enter number n : ")) for i in range(5): m=int(input("Enter factor to check : ")) if(n%m==0): print(m," is factor") else: print(m," is not a factor")
import re ans = re.findall(r'[aeiouAEIOU]{2,}',input(),flags = re.I) if(ans == []): print("-1") else: print(*ans,sep='\n') # import re # v = "aeiou" # c = "qwrtypsdfghjklzxcvbnm" # m = re.findall(r"(?<=[%s])([%s]{2,})[%s]" % (c, v, c), input(), flags = re.I) # print('\n'.join(m or ['-1']))
# -*- coding: utf-8 -*- class Solution: def countBattleships(self, board): result = 0 if not board or not board[0]: return result for i in range(len(board)): for j in range(len(board[0])): result += ( 1 if ( ...
#!/usr/bin/env python3 import mpi4py mpi4py.rc.recv_mprobe = False from mpi4py import MPI from socket import gethostname from random import random as r from math import pow as p from sys import argv # Initialize MPI stuff comm = MPI.COMM_WORLD size = comm.Get_size() rank = comm.Get_rank() # Make sure number of attemp...
import sys import re #from numpy import matrix #import numpy as np from pyeda.inter import * n = 4 k = 0 #n, k = [int(x) for x in input("Enter two numbers here: ").split()] print (n) print (k) ''' matrix = [['A', 'B', 'C'], ['D', 'E', 'F'], ['G', 'H', 'I']] ''' matrix = [['A', 'B', 'C', '1'], ...
from django.contrib import admin from .models import Course, Teacher, Classroom, Student, LevelField, TeacherClassCourse, StudentCourse, Register, ClassTime class TeacherAdmin(admin.ModelAdmin): # list_display = ('user', 'hire_date', 'profession') # list_filter = ('user', 'hire_date', 'profession') # sear...
OUTPUT = 'ko{}-{}ntti'.format VOWELS = frozenset('aeiouyAEIOUY') def kontti(s): result = [] for word in s.split(): dex = next((i for i, a in enumerate(word) if a in VOWELS), -1) + 1 result.append(OUTPUT(word[dex:], word[:dex]) if dex else word) return ' '.join(result)
# identify the data type in python # type() function from math import * # https://www.w3schools.com/python/python_syntax.asp # SOME ARE REPETED bo = (1,2,3,4,5,6,7,8,9,10) print(type(bo)) print('_________',bo,'___________') bo_1 = 'Jeewan' print(type(bo_1)) print('_________',bo_1,'___________') bo_2 = ['Jeewan', 'Dee...
from flask import Flask ,render_template,flash,redirect,request,url_for import mysql.connector # from datetime import datetime try: print("connected") connection = mysql.connector.connect(user='root', password='Password@123', host='localhost', database='data') print("connected") cur = connection.cursor(buffered=T...
# encoding=utf-8 import numpy as np from numpy.linalg import * def main(): print(np.eye(3)) #单位矩阵 print('线性方程组') lst = np.array([[1,2],[3,4]]) print('Inv矩阵的逆:') print(inv(lst)) print("T矩阵转置:") print(lst.transpose()) print("T矩阵行列式:") print(det(lst)) print("T矩阵特征值:特征向量") ...
from PyQt5.QtGui import QPixmap from ui_msgbox import * from socket import * class MsgBoxWindow(QtWidgets.QWidget,Ui_msgbox): message =[] def __init__(self,msg,parent=None): super(MsgBoxWindow, self).__init__(parent) self.setupUi(self) self.message = msg self.loadmsg(msg) ...
__authors__ = "" __copyright__ = "(c) 2014, pymal" __license__ = "BSD License" __contact__ = "Name Of Current Guardian of this file <email@address>" USER_AGENT = 'api-indiv-0829BA2B33942A4A5E6338FE05EFB8A1' HOST_NAME = "http://myanimelist.net" DEBUG = False RETRY_NUMBER = 4 RETRY_SLEEP = 1 SHORT_SITE_F...
#coding:utf-8 #!/usr/bin/env python import copy from gclib.utility import currentTime, drop from game.utility.config import config from game.routine.pet import pet from game.routine.vip import vip class educate: @staticmethod def start(usr, edupos, cardid): """ 开始训练 """ inv = usr.getInventory() card = i...
from django.db import models from django.contrib.auth.models import User from django.utils import timezone # Create your models here. class Works(models.Model): #儲存手工藝品資料 class Meta: permissions = ( ("add_add_works", "add_add_works"), # 只有一個權限時,千萬不要忘了逗號! ) Title = models.CharField(max_lengt...
import sys sys.path.insert(0, 'Serializers') from yaml_serializer import YamlSerializer from pickle_serializer import PickleSerializer from json_serializer import JsonSerializer from toml_serializer import TomlSerializer class Factory(): @staticmethod def create_serializer(s_name): if (s_name == "json...
import numpy as np import cv2 as cv import matplotlib.pyplot as plot import operator import os imgListt = np.full((28,28), 0) testImg = cv.imread("E:/cut_ImgsTest/28pix/T"+str(7)+".jpg") for index1 in range(len(testImg)): for index2 in range(len(testImg[index1])): if(testImg[index1][index2][2] < 90): ...
#!/usr/bin/env python """ An axes used to jointly format Cartesian and polar axes. """ # NOTE: We could define these in base.py but idea is projection-specific formatters # should never be defined on the base class. Might add to this class later anyway. from ..config import rc from ..internals import _pop_kwargs from ....
#!/usr/bin/env python2 # # The MIT License (MIT) # # Copyright (c) 2014 Fam Zheng <fam@euphon.net> # # 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 lim...
import urllib2 from bs4 import BeautifulSoup import re import sys reload(sys) sys.setdefaultencoding('utf-8') #txt_path = r"/Users/zhoufengting/Desktop/href_2013_2014.txt" #fp = open(txt_path) #print len(fp) #for line in fp: #print line url = r"http://www.eurosport.com/football/ligue-1/2013-2014/montpellier-hsc-pa...
from importlib import import_module from django.conf import settings from django.contrib.auth.base_user import BaseUserManager from django.contrib.auth.models import AbstractUser from django.contrib.auth.models import UserManager as AuthUserManager from django.contrib.auth.signals import user_logged_in from dja...
from sqlite3.test import factory l=[1,2,3,4] s="hola mundo" l3=(c * num for c in s for num in l if num >0) print l3.next() for letra in l3: print letra def factorial(n): i =1 while n >1 : i =n*i yield i n-=1 for e in factorial(5): ...
def solution(n): count =0 ans = 0 while(n>0): count+=1 if(n&1): temp = 1<<(32-count) ans+=temp n = n>>1 return ans n = int(input()) ans = solution(n) print(ans,end="\n")
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Mar 11 22:01:04 2018 @author: panzengyang """ import SVM_cv import Perceptron_cv import msg2matrix as mx from sklearn.metrics import hinge_loss from sklearn.linear_model import Perceptron from sklearn.svm import SVC from sklearn.feature_extraction.text ...
from numpy import diag, sqrt from numpy.linalg import inv class ExtendedKalmanFilter: def __init__(self, state_means, state_covariances, transition_means_lambda, transition_means_jacobi_lambda, transition_covariances_lambda, observation_means_lambda, observation_means_jacobi_lamb...
import jieba import jieba.posseg as pseg jieba.load_userdict('./dict.txt') # get the origin data def getTheOriginData(path): with open(path,encoding='UTF-8') as file_object: contents = file_object.read() ##split the data by line lines = contents.split('\n') ##the labels labels = [] ##t...
# # Copyright © 2021 Uncharted Software 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 l...
from __future__ import absolute_import, division, unicode_literals from mimic.model import cloudfeeds from twisted.trial.unittest import SynchronousTestCase from testtools.matchers import (MatchesSetwise, MatchesDict, Equals) class TestCloudFeeds(SynchronousTestCase): def setUp(self): self.cf = cloudfeed...
import numpy as np def temptable_template(df, sql, DB): """ This function takes a dataframe, a stub bit of a bulk sql insert e.g. INSERT INTO mytable VALUES and turns the datafame into the requisite string that follows and concatenates it all together. :param df: The dataframe we are going to ...
import pytest from responder import routes @pytest.mark.parametrize( "route, expected", [ pytest.param("/", False, id="home path without params"), pytest.param("/test_path", False, id="sub path without params"), pytest.param("/{test_path}", True, id="path with params"), ], ) def te...
from django.conf.urls import include, url from . import views urlpatterns = [ url(r'^$', views.IndexView.as_view(), name='index'), url(r'^success/(?P<next>[\s\S]*)/$', views.SuccessView.as_view(), name='success'), url(r'^error/(?P<next>[\s\S]*)/(?P<msg>[\s\S\\u4e00-\\u9fa5]*)/$', views.ErrorView.as_view()...
from abc import ABC, abstractmethod class ClientDAO(ABC): """ Abstract class for Data Access Objects for Client with four methods. get_clients add_client update_client delete_client """ @abstractmethod def get_clients(self): pass @abstractmethod ...
# Generated by Django 2.0.3 on 2018-05-04 12:43 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('web', '0042_takencourse_taken_course_title'), ] operations = [ migrations....
from flask import Flask, render_template, request, redirect app = Flask(__name__) @app.route('/users/<username>/<id>') def show_user_profile(username, id): # print username print id # return username return render_template('users.html', username=username) @app.route('/route/with/<vararg>') def ha...
# import the libraries # -------------------- import pandas as pd # import numpy as np import math from sklearn.ensemble import RandomForestClassifier from sklearn.cross_validation import train_test_split # from sklearn import preprocessing as pp from sklearn.metrics import accuracy_score from sklearn.metrics import co...
from django.db.models.signals import post_save, pre_delete from django.dispatch import receiver from django.contrib.auth import get_user_model from ghostwriter.home.models import UserProfile User = get_user_model() @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): ...
# AUTO GENERATED FILE - DO NOT EDIT from dash.development.base_component import Component, _explicitize_args class Input(Component): """A Input component. Keyword arguments: - id (string; optional): The ID of this component, used to identify dash components in callbacks. The ID needs to be unique across all of...
from __future__ import print_function import argparse try: from orlo import __version__ except ImportError: # _version.py doesn't exist __version__ = "TEST_BUILD" __author__ = 'alforbes' """ Command line interface Generally setup/initialisation functions and the like, called by /usr/bin/orlo """ def ...
import smtplib SERVERS = ["156.17.40.148", "156.17.40.162", "156.17.40.46", "156.17.40.85"] for SERVER in SERVERS: FROM = "test@pwr.wroc.pl" TO = ["xx@plonk.ict.pwr.wroc.pl", "zxcvbnm@heaven.org"] message = """\ From: %s To: %s Subject: %s %s """ % (FROM, ", ".join(TO), "test", "test...
import json def lambda_handler(event, context): jsonRequestInput = json.loads(event['body']) userid = jsonRequestInput['userid'] stock = jsonRequestInput['stock'] db_stocks = getDynamoData(userid) if(db_stocks == ""): putDynamoData(userid, stock) else: d...
#YOU ARE CURRENTLY VIEWING THE GENIUS CODING BEHIND PYTHON CALCULATOR 1.0 #BRACE YOURSELVES....SWAG INCOMING! print " +---+---+---+---+---+---+" print " |~~~~~~~ THIS IS ~~~~~~~|" print " +---+---+---+---+---+---+" print " ...
# Simulation Logic from utils import v_sub, v_add, v_mul, v_div, v_array_sum, agent_degree_rotation, convert_to_unit_vector, limit from Agent import DEFAULT_SPEED, Agent from Obstacle import Obstacle import shared from random import randrange # Blue Agent:0 # Red Agent:1 ALIGNMENT_WEIGHT = [10,4] COHESION_WEIGHT = [5...
#!/usr/bin/python3 import sys import subprocess #exchanges = ["bittrex", "binance_us", "kucoin", "ftx_us", "kraken", "gemini" exchanges = ["ftx_us", "kucoin"] import util import json from collections import defaultdict markets = defaultdict(list) def getdata(): try: for exchange in exchanges: ...
print("Hammie was here!") sum = 0 empty = [] for i in range(1, 1000): if i%3 == 0 or i%5 == 0: empty.append(i) sum += i print(empty) print(sum) print("hello") print("test")
from setuptools import setup import pylint_report setup( name=pylint_report.__name__, version=pylint_report.__version__, description='Generates an html report summarizing the results of pylint.', url='https://github.com/drdv/pylint-report', author='Dimitar Dimitrov', author_email='mail.mitko@gm...
from time import sleep from json import dumps from numpy.random import choice, randint from kafka import KafkaProducer def get_random_value(): """ Generate dummy data :return: dict """ cities_list = ['Lviv', 'Kyiv', 'Odessa', 'Donetsk'] currency_list = ['HRN', 'USD', 'EUR', 'GBP'] return ...
#!/usr/bin/python3 # This is python_server1.py file import socket import threading import pickle from time import sleep from collections import OrderedDict from section import generate_rooms import sql def main(): print('start server') # create a socket object server_socket = socket.socket(soc...
# -*- coding: utf-8 -*- import logging import datetime import uuid from model.assistance.justifications.justifications import Justification, RangedJustification, RangedTimeJustification from model.assistance.justifications.status import Status from model.assistance.justifications.status import StatusDAO from model.a...
from django.shortcuts import render ''' # Create your sql here. from django.shortcuts import render, HttpResponse, render_to_response from django.views.decorators.csrf import csrf_exempt from django.http import JsonResponse from django.views.generic import View from django.utils.decorators import method_decorator impor...
import uuid import django.utils.timezone as timezone from django.db import models class Test(models.Model): id=models.UUIDField(primary_key=True, auto_created=True, default=uuid.uuid4, editable=False) name=models.CharField(max_length=20) code=models.IntegerField(default=0) grade=models.Char...
# スクレイピング # !pip install lxml import requests import re import uuid from bs4 import BeautifulSoup import os word = "カメラ" images_dir = 'image_data/camera/' if not os.path.exists(images_dir): os.makedirs(images_dir) url = "https://search.nifty.com/imagesearch/search?select=1&chartype=&q=%s&xargs=2&im...
class Solution: def findJudge(self, N: int, trust: List[List[int]]) -> int: i = 1 x = [] for j in range(len(trust)): if trust[j][0] not in x: x.append(trust[j][0]) m = 0 for i in range(1,N+1): if i not in x: m = i ...
############################################################################################# ##################### Simple Linear Regression - Python #################################### ############################################################################################# #-----------------------------------...
from abc import ABC, abstractmethod class Department: def __init__(self, name, code): self.name = name self.code = code class Employee(ABC, Department): def __init__(self, code, name, salary): self.code = code self.name = name self.salary = salary @abstractmethod...
#首字母大写 使用[map] (返回列表) #用法:name = ['jArrY','tOM'] # normalize(name) def normalize(name): def fn(a): return a[:1].upper() + a[1:].lower() return list(map(fn,name)) #list求积 使用[reduce] (返回值) from functools import reduce def prod(L): def fn(x,y): return x * y return reduce(fn,L) #字符串转浮点...
# -*- coding: utf-8 -*- """ Created on Tue May 17 14:38:53 2016 @author: a_danda """ import json import re import operator import sys from pprint import pprint data = [] with open(sys.argv[2]) as f: for line in f: data.append(json.loads(line)) #pprint(data) afinnfile = open(sys.argv[1]) scores = {...
# -*- coding: utf-8 -*- """ Autor: Jorge Casillas y Miguel Morales Castillo Fecha: Noviembre/2018 Contenido: Uso simple de XGB y LightGBM para competir en DrivenData: https://www.drivendata.org/competitions/7/pump-it-up-data-mining-the-water-table/ Inteligencia de Negocio Grado en I...
from json import loads from redis import Redis from datetime import datetime import ed25519 import hashlib class Transaction(object): """This class is used for getting easy-to-use txn class from the bytes, received from the Tendermint core""" def __init__(self, tx): self.raw_tx = tx self...
# Copyright 2015 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). import unittest.mock import pytest from packaging.version import Version from pants.base.deprecated import ( BadDecoratorNestingError, BadSemanticVersionError, CodeRemovedErr...
import time import hashlib import argparse import multiprocessing from joblib import Parallel, delayed __author__ = 'David Flury' __email__ = "david@flury.email" def calculate_hash(): input = 'unmix.io is great!' hash_object = hashlib.sha1(input.encode()) return hash_object if __name__ == '__main__': parser...
# Copyright 2023 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import annotations from pants.backend.cue.subsystem import Cue from pants.core.util_rules.external_tool import DownloadedExternalTool, ExternalToolRequest from pants.engine...
#!/usr/bin/env python import rospy from std_msgs.msg import Int32 from geometry_msgs.msg import PoseStamped, Pose from styx_msgs.msg import TrafficLightArray, TrafficLight from styx_msgs.msg import Lane from sensor_msgs.msg import Image from cv_bridge import CvBridge from light_classification.tl_classifier import TLCla...
import os import random import numpy as np import pygame from pygame.locals import * from constants import * from Oracle import Oracle, State class Block(pygame.sprite.Sprite): def __init__(self, color_index, grid_center, block_size=50): super(Block, self).__init__() self.block_size = block_size...
import torch from torch.utils.data import Dataset from torch.utils.data import DataLoader import numpy as np from pathlib import Path from functools import lru_cache def pad_collate(batch): # find longest sequence max_input_length = max([len(x[0]) for x in batch]) max_output_length = max([len(x[1]) for x...