text
stringlengths
8
6.05M
"""ispeak_crmm URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/dev/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class...
# # Copyright 2017 Bleemeo # # bleemeo.com an infrastructure monitoring solution in the Cloud # # 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/...
#!env python3 # -*- coding: utf-8 -*- import shelve with shelve.open('shelve.db') as db: db['name'] = 'python' db['dict'] = {"A": 3, "B": (2, 5), "C": "Hello"} db['list'] = [2,4,5,6,1,2,3] with shelve.open('shelve.db') as db: print(db['name']) print(db['dict']) print(db['list'])
""" EE219 Winter 2017 Project 2 - Task f to Task j Zeyu Li lizeyu_cs@foxmail.com 2017-02-07 This is the Task-g "Multinomial Naive Bayes" of Project 2 In this task, we fit the "comp" data set and "rec" data set separately, and predict the target separately, too. """ import project2_toolkit from sklearn.naive_bayes i...
import numpy as np from sklearn.base import BaseEstimator, TransformerMixin from tomotopy import LLDAModel def _counts_to_str(counts, min_length=0): documents = [] n_words, n_docs = counts.shape for d in range(n_docs): doc = [] for n in range(n_words): doc += [str(n)] * counts[...
#import sys #input = sys.stdin.readline def main(): N = int( input()) A = list( map( int, input().split())) B = [(A[i], i) for i in range(N)] B.sort( reverse=True) ANS = [-1]*(N+1) m = 0 M = N-1 ans = 0 for b, i in B: if i-m <M-i: ans += b*(M-i) M -= 1...
import requests from bs4 import BeautifulSoup # format을 활용한 bs4 for i in range(1, 57): base_url = 'https://www.kookmin.ac.kr/site/resource/board/scholarship/?&pn={}' page_url = base_url.format(i - 1) req = requests.get(page_url) html = req.text soup = BeautifulSoup(html, 'html.parser') ...
#!/usr/bin/env python """ Map reduce implementations of QR decompositions """ from functools import reduce import numpy as np def qr_mapped(X, n=None): """Mapper for QR decomposition Args: X: matrix chunk n: number of rows after which to perform QR decomposition. If X has less th...
from django.contrib import admin from .models import Event, City admin.site.register(Event) admin.site.register(City)
""" Specifies routing for the application""" from flask import render_template, request, jsonify from app import app from app import database as db_helper @app.route("/waters", methods=['GET']) def get_waters(): """ get all waters from table """ try: waters = db_helper.fetch_waters() result = {...
import pandas as pd import numpy as np from selenium import webdriver from selenium.common.exceptions import NoSuchElementException, WebDriverException, TimeoutException import csv import tqdm from tqdm import tnrange, tqdm_notebook tqdm.monitor_interval = 0 import lxml.html import lxml import glob from time impo...
#-*- coding: utf8 -*- import crypt def testPass(cryptPass): salt=cryptPass[0:2] dicFile=open('dictionary.txt','r') a=1 for word in dicFile.readlines(): word = word.strip('\n') cryptWord = crypt.crypt(word,salt) a += 1 if (cryptWord==cryptPass): print "[+] Pas...
"""Objective In this challenge, we're going to use loops to help us do some simple math. Check out the Tutorial tab to learn more. Task Given an integer, n, print its first 10 multiples. Each multiple n x i(where 1 <= i <= 10) should be printed on a new line in the form: n x i = result. """ if __name__ == '__main__'...
#!/usr/bin/env python # Jamie Bodeau # Imports ------------------------------------------------- import sys # Classes ------------------------------------------------- # Functions ----------------------------------------------- def getKey(banks): return ",".join(map(str, banks)) def reallocate(banks): #...
# This file is only intended for development purposes from kubeflow.kubeflow.cd import base_runner base_runner.main(component_name="central_dashboard", workflow_name="cdash-build")
# Generated by Django 3.0.8 on 2020-07-29 06:05 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('musictest', '0008_auto_20200727_2000'), ] operations = [ migrations.AlterField( model_name='post', name='song', ...
from heapq import heappush, heappop import functools @functools.total_ordering # give a comparison method, this class decorator supplies the rest. class Book: def __init__(self, title, due_date): self.title = title self.due_date = due_date self.returned = False # for returned early def __lt__(self, other): ...
# -*- coding: utf-8 -*- # Author Yunguan 'Jake' Wang # 07/16/2018 """ Read a table from synapse, common formats such as txt, csv or excel """ import synapseclient import os import pandas as pd from io import StringIO def read_file(fn): """Read local files, either csv, txt or excel. """ if fn[-3:] == 'csv':...
from django.shortcuts import render from aplicativo.models import Tab,Adsense from aplicativo.signals.visualizacao import visualizacao from django.http import HttpResponseRedirect from django.core.urlresolvers import reverse def home(request): try: tab = Tab.objects.get(namespace=namespace) except: tab = Tab.obj...
import os import click import tarfile import shutil import logging import sonosco.common.audio_tools as audio_tools import sonosco.common.path_utils as path_utils from sonosco.datasets.download_datasets.create_manifest import create_manifest from sonosco.common.utils import setup_logging from sonosco.common.constants ...
import os import sys import unittest.mock dirname = os.path.dirname(__file__) module_path = os.path.join(dirname, 'contrib', 'dummy_contrib.py') cls_name = 'FooContribEncoder' @unittest.SkipTest class TestContribModule(unittest.TestCase): def setUp(self): self.yaml_path = os.path.join(os.path.dirname(__fi...
from ED6ScenarioHelper import * def main(): # 柏斯 CreateScenaFile( FileName = 'T1130 ._SN', MapName = 'Bose', Location = 'T1130.x', MapIndex = 1, MapDefaultBGM = "ed60011", Flags = 0, Ent...
#!/usr/bin/python3 """ a Python script that sends an email in a POST request to a URL""" import urllib.request import sys if __name__ == '__main__': data = "email=" + sys.argv[2] data = data.encode('ascii') req = urllib.request.Request(sys.argv[1], data) with urllib.request.urlopen(req) as response: ...
import pandas as pd import numpy as np import pickle class DataCleaner(object): def __init__(self, data_frame): """ Instantiate with a one row dataframe (from HTML cleaning class) ex: X = DataCleaner(data_frame) X_vals = X.get_array_of_values() """ ...
import unittest from nose_parameterized.parameterized import parameterized from conans.test.utils.tools import TestClient from conans.paths import CONANFILE tool_conanfile = """ import os from conans import ConanFile class Tool(ConanFile): name = "Tool" version = "0.1" def package_info(self): s...
import pickle import collections import numpy as np import pandas as pd import spacy from sklearn.model_selection import train_test_split from sklearn.model_selection import StratifiedShuffleSplit from sklearn.linear_model import LogisticRegression from sklearn.metrics import f1_score from sklearn.feature_extraction.te...
#!/usr/bin/env python #-*-coding:utf-8-*- ''' A Pythagorean triplet is a set of three natural numbers, a < b < c, for which, a2 + b2 = c2 For example, 32 + 42 = 9 + 16 = 25 = 52. There exists exactly one Pythagorean triplet for which a + b + c = 1000. Find the product abc. ''' import numpy as np import timeit import ...
from django.shortcuts import redirect from django.core.urlresolvers import reverse class UserMiddleware(object): def process_request(self, request): # Запрещаем удалённому пользователю что либо делать, кидая его на личную страницу и оставив возможность восстановления и выхода if (request.user.is...
import random original_num = random.randint(2,89) print(original_num) def guess_checker(count): user_guess = int(input("Enter your guess no:-")) if(user_guess < original_num): print("Your guess Number is low") count = count +1 guess_checker(count) elif(user_guess > original_num): ...
# Copyright PA Knowledge Ltd 2021 # For licence terms see LICENCE.md file import unittest import copy from verify_control_header import VerifyControlHeader class VerifyControlHeaderTests(unittest.TestCase): control_header_as_dict = dict(Session_Id=b'\x01\x00\x00\x00', Frame_Coun...
# -*- coding: utf-8 -*- """ Created on Mon Jan 20 15:50:29 2020 @author: spriyadarshini """ import pandas as pd import matplotlib.pyplot as plt import re import numpy as np data = pd.read_csv('train_fwYjLYX.csv') def add_datepart(df, fldname, drop=True): fld = df[fldname] if not np.issubdtype(fld.dtype, ...
# -*- coding: utf-8 -*- """ MetaFiles. Like Flask-FlatPages or Flask-JSONPages, but reusable and library/markup agnostic. The original Flask-FlatPages was written by Simon Sapin: <https://github.com/SimonSapin/Flask-FlatPages> """ import itertools import os # IO utils: def walk_filepaths(folder): """ Walk 'f...
import subprocess class Git(object): """ Generic git command executor using subprocesses. Commands are white space separated. Returns the return code of the process Usage: git('pull origin master') """ def __new__(cls, commands): # type: (str) -> int return subprocess.call...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Mar 9 20:15:39 2020 @author: kodiuser """ from flask import Flask, render_template app = Flask(__name__, static_folder='static', template_folder='templates') @app.route('/', methods=['GET']) def home(): return render_templat...
from keras import applications from keras import backend as K import numpy as np from scipy.misc import imsave import matplotlib.pyplot as plt import matplotlib.image as mpimg img_width = 128 img_height = 128 # Load model model = applications.VGG16(include_top=False, weights='imagenet') layer_dict = dict([(layer.nam...
from Instrucciones.DeclaracionReferencia import DeclaracionReferencia from Instrucciones.DeclaracionArr1 import DeclaracionArr1 from Instrucciones.Declaracion import Declaracion from Abstract.NodoAST import NodoAST from Instrucciones.Continue import Continue from Instrucciones.Return import Return from TS.TablaSimbolos...
from distutils.core import setup from setuptools import find_packages setup(name='copter', version='0.1.1', description='Offline CLI password manager', author='Dzmitry Talkach', author_email='chakmidlot@gmail.com', url='https://www.python.org/sigs/distutils-sig/', packages=find_pac...
from tkinter import * cf = Tk() cf.geometry("700x600") cf.title("Connect Four") cf.configure(background='blue') turn = 'red' def toggle(): global turn if turn=='red': turn ='yellow' else: turn = 'red' def column_1(event): global turn if frame_6.cget('bg') == 'gray87': fr...
# /usr/bin/env python # coding:utf-8 # author:ZhaoHu import socketserver import os import re import sys import json import subprocess # import time sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) from config import settings from lib import commons ip_port = ('0.0.0.0', 10086) CURRENT_USE...
# the inclusion of the tests module is not meant to offer best practices for # testing in general, but rather to support the `find_packages` example in # setup.py that excludes installing the "tests" package import unittest from sample.simple import add_one class TestSimple(unittest.TestCase): def test_add_one...
import os import sys import unittest from io import StringIO from coala_json.reporters.cli import cli class CliTestCase(unittest.TestCase): def setUp(self): """ Set up parser """ self.parser = cli.create_parser() def test_with_empty_args(self): """ User passes...
from __future__ import absolute_import, unicode_literals from celery import Celery import os user = os.getenv('LOGIN', 'admin') password = os.getenv('PASSWORD', 'mypass') hostname = os.getenv('HOSTNAME', 'localhost') broker_url = f'amqp://{user}:{password}@{hostname}:5672/' app = Celery('tasks', broker=broker_url, n...
print('hi') print('no no')
from service.model import Base from sqlalchemy import Column, Integer, String from enum import unique # 클래스가 테이블과 매핑된다. class User(Base): # 테이블명 __tablename__ = 'user' # 컬럼 id = Column(Integer, primary_key=True) name = Column(String(50),unique = True) password = Column(Stri...
from django.contrib import messages from django.contrib.sites.shortcuts import get_current_site from django.template.loader import render_to_string from django.conf import settings from django.core.mail import send_mail from django.shortcuts import render, render_to_response, get_object_or_404 from django.http import H...
#!/usr/bin/python3 ''' Makes a request and prints information about the body of the response ''' from urllib.request import urlopen URL = 'https://intranet.hbtn.io/status' if __name__ == '__main__': with urlopen(URL) as r: body = r.read() print("Body response:") print("\t- type:", type(b...
""" Base class for Riemannian metrics. """ import logging import numpy as np import geomstats.vectorization as vectorization EPSILON = 1e-5 class RiemannianMetric(object): """ Base class for Riemannian metrics. Note: this class includes sub- and pseudo- Riemannian metrics. """ def __init__(sel...
import random import time import copy import heapq #-------------------------------sorting algorithms----------------------------- #big O average, worst, best case is O(N^2) #--> but with a flag, best case is O(N) def bubble_sort(array): for j in reversed(range(0, len(array))): flag = True ...
import os import itertools import cv2 as cv import numpy as np import PIL from PIL import Image PATH_TO_FILES = '/home/kelsonl/Desktop/Dataset/' what_to_find = "Chinos" TEXT_LOCATION_LABEL = PATH_TO_FILES + 'bbox_list.txt' def create_list(text_location_label, keyword): our_file = open(text_location_label, 'r...
#print(a) def dic(**num): for d in range(0,21): print(d,':',d**2) dic(dict())
def authenticate(uname,pword): if uname=="stuy" and pword=="2016": return True else: return False
from numpy import linspace, sin, pi, cos, linalg, zeros, random import matplotlib.pyplot as plt from interpolate import interpolate1D def assignment1(x, fnVal, baseSize, kernal): [interpX, interpFn] = interpolate1D(x, fnVal, baseSize, var, kernal) return [interpX, interpFn] if __name__ == '__main__': x = li...
from enum import IntEnum import attr import numpy as np from simulation.cell import CellData, CellList from simulation.coordinates import Point, Voxel from simulation.grid import RectangularGrid from simulation.module import Module, ModuleState from simulation.modules.fungus import FungusCellData, FungusCellList from...
print(3*'suriya')#to repeat a string print('\nsuriya')#here \n is new line print(r'\nsuriya')#here it is a raw sting whatever inside gets printed print("'ssg'")#to print single use them inside double print('"ssg"')#to print double use them inside single name='suriya' print(name[0]) print(name[0:]) print(name[-1]) print...
""" Copyright Matt DeMartino (Stravajiaxen) Licensed under MIT License -- do whatever you want with this, just don't sue me! This code attempts to solve Project Euler (projecteuler.net) Problem #4 Largest palindrome product A palindromic number reads the same both ways. The largest palindrome made from the product of...
from incremental import Version __version__ = Version("towncrier", 16, 1, 0) __all__ = ["__version__"]
from bs4 import BeautifulSoup import requests import csv import timeit def main(): players_file = "player_names.txt" # create list of all distinct player names with open(players_file, 'r') as f: players = f.read().split('\n') fieldnames = ["Name", "Full Name", "Match Type", "Batting Average"...
# -*- coding: utf-8 -*- import pandas as pd import glob pathway ="/Users/Desktop/data/" mycsv = glob.glob(pathway+'*.csv') RT1=[] RT2=[] RT3=[] RT4=[] RT5=[] RT6=[] Ans=[] AnsSpeed=[] ID =[] Sub=[] Type=[] Version=[] for onefile in mycsv: marks = pd.read_csv(onefile) r1 =marks.column...
""" """ import numpy.random import math import array import numpy def makePoissonModel(model,lam=1): """ Modifies the model passed as parameter, replacing all bins with random values taken from a Poisson distribution with lambda = lam Returns modified model for chaining""" model.bins = (numpy.rando...
lst = [] lst.append("Tony") lst.append("Is") lst.append("Best") print(lst) choice = int(input("Your Fucking Choice : ")) if choice==1: position = int(input("Enter Position : ")) element = input("Enter Element To Insert : ") lst.insert(position,element) print(lst) if choice==2: remove = input("...
#!/usr/bin/env python import sys import gzip file = sys.argv[1] file_stream = gzip.open(file, 'r') num_samples = 0 try: for line in file_stream: if line.startswith("#"): sys.stdout.write(line) continue fields = line.split("\t", 9) if len(fields) < 10: sys.stdout.writ...
""" @File: re_use_all.py @CreateTime: 2020/2/27 上午11:52 @Desc: 正则的使用,match findall search http://www.codeceo.com/article/20-regular-expressions.html 常用的正则表达式 """ import re import requests from setting import HEADERS class ReAllUse(object): def __init__(self): self.url_str = "https://author.baidu.com/ho...
#!/usr/local/anaconda3/bin/python3 from __future__ import division import sys sys.path.insert(0, '/home/machen/face_expr') try: import matplotlib matplotlib.use('agg') except ImportError: pass import argparse import numpy as np import os import chainer from chainer import training from chainer.datasets ...
# # Copyright (C) Patrik Jonell and contributors 2021. # Licensed under the MIT license. See LICENSE.txt file in the project root for details. # import json import os import re from datetime import datetime, timedelta from pathlib import Path from fastapi import FastAPI, Form, Query from fastapi.staticfiles import St...
import sys import os import time import tensorflow as tf import numpy as np from sar_model import SARModel # from data_provider.data_generator import get_batch # from data_provider.lmdb_data_generator import get_batch from data_provider import data_generator from data_provider import lmdb_data_generator fro...
""" Test cases for Order Model Test cases can be run with: nosetests coverage report -m """ import unittest import os from app.models import Order, OrderItem, DataValidationError, db from app import app, service, get_env_variable DB_NAME = get_env_variable('DB_NAME') DB_USER = get_env_variable('DB_USER') DB_PAS...
# -*- coding: utf-8 -*- """Tests for the correlation measures. MIT License Copyright (c) 2022, Daniel Nagel All rights reserved. """ import os.path import numpy as np import pytest from beartype.roar import BeartypeException from sklearn.preprocessing import StandardScaler import mosaic # Current directory HERE = ...
from django.contrib import admin # Register your models here. from .models.transaction import Transaction admin.site.register(Transaction)
import networkx as nx from networkx.exception import NetworkXError from networkx.algorithms.bipartite import configuration_model \ as bipartite_configuration_model from warnings import warn # from IPython import embed import numpy as np class Frame(nx.DiGraph): ''' This class defines a k-frame random gra...
import os from PIL import Image import glob import numpy as np import cv2 if(not os.path.isdir('edgeEnhance')): os.makedirs('edgeEnhance') for dir in ['akiec', 'bcc', 'bkl', 'df', 'mel', 'nv', 'vasc']: os.makedirs('edgeEnhance/' + dir) akiec_filenames = glob.glob('train/akiec/*.jpg') bcc_filenames = glob.glob('tr...
from PyQt5 import QtCore, QtGui, QtWidgets from GirişEkranı import Fo from PyQt5 import QtCore, QtGui, QtWidgets from PyQt5.QtCore import QBasicTimer from PyQt5.QtCore import QObject,QPointF,QPropertyAnimation,pyqtProperty import sys class Ui_MainWindow(object): def setupUi(self, MainWindow): MainWindow...
from django.shortcuts import render, reverse from django.http import HttpResponseRedirect import time from random import randint, uniform from .models import Pokemon, Trener, Kurz, Druzinka, Ucet, Akcia from .forms import TreningForm, ObchodForm, JedalenForm, SpravcaForm def bezi(): z = zaciatok() k = koniec...
import pandas as pd import numpy as np from random import sample import datetime as dt import matplotlib.pyplot as plt def pos_expected_points(row): ''' Calculates expected total points for the offense, based on over-under line, spread, and team ''' if row['posteam'] == row['favorite']: re...
import orun.addons class Addon(orun.addons.Addon): version = '0.1' installable = True name = 'crm' verbose_name = 'CRM' dependencies = ['sales_team']
import tensorflow as tf from graph_lm.models.networks.utils.dag_utils import message_passing from ...sn import sn_fully_connected, sn_kernel def discriminator_dag_supervised( latent, dag, dag_bw, params, idx, tags, tag_size, weights_regularizer=None, is_training=True): # latent (N, L, D) ...
# -*- coding: utf-8 -*- # Generated by Django 1.11 on 2018-05-08 13:03 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('authentication', '0031_auto_20180508_1244'), ] operations = [ migrations.AddF...
def draw(x,y): try: print(x,y) except ValueError: print("The exception is Value error") except IndexError: print("There is an index error") pass except NameError: print("There is an name error") except RuntimeError: print("There is an Run-Ti...
from globals import getGlobalsInstance globalsInstance = getGlobalsInstance() BASE_URL = globalsInstance.getApiSetting('idealizar.agenda.base-url') REQUEST_TIMEOUT = int(globalsInstance.getApiSetting('idealizar.agenda.request-timeout'))
import pandas as pd import math import ipywidgets as widgets import warnings import graphviz from IPython.display import display, clear_output class eLABJournalPager: def __init__(self, api, title, location, request, index, records, item_handler=None): """ Internal use only: initialize pa...
############################# #파이썬 기본 - 예외처리 ############################# print('='*100) try: print("1") a = 1/0 print("2") except Exception as e: print("3") print(e) finally: print("4")
import socket import select import sys server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server.connect(('0.0.0.0', 5000)) while True: message = input('> ') server.send(message.encode()) message = server.recv(2048) print(message) server.close()
from django.db import models class PapalStats(models.Model): server = models.CharField(max_length=255) flag = models.CharField(max_length=255) level = models.CharField(max_length=10) date = models.DateField() data = models.TextField() md5 = models.CharField(max_length=500)
# -*- coding: utf-8 -*- # Define your item pipelines here # # Don't forget to add your pipeline to the ITEM_PIPELINES setting # See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html import json import pymysql from twisted.enterprise import adbapi class Scrapy1Pipeline(object): def __init__(self, dbpoo...
""" TODO continue migrating code from bfModifiers cleaning up as we go with the aim to use this in a test objects to construct and orient an arm joint chain from guides """ import fbx from brenpy.cg import bpEuler from brenfbx.utils import bfFbxUtils def get_euler_cls(fbx_rotate_order): """Find brenpy bpEu...
# Copyright (c) 2007-2014 by Enthought, Inc. # All rights reserved. __version__ = '4.2.1' __requires__ = [ 'traitsui', 'configobj', ]
def permutationCoef(n,k): p = [[0 for i in range(k+1)] for j in range(n+1)] for i in range(n + 1): for j in range(min(i,k) + 1): if (j==0): p[i][j] = 1 else: p[i][j] = p[i - 1][j] + (j*p[i - 1][j-1]) if (j<k): p[i][j +...
# # test_io.py # unit tests for the crayon.io python module # # Copyright (c) 2018 Wesley Reinhart. # This file is part of the crayon project, released under the Modified BSD License. import numpy as np import os test_path = os.path.abspath(os.path.dirname(__file__)) build_path = os.getcwd() src_path = test_path[:tes...
#!/usr/bin/python3 """ accepts 3 arguments (mysql username, password and database name) and lists all states from that database whose names start with N """ import sys import MySQLdb def main(argv): """connects to a given mysql database and lists filtered states from it""" conn = MySQLdb.connect(host="localho...
""" Created by Guillaume WELLER on 09/01/2020 """ """ Last modifications on 23/12/2020 by Guillaume WELLER """ ######### ######### ######### ######### ####9#### ######### ######### ######### ######### ########################## ### Modules à importer ### ########################## import os import datetime...
import numpy as np from scipy.constants import physical_constants from scipy.special import expit k_b = physical_constants['Boltzmann constant in eV/K'][0] def fermi_dirac_distribution(temperature, mu, energy): """ Parameters ---------- energy : Energy (eV). temperature : Tempera...
"""query.py Mostly copied from ../../query_index.py (bad design, must be changed). """ import sys import codecs import json if __name__ == '__main__': from elastic import Index else: # there is a better way I thought, but no time to find it now if sys.version_info.major == 2: from elastic import...
""" Specification types for resolving identifiers in execution contexts. """ from .types import ( get_primitive_type, Undefined, ObjectType, NumberType, BooleanType, StringType ) from .objects import PropertyDescriptor from .exceptions import ESTypeError, ESReferenceError class Binding(object): """ A name...
import os import pandas as pd import numpy as np import sqlalchemy from sqlalchemy.ext.automap import automap_base from sqlalchemy.orm import Session from sqlalchemy import create_engine from flask import Flask, jsonify, render_template from flask_sqlalchemy import SQLAlchemy app = Flask(__name__) app.config['DEBUG...
def main(): n, k = map(int, input().split()) circular_list = [] for i in range(1, n+1): circular_list.append(i) pop_idx = 0 answer = [] while len(circular_list) > 0: pop_idx = (pop_idx + k - 1) % len(circular_list) elem = circular_list.pop(pop_idx) answer.append(...
from AppKit import NSWorkspace import time awn = "" while True: nwn = (NSWorkspace.sharedWorkspace().activeApplication()['NSApplicationName']) if awn != nwn: awn = nwn print(awn) time.sleep(10)
import datetime import json DATA = {"datetime": datetime.datetime(1961, 4, 12, 2, 7, 0, 123456)} class DatetimeEncoder(json.JSONEncoder): def default(self, obj): try: return super().default(obj) except TypeError: return f'{obj:%Y-%m-%dT%H:%M:%S.%fZ}' json.dumps(DATA, cl...
# Import all the libraries import pandas as pd import numpy as np import geopandas as gpd from sklearn.preprocessing import PolynomialFeatures, StandardScaler from sklearn import datasets, linear_model from sklearn.model_selection import train_test_split, KFold, cross_val_score from sklearn.linear_model import Logisti...
def fanctorial (n): if n ==0: return 1 else: a = n * fanctorial(n-1) return a
from django.contrib import admin from vpn_user.models import Users from vpn_user.models import Log admin.site.register(Users) admin.site.register(Log)
from config.global_parameters import default_model_name from utils import load_pkl import numpy as np from model_utils import lstm_model import matplotlib.pyplot as plt def train_classifier(genres=['Chases','Dance','Eating','Fight','Heated_Discussions','Normal_Chatting','Romance','Running','Tragic'], model_name=defa...