text
stringlengths
38
1.54M
import FWCore.ParameterSet.Config as cms hltDeepInclusiveMergedVerticesPF = cms.EDProducer("CandidateVertexMerger", maxFraction = cms.double(0.2), minSignificance = cms.double(10.0), secondaryVertices = cms.InputTag("hltDeepTrackVertexArbitratorPF") )
class AgenteVainilla: def __init__(self, cash: float, stock_portfolio: dict, indiccators: object, environment: object) -> None: pass def policy(): pass
import pkg_resources from mako.lookup import TemplateLookup from bravado_types.config import Config from bravado_types.data_model import SpecInfo from bravado_types.metadata import Metadata def render(metadata: Metadata, spec: SpecInfo, config: Config) -> None: """ Render module and stub files for a given Sw...
# -*- coding: utf8 -*- import unittest from source.array_n_string import * class TestTwoSum(unittest.TestCase): def test_two_sum_001(self): numbers = [1, 2, 3, 4, 5] target = 8 index1, index2 = TwoSum().two_sum(numbers, target) self.assertEqual(index1, 3, 'first val...
import pygame pygame.init() clock = pygame.time.Clock() fps = 60 word_data = [] lines = 16 cols = 31 monitor = pygame.display.Info() screen_width = monitor.current_w screen_height = monitor.current_h screen = pygame.display.set_mode((screen_width, screen_height)) object_size = screen_width // 30 for i in range(line...
def recursive_binary_search(arr,target): # check the length of the list first # This condition also accounts for when a number is not in the list, # Then len of arr evetually turns to zero as the search progresses if len(arr) == 0: return False else: # get the midpoint mid_po...
''' Select multiple image of same size that all need cropping in same area. Select a region to crop on one image, and apply it to all selected images. Saves cropped images with filename prefix 'Multicropped-' Particularly useful for cropping the same area of many screenshots. ''' from tkinter import filedialog import...
import sys sys.path.append('/home/test/automation/All_repo/SDNC-FUNC/HAPPIEST_FRAMEWORK') from Config import ControllerConfig from Config import variables from Supporting_Libs import snmp_utils import re oid = '1.3.6.1.2.1.2.2.1.7' up = [] down = [] ## Performing GET-BULK operation on interface status prin...
# https://leetcode.com/problems/string-to-integer-atoi/ class Solution: def myAtoi(self, str: str) -> int: num = 0 is_positive = True i = 0 while i < len(str) and str[i] == ' ': i += 1 if i < len(str) and str[i] == '+': i += 1 elif i < len(s...
import json from django.db import models from django.utils.six import python_2_unicode_compatible from channels import Group from .settings import MSG_TYPE_MESSAGE from django.contrib.auth.models import User # Create your models here. class UserProfile(models.Model): user = models.OneToOneField(User) def __str__(...
"""Interface with git locally and remotely.""" import glob import json import logging import os import re import sys import tarfile import time from datetime import datetime from subprocess import CalledProcessError, PIPE, Popen, STDOUT IS_WINDOWS = sys.platform == 'win32' RE_ALL_REMOTES = re.compile(r'([\w./-]+)\t([...
from index_map import indexes from get_objects import get_objects from PIL import Image import numpy as np class Data: def __init__(self) -> None: self.englishFile = open("en-es/source.final.file-found") self.spanishFile = open("en-es/reference.final.file-found") self.metadataFile = open("e...
import logging import pandas as pd from scrapper.configuration import config from scrapper.infraestructure.TwitterScrapper import TwitterScrapper class TwitteService: def __init__(self): self._twitter_scrapper = TwitterScrapper() def scrap_profiles_from_user_ids(self, user_ids: list) -> list: ...
from flask import Flask, render_template, request, jsonify from marshmallow import Schema, fields, ValidationError import SO2002A import string # validation class BaseSchema(Schema): value = fields.List(fields.String, required=True) printable = set(string.printable) # initialise app = Flask(__name__) message ...
import sys, re dico = { 'févriyé':'NOUN' } sent_idx = 1 def guess_tag(idx, s, dico, first_alpha): tag = '_' # print(idx, s, first_alpha, file=sys.stderr) if s in "!\"'()+,./:?«»–—‘“”•…": return 'PUNCT' elif idx != 1 and s[0].isupper() and not first_alpha and s.title(): return 'PROPN' elif re.match('^[0-9]...
def main(): #escribe tu código abajo de esta línea vel = float(5.7) min = float(input("Dame los minutos: ")) dis = (vel * (min*60))/10 print("Centímentros recorridos: ", dis) if __name__ == '__main__': main()
""" This module takes care of starting the API Server, Loading the DB and Adding the endpoints """ import os import sendgrid from sendgrid.helpers.mail import * from flask import Flask, request, jsonify, url_for, Blueprint,current_app from api.models import db, User, Pregunta from api.utils import generate_sitemap, API...
from bear.install_data import testRun # coding=utf-8 import time import unittest class TestSendMessage(unittest.TestCase): def test_send(self): print("如果用例失败,代表BearFrame 框架没有正确安装,请用 {pip install BearFramework}命令安装") self.assertEqual(testRun(),"OK")
import numpy as np np.random.seed(2016) import os from random import shuffle import sys import pandas as pd import warnings import platform import time as tm import json from collections import OrderedDict import pandas as pd import numpy as np import glob ###############################################...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Oct 20 15:10:22 2020 @author: scro3517 """ import numpy as np import pandas as pd import random def modify_df(): """ Load Dataframe as an Iterable """ iter_csv = pd.read_csv('/home/scro3517/Desktop/mimic-iii-clinical-database-1.4/NOTEEVENTS.cs...
import pandas as pd import seaborn as sns import matplotlib.pyplot as plt import numpy as np from sklearn.manifold import TSNE import argparse from matplotlib.animation import FuncAnimation from pose_embedder import FullBodyPoseEmbedder def tsne_trace(train_path, perp, iter, plot_type, embedder): df, data_cols, data...
__author__ = 'thiagocastroferreira' import os root_dir = '/roaming/tcastrof/names/eacl' parsed_dir = '/roaming/tcastrof/names/regnames/parsed' mentions_dir = '/roaming/tcastrof/names/eacl/mentions' webpages_dir = '/roaming/tcastrof/names/regnames/webpages' file_dbpedia = os.path.join(root_dir, 'name_base.json') file...
import os, sys sys.path.append( os.path.dirname(os.path.dirname((os.path.realpath(__file__)))) ) import time import torch import numpy as np import gym from Games.envs import DiskonnectPlayerEnv import wandb from stable_baselines3 import PPO, TD3, SAC, DDPG from stable_baselines3.common.vec_env import DummyVecEn...
import unittest from rabin_karp import RabinKarp class RabinKarpTests(unittest.TestCase): def setUp(self): self.rk_one = RabinKarp('abcabaaba', 'aba') self.rk_two = RabinKarp('abccdhabacfhfhf', 'abac') self.rk_three = RabinKarp('fabdgdtdf', 'fabdgdtdf') def test_one(self): self...
import cmapPy.pandasGEXpress.parse as parse import cmapPy.pandasGEXpress.GCToo as GCToo import numpy as np import pandas as pd # TODO add to metadata invariant_rids = ['c-661', 'c-662', 'c-663', 'c-664', 'c-665', 'c-666', 'c-667', 'c-668', 'c-669', 'c-670'] def normalize(mfi_gctoo, log=True, inv=True, inv_threshold =...
__author__ = 'mwas' __author__ = 'mwas' from django import forms from customer_feedback import models class admin_login_form(forms.Form): password = forms.CharField(required=False, label="Password", max_length=255, widget...
from typing import List class Solution: def findMaxConsecutiveOnes(self, nums: List[int]) -> int: max_length = 0 current_length = 0 for num in nums: if num: current_length += 1 else: if current_length >= max_length: ...
""" SSW533-get_logs by Yuning Sun 11:54 PM 11/30/20 Module documentation: """ import json import requests repo_name = 'kernel_liteos_a' url = 'https://gitee.com/api/v5/repos/openharmony/' + repo_name + '/pulls' params = {"access_token": "5b304d9b1353007d8891cc3ea2c84841", "state": "merged"} res = requests.get(url=url...
# Original Idea that started it all: def danny_bub(list): length = len(list) - 1 sorted = False counter = 0 while not sorted: sorted = True for i in range(counter, length - 1, 1): if list[i] > list[i + 1]: list[i], list[i+1] = list[i+1], list[i] ...
from veides.sdk.stream_hub import StreamHubClient, AuthProperties, ConnectionProperties from time import sleep import logging import argparse if __name__ == "__main__": parser = argparse.ArgumentParser(description="Basic example of connecting to Veides Stream Hub") parser.add_argument("-u", "--username", req...
'''Code snippets on how to unfreeze and train specific layers''' ### How to import a pretrained model from torchvision import torchvision.models as models model = models.resnet152() ### How to train the last layer only (classifier) for param in model.parameters(): param.requires_grad = False ### Training all the...
""" The models module encapsulates the parameters data inherent in a large database of phrases. """ import hashlib from sqlalchemy import Column, Integer, String, Unicode, ForeignKey from sqlalchemy.orm import relationship from chkphrase.database import Base class User(Base): __tablename__ = 'users' id = Col...
""" Script that trains graph-conv models on Tox21 dataset. """ from __future__ import division from __future__ import print_function from __future__ import unicode_literals import numpy as np import json np.random.seed(123) import tensorflow as tf tf.set_random_seed(123) import deepchem as dc from deepchem.molnet im...
#!/usr/bin/env python3 import yaml from math import log, sqrt, floor, ceil from itertools import product from operator import itemgetter import numpy as np if __name__ == '__main__': max_n = 3000000 iv = 10 multiplier = sqrt(2) max_i = int((log(max_n)-log(iv))/log(multiplier)) mks = [int(round(iv*...
# 3. Реализовать функцию my_func(), которая принимает три позиционных # аргумента и возвращает сумму наибольших двух аргументов. # реализация функции def my_func(p_1, p_2, p_3): """ Возвращает сумму наибольших двух аргументов. Именованные параметры: p_1 -- первое число p_2 -- второе число p_3 ...
import json from django.http import HttpResponse from user.helper.string import * def create_json_response(json_dict, error_header, status_code=200, dumps=True): # if dumps equals to False then jsonDict is already in json format if dumps: json_dict = json.dumps(json_dict) response = HttpResponse(...
import random from matplotlib import pyplot as plt from matplotlib import animation from language import Language from ethnicity import Ethnicity from utils import * from math import sqrt, ceil from threading import * N = 1000 movement_rate = 0.001 influence_rate = 0.1 propagation_rate = 0.01 chance_to_change = 0.75 l...
# Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def rob(self, root): """ :type root: TreeNode :rtype: int """ # flag = True means rob the root, else not. r...
import SocketServer from mixins import ThreadPoolMixIn, OtherPoolMixIn import re import threading import os class MyRequestHandler(SocketServer.BaseRequestHandler): users = {} def handle(self): # print threading.currentThread().getName() # print "Pid: %d" % os.getpid() command = self...
import numpy as np import pdb import cv2 import logging from skimage.feature import local_binary_pattern from modshogun import RealFeatures, MulticlassLabels from modshogun import LMNN as shogun_LMNN import matplotlib.pyplot as plt from metric_learn import ITML_Supervised logging.basicConfig(filename="logs", level=log...
# Project: Live Webcam Video Filters # Contributers: Abraham Medina, Gurjot Sandhu, Valentina Fuchs Facht # Class: CST 205-02 Spring 2017 # Date: March 16, 2017 # Abstract: This program allows the user to activate the webcam of a computer according to a filter they would like put over their face and to be able to then ...
import math Phi = (1 + math.sqrt(5)) / 2 phi = 1/Phi def fib(n): return round((Phi**n / math.sqrt(5)) - (-phi**n / math.sqrt(5))) n = 1 sum = 0 while fib(n) < 4000000: if(fib(n) % 2 == 0): sum += fib(n) n += 1 print(sum)
from pyspark import SparkContext from collections import OrderedDict import sys import itertools inputfile = sys.argv[1] outputfile = sys.argv[2] sc = SparkContext(appName = "Girvan Newman") data = sc.textFile(inputfile) data = data.map(lambda x: (eval(x)[0],eval(x)[1])) g = data.collect() node_test = s...
from django.conf.urls import url from . import views app_name = 'weixin' urlpatterns = [ # ex: /polls/ url(r'^$',views.weixin ,name="index"), ]
# -*- coding: UTF-8 -*- from django.db import models from apps.seguridad.models import Usuario, MotivoBloqueo from apps.seguridad.audit import audit @audit class BloqueoLog(models.Model): usuario = models.ForeignKey(Usuario) motivo = models.ForeignKey(MotivoBloqueo) fecha = models.DateField() class M...
from typing import Union from types import FunctionType from functools import wraps __all__ = ('lru_cache', 'cache') __version__ = '0.4' def cache(f): return lru_cache()(f) def lru_cache( maxsize: Union[None, "NonNegativeInt", FunctionType, classmethod, staticmethod]=None, generate_key = lambda *...
import functools import unittest import six if six.PY3: from unittest import mock else: import mock from socketio import base_manager from socketio import pubsub_manager class TestBaseManager(unittest.TestCase): def setUp(self): mock_server = mock.MagicMock() self.pm = pubsub_manager.Pub...
from PIL import Image import matplotlib.pyplot as plt def getRed(redVal): return '#%02x%02x%02x' % (redVal, 0, 0) def getGreen(greenVal): return '#%02x%02x%02x' % (0, greenVal, 0) def getBlue(blueVal): return '#%02x%02x%02x' % (0, 0, blueVal) image = Image.open("C:/Users/DELL/projects/colon/original...
""" Format the characters in the stdin by the given number of spaces Python 3 Assumptions: ============ * if a word is greater than width, it will NOT be split across the lines. Instead, the entire word will be printed out * the line to be read is not larger than available main memory * input is formatted correctly ...
#!/usr/bin/env python import SimpleITK as sitk import time import DataPreparation def main(): outputDirPath = 'C:/ZCU/Diplomka/Dataset/04/RESULTS/Res_Affine_Conv' # fixed = DataPreparation.readDICOMSerieToImage('C:/ZCU/DATA_FOR_TEST/MRI/TCGA-LIHC/TCGA-K7-AAU7/07-31-2001-MRI ABDOMEN WWO CONTRAST-59507/12...
import math columns_and_rows = int( input('How many columns and rows do you want in your multiplication table? ')) columns = range(1, columns_and_rows + 1) rows = range(1, columns_and_rows + 1) digits = int(math.log10(columns_and_rows)) + 1 for column in columns: r = '' for row in rows: r += f'{...
from datetime import datetime, timedelta from config import settings from TwitterAPI import TwitterAPI from dateutil.parser import parse from .data.twitter import lists import csv import os description = """ First-person accounts from regions affected by conflict and diaster. """ definition = { 'internalID': 'b3b...
import numpy as np import pandas as pd import random import geneticAlgorithm.fitnessFunctions as functions import geneticAlgorithm.experiment as exp from classes.Encoding import Encoding lethalityDict = {} def generateRandomTraps(encoder: Encoding=None, numTraps=100000): """Generates numTraps traps uniformly at r...
import re import datetime a_monday = datetime.datetime.strptime('2019-08-19', '%Y-%m-%d') class Line: def __init__(self, date, l, sticky, attrs): self.date = date self.full = l self.dist = None self.dur = None self.d_pos = None self.d_neg = None self.shoes ...
# Generated by Django 2.2 on 2020-06-12 11:54 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('biblioteca', '0001_initial'), ] operations = [ migrations.RemoveField( model_name='ejemplar', name='usuario', ...
import numpy as np import matplotlib.pyplot as plt import pickle from scipy.optimize import curve_fit def corrected_rotation(x_arr, mu): """ Given an input rotation angle [-180,180), return corrected angle to ensure such that angle lies within mu-180 and mu+180. :param x_arr: :param mu: :rty...
from styn import chore @chore() def clean(): pass # Should be marked as chore. def html(): pass # References a non chore. @chore(clean, html) def android(): pass
print('Hello, welcome to true talk') ans = input('Are you ready to play ? (yes/no): ') score = 0 total_q = 4 if ans.lower() == 'yes': ans = input('1. What is the best programming language ? ') if ans.lower() == 'python': score += 1 print('Correct') else: print('Incorrect'...
import os import string import tarfile import collections import requests from nltk.corpus import stopwords import numpy as np import tensorflow as tf vocabulary_size = 10000 embedding_size = 200 batch_size = 100 num_sampled = int(batch_size/2) window_size = 2 valid_words = ['cliche', 'love', 'hate', 'silly', 'sad']...
import unittest from unittest.mock import patch from synapses.model import Model from synapses.activator import ActivatorEnum, StepActivator from synapses.perceptron import PerceptronInterface # noinspection PyMethodMayBeStatic class ModelTests(unittest.TestCase): def setUp(self) -> None: self.xor_model_...
# -*- coding: utf-8 -*- # @Time : 2021/9/2 15:44 # @Author : CuiShuangqi # @Email : 1159533975@qq.com # @File : pytestParaTest.py import pytest from selenium import webdriver from time import sleep """ pytest 参数化 当一组测试用例有固定的测试数据时,就可以通过参数化的方式简化测试用例的编写 通过pytest.mark.parametrzie()方法设置参数: 参数名:"se...
#-*- coding = utf-8 -*- #@Time : 2020/11/3 15:12 #@Author : 冯朗 #@File : Fit2.py #@Software : PyCharm import numpy as np import matplotlib.pyplot as plt from scipy.optimize import leastsq # 目标函数 def real_func(x): return np.sin(2 * np.pi * x) # 多项式 def fit_func(p,x): f = np.poly1d(p) return f(x) # 残差 def ...
import eventlet from urllib import request import random import datetime import pandas as pd import itertools starttime = datetime.datetime.now() base_url = "http://splitit.cs.loyola.edu/cgi/splitit.cgi" max_int = 9999 num_of_splitting = 1 verbose = False df = pd.read_csv("tmp/cheat_splitting_file.csv", header=None)...
from collections import defaultdict import torch import numpy as np import pandas as pd from pytorch_toolbox.callbacks import Callback, LearnerCallback from pytorch_toolbox.callbacks import hook_output from pytorch_toolbox.utils import Phase, to_numpy from pytorch_toolbox.utils.training import flatten_model class O...
import unittest from nose import SkipTest import numpy as np from airline_alloc.dataset import Dataset from airline_alloc.optimization import * class ObjectiveTestCase(unittest.TestCase): """ test the get_objective function """ def test_3routes(self): data = Dataset(suffix='after_3routes') ...
from segmentation.segmentation_abstract import Segmentation class Probabilistic_old(Segmentation): def precompute(self,datasetdscr,s_events,a_events,acts): ws= a_events.groupby('Activity')['Duration'].mean(numeric_only=False) L=10 w={} w[0]=min(ws) w[L]=ws...
""" earthpy.spatial =============== Functions to manipulate spatial raster and vector data. """ import os import sys import contextlib import warnings import numpy as np from shapely.geometry import mapping, box import geopandas as gpd import rasterio as rio from rasterio.mask import mask def extent_to_json(ext_ob...
#coding=utf-8 """ @Author: Freshield @Contact: yangyufresh@163.com @File: bagOfWords2Vec.py @Time: 2019-12-12 17:33 @Last_update: 2019-12-12 17:33 @Desc: None @==============================================@ @ _____ _ _ _ _ @ @ | __|___ ___ ___| |_|_|___| |_| | @ @ | __| ...
import time def do_my_sum(xs): sum = 0 for v in xs: sum += v return sum sz = 10000000 # Lets have 10 million elements in the list testdata = range(sz) t0 = time.clock() my_result = do_my_sum(testdata) t1= time.clock() print('my result = {0} (time taken = {1:.4f} seconds)' .format...
# Copyright 2019 Ondrej Skopek. # # 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 writing...
from django.shortcuts import render, redirect from .models import Task from django.views.generic import CreateView from .forms import Create_task from django.contrib import messages from django.contrib.auth.decorators import login_required from .serializers import TaskSerializer from .models import Task from rest_fram...
import re strings = ( "-a-", "-b-", "-x-", "-aa-", "-ab-", "--", ) for line in strings: match = re.search(r'-[abc]-', line) if match: print(line) print('=========================') for line in strings: match = re.search(r'-[abc]+-', line) if match: print(line) ...
## 함수 선언부 ## ## 변수 선언부 ## money, c500, c100, c50, c10 = [0] * 5 # 돈, 동전 500, 동전 100..... ## 메인 코드부 ## if __name__ == '__main__' : money = int(input('바꿀 돈 -->')) c500 = money // 500; money %= 500 c100 = money // 100; money %= 100 c50 = money // 50; money %= 50 c10 = money // 10; money %...
from django.shortcuts import render, redirect, HttpResponseRedirect from .models import User, Item from django.contrib import messages from django.contrib.auth import logout def index(request): return render(request, 'exam/index.html') def register(request): viewsResponse = User.objects.add_user(request.POST)...
from flask import Flask, request, render_template import pandas as pd import numpy as np import pickle app = Flask(__name__) model = pickle.load(open('model.pkl', 'rb')) test=pd.read_csv("insomniaa test.csv",error_bad_lines=False) x_test=test.drop('insomnia',axis=1) @app.route('/') def home(): return render_tem...
import sys input = sys.stdin.readline N, M = map(int, input().split()) count = dict() for _ in range(N): word = input().rstrip() if len(word) < M: continue if word in count: count[word] += 1 else: count[word] = 1 words = list(count.keys()) words.sort() words.sort(key=le...
""" Zemberek: Turkish Tokenization Example Java Code Example: https://bit.ly/2PsLOkj """ from jpype import JClass, JString TurkishTokenizer: JClass = JClass('zemberek.tokenization.TurkishTokenizer') TokenIterator: JClass = JClass( 'zemberek.tokenization.TurkishTokenizer.TokenIterator' ) Token: JClass = JClass('zem...
import re #for get_application_base_url from google.appengine.ext import db #for does_tweet_exist from storage import TWEETS # INPUT :: http://www.sample.co.uk:8080/folder/file.htm # OUTPUT :: http://www.sample.co.uk:8080 def get_application_base_url(current_url): regex = '(https?://[-\w\.]+(:[0-9]{4})?)' match = ...
# Author: Shubham Waghe # Roll No: 13MF3IM17 # Description: WSD-II Assignment-1 import numpy as np import matplotlib.pyplot as plt from random import gauss import Tkinter as tk import math # Given data READINGS_EACH_DAY = 400 desired_limit = 0.05 p = 0.2 RANGE_VALUE = 3 PLOT_RANGE = 2*p #Stopping criteria NO_OF_DAYS =...
''' 5125->1259. Handshakes That Don't Cross Difficulty: Hard You are given an even number of people num_people that stand around a circle and each person shakes hands with someone else, so that there are num_people / 2 handshakes total. Return the number of ways these handshakes could occur such that none of the hand...
#!/usr/bin/env python # -*- coding: iso-8859-1 -*- """DOCS HERE. """ # Copyright (C) 2010 # $Id: scene_object_bounding_box.py 1916 2006-11-21 17:21:05Z $ __version__ = "$Revision: 1916 $"[11:-2] # numpy lib import numpy as np # FrustumTracer CORE Classes from scene_element import * from scene_element_...
import unittest from api.sources.cptec.getter.cptec_api_getter import CptecAPIGetter class CptecAPIGetterTest(unittest.TestCase): def setUp(self): self.__cptec_api_getter = CptecAPIGetter(-22.87216997446473, -48.44871995614285) # Botucatu - SP def test_retrieving_data_from_api(self): self.a...
import sys def dfs(graph, vertex, visited): visited[vertex] = True global result result += 1 for around_vertex in graph[vertex]: if not visited[around_vertex]: dfs(graph, around_vertex, visited) node = int(input()) graph = [[] for _ in range(node + 1)] edge = int(input()) for _ in range(edg...
#dayNum.py #program that accepts a date as month/day/year, verifies that it is a valid date, and then calculates the corresponding day number. def main(): month,day,year = input("Enter date in format (mm/dd/yyyy)").split('/') month = int(month) day = int(day) year = int(year) dayN...
# # Working with files # def main(): # Open a file for writing and create it if it does not exists # f = open("textfile.txt", "w+") # w = write, + = create if not exists # Open a file for appending text at the end #f = open("textfile.txt", "a") # a = append # Write lines of data to a file ...
from time import time, localtime, sleep class Clock(object): """数字时钟""" def __init__(self, hour=0, minute=0, second=0): self._hour = hour self._minute = minute self._second = second @classmethod def now(cls): ctime = localtime(time()) return cls(ctime.tm_hour, ...
from threading import Thread from server_socket import ServerSocket from socket_wrapper import SocketWrapper from response_protocol import * from db import DB from config import * class Server(object): """服务器""" def __init__(self): # 初始化套接字 self.server_socket = ServerSocket() # 保存客户端连接...
import numpy as np from optimization import kernel_optim def get_representations(types=[]): representations = [] if types == []: representations.extend(['STRF', 'FFT', 'STFT', 'CQT']) return ['STRF', 'FFT', 'STFT', 'CQT'] if 'STRF' in types: representations.append('STRF') else:...
""" # Definition for a Node. class Node: def __init__(self, x: int, next: 'Node' = None, random: 'Node' = None): self.val = int(x) self.next = next self.random = random """ # Time: O(N), Space: O(N) class Solution: def copyRandomList(self, head: 'Node') -> 'Node': ans_head = prev...
#!/usr/bin/python3 # -*- coding: utf-8 -*- # @date : 2019/5/10 # @author : Rong Ya-feng # @desc : Chapter 1 : Programming Exercise1 # Case Study:Display the current time(GMT) """ import time currentTime = time.time() # obtain the total seconds since midnight, Jan 1, 1970 totalSeconds = int(currentTime...
# -*- coding: utf-8 -*- from django.test import ( Client, TestCase, ) from service_area_mozio.shapes.models import ( Polygon, Vertex, ) class PolygonTestCase(TestCase): def setUp(self): """Create basic instances""" line = Polygon.objects.create(name='line') Vertex.objects....
import win32api import cv2 import time import os import enum from .CBotDebugState import CBotDebugState from .extractGameMap import extractGameMap from .CNavigator import CNavigator from CMinimapRecognizer import CMinimapRecognizer class BotState(enum.Enum): IDLE = 0 MOVING = 1 BATTLE = 2 c...
has_player = False def vis_print(*kwargs, end="\n"): if not has_player: print(*kwargs, end=end) # ABSTRACT DECISION CLASS class Decision: """DO NOT INSTANTIATE!""" def __init__(self, agent): global has_player self.agent = agent if agent.get_name() == "Player": ...
from django.db import models class OneGame(models.Model): slug = models.SlugField(unique=True)
# --------------------------------------------------------------------------------------------------------------------- # sys import sys # --------------------------------------------------------------------------------------------------------------------- # system from math import sqrt, ceil # ------------------------...
from instance_recommender.inventory import Inventory from unittest import TestCase import json import pandas class TestInventory(TestCase): def __init__(self, methodName): super().__init__(methodName) self.source_path = 'inventory/instances.json' self.dest_path = '/tmp/test_inventory.json'...
def ordenar (): def calcularComision(ventatotal, Objetivo, Sueldoanual): if ventatotal < ((Objetivo*80)//100): comision=0 elif ventatotal >= ((Objetivo*80)//100) and ventatotal < Objetivo: comision= ((Sueldoanual*3)//100) elif ventatotal >= Objetivo: comision= ((Sue...
from src.knn.utils import convert_df_to_np from src.knn.main import classify def test_knn(test_df): np_arr, labels = convert_df_to_np(test_df) input_data = [1.0, 3.0] k = 2 result = classify(input_data, np_arr, labels, k) assert isinstance(result, str)
import sys def combi(n, m): if dp[n][m] == -1: if n == m or m == 0: dp[n][m] = 1 else: dp[n][m] = combi(n-1, m) + combi(n-1, m-1) return dp[n][m] n, m = map(int, sys.stdin.readline().split()) dp = [[-1 for _ in range(n+1)] for _ in range(n+1)] print(combi(n, m))
n = int(input()) for i in range(n): ox_list = input() ox_sum = 0 score = 0 for ox in ox_list: if ox == 'O': score += 1 else: score = 0 ox_sum += score print(ox_sum)