text
stringlengths
38
1.54M
#! /usr/bin/env python #coding=utf-8 from base.models import AppOperation from django.db import models from base.models import CachingModel from base.operation import Operation,ModelOperation from django.utils.translation import ugettext_lazy as _ from dbapp.datautils import filterdata_by_user from base.middleware imp...
""" This basically returns a list of all the palindromes from subsequences of a string""" def get_palindromes_for_string(string: str): if len(string) == 1: return [string] from pprint import pprint def get_i_j(l:list): len_l = len(l) if len_l == 2: return 0, 1 if ...
# STACK클래스 생성 class Stack: def __init__(self): self.myStack = [] def push(self, n): self.myStack.append(n) def pop(self): if self.empty() == 1: return else: self.myStack.pop() def size(self): return len(self.myStack) def empty(self)...
from django.conf import settings from django.core.mail import EmailMessage from django.core.management.base import BaseCommand from django.utils import timezone from common.helpers.constants import FrontEndSection from common.helpers.front_end import section_path from common.helpers.date_helpers import DateTimeFormats,...
from os import environ MONGO_SERVER = environ['MONGO_SERVER'] MONGO_USER = environ['MONGO_USER'] MONGO_PASSWORD = environ['MONGO_PASSWORD'] CONTRACT_ADDRESS = environ['CONTRACT_ADDRESS'] APP_ADDRESS = environ['APP_ADDRESS'] CONTRACT_PROVIDER = environ['CONTRACT_PROVIDER']
from guizero import App , Text, PushButton,yesno, warn, info, MenuBar, Picture app = App(title="trashbot ", height = 500, width = 700, bgcolor = "black") #Bienvenida al programa "Trashbot" join_the_trashbot= yesno("Welcome", "Do you want to join trashbot?") if join_the_trashbot == True: info("Welcome", "Than...
Mouse = ''' class Mouse: """STOP!!! DON'T USE THIS UNLESS YOU'RE REALLY SURE YOU KNOW HOW TO USE IT!! Nothing bad will happen, but it just won't really help you much. Peace. """ def __init__(self): """Mouse.__init__()""" ## button press things self.justpressed = (0,0,0) ...
import abc import torch from typing import Any, Callable, List, MutableMapping, Optional, Text, Tuple import math from functools import partial from multiprocessing import Pool import numpy as np from rdkit import Chem from rdkit import rdBase from rdkit.Chem import AllChem from rdkit import DataStructs import os ...
class Solution: def numSubarraysWithSum(self, A: List[int], S: int) -> int: l = 0 count = 0 ans = 0 currSum = 0 for r in range(len(A)): currSum += A[r] if A[r] == 1: count = 0 ...
import sys sys.path.append('../') from roleplay import * main.roleplayRun() #main.IllustrationTest()
from flask import Blueprint from flask import jsonify from api.utils import get_zone_facts_select_columns import logging from flask_cors import cross_origin def construct_filter_blueprint(name, engine): blueprint = Blueprint(name, __name__, url_prefix='/api') @blueprint.route('/filter/', methods=['GET']) ...
# Se RECOMIENDA INDENTAR un DICCIONARIO para que sea mas CLARO de LEER. # Se RECOMIENDA FINALIZAR un DICCIONARIO con una COMA FINAL(,) person = { 'first_name': 'javier', 'last_name': 'ramon', 'age': 41, 'city': 'teruel', } print('Person Profile:') print('---------------') pri...
from collections import defaultdict def findMin(nums): add = 0 store = defaultdict(int) glbMin = float('inf') for i in range(len(nums)): add = add + nums[i] store[i] = add for i in range(len(nums)): value = store[len(nums)-1]-store[i] -store[i] if value > 0 and value in nums: glbMin = min(glbMin, value)...
from __future__ import unicode_literals from functools import partial from .handlers import store_initial, action_receiver, TrackHistoryModelWrapper from django.db.models.signals import post_init, post_save, pre_delete from .manager import TrackHistoryDescriptor from .settings import ( TH_DEFAULT_EXCLUDE_FIELDS, ...
import numpy as np import pandas as pd import logging import warnings from pandas.core.indexes.base import Index from typing import ( Iterable, List, ) import artm from topicnet.cooking_machine import Dataset from topicnet.cooking_machine.models import TopicModel _logger = logging.getLogger() # TODO: see...
import enum import re from enum import unique from typing import ( Any, Callable, Dict, Literal, NamedTuple, Optional, Sequence, Type, TypeVar, Union, cast, get_type_hints, ) from django import forms as django_forms from django.forms.widgets import Widget from django.htt...
from validator import data_validator as dv from importlib import reload import config import main import os import pathlib import csv import pandas as pd from pytorch_utils.utils import train_best_model, evaluate folder = 'all-spectrograms-symlinks/99.5' cwd = os.getcwd() spectrogram_path = os.path.join(cwd, 'data', f...
# import argv from sys module from sys import argv # unpack argv to two variables script, filename = argv # open 'filename', defined above via argv, # and assign contents to variable 'txt' file_object = open(filename) # print text & variable 'filename' print "Here's your file %r: " % filename # print the output...
# Copyright 2021 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import annotations from dataclasses import dataclass from typing import Iterable, Iterator from pants.backend.scala.subsystems.scalac import Scalac from pants.backend.sca...
from django.contrib import admin from stud.models import AddStudent # Register your models here. admin.site.register(AddStudent)
# inspired from classification_tsv, an example from the allennlp repository from typing import Dict, Iterable, List import logging from overrides import overrides import itertools import re from allennlp.common.file_utils import cached_path from allennlp.data import DatasetReader, Instance from allennlp.data.fields i...
""" 1223. Dice Roll Simulation A die simulator generates a random number from 1 to 6 for each roll. You introduced a constraint to the generator such that it cannot roll the number i more than rollMax[i] (1-indexed) consecutive times. Given an array of integers rollMax and an integer n, return the number of distinc...
from app import create_app if __name__ == '__main__': app = create_app() from app.views import _populate_ranks _populate_ranks()
from bs4 import BeautifulSoup import methods import requests import urllib import parse import json import time import re import urllib.request def uri_exists_get(uri: str) -> bool: try: response = requests.get(uri) try: response.raise_for_status() return True excep...
import pytest from delta_crdt.rga import RGA from .helpers import transmit @pytest.fixture def rga(): return RGA("test id") def test_rga_can_be_created(rga): pass def test_rga_starts_empty(rga): assert len(rga) == 0 def test_add_right(rga): rga.add_right(None, "a") assert rga == ["a"] de...
import codecs import os from os import listdir from jinja2 import Environment, FileSystemLoader from src.jsonclass import JsonClass from src.layers.javalayer import JavaClassLayer from src.layers.markdownlayer import MarkdownClassLayer from src.layers.phplayer import PhpClassLayer from src.layers.swiftlayer import Swif...
import re text = "sangeeth1-23sj@gmail.com random alan@gmail.net string" pattern = re.compile("[a-zA-Z0-9\.\-\_]+@[a-zA-Z0-9]+\.[a-zA-Z]+") result = pattern.search(text) result = pattern.findall(text) print(result)
import re from random_line import random_line_from_file from oyoyo import helpers history = {} MAXHISTORY = 10 def get_nick(fullnick): return fullnick.split("!",1)[0] def echo(client, nick, message): if message.lower() == "ping": helpers.msg(client, nick, "pong") def whoami(client, nick, message): ...
import psycopg2 db_pools = {} def get_conn(dbname): db_cons = db_pools.setdefault(dbname, set()) if not db_cons: return psycopg2.connect(database=dbname) else: return db_cons.pop() def put_conn(dbname, conn): db_cons = db_pools.setdefault(dbname, set()) db_cons.add(conn) class db_conn(object): def execute(...
import os from transformers import (T5Config, T5ForConditionalGeneration, Trainer, TrainingArguments, HfArgumentParser) from data import read_parallel_split def main(training_args, args): if not os.path.isdir(args.model_dir): os.makedirs(args.model_dir) config = T5Confi...
import random from rollbar.lib import build_key_matcher from rollbar.lib.transform import Transform class ScrubTransform(Transform): suffix_matcher = None def __init__(self, suffixes=None, redact_char='*', randomize_len=True): super(ScrubTransform, self).__init__() if suffixes is not None and...
import logging import datetime import traceback from autobahn.twisted.util import sleep import inject from mcloud.application import ApplicationController from mcloud.container import PrebuiltImageBuilder, InlineDockerfileImageBuilder, VirtualFolderImageBuilder from mcloud.deployment import DeploymentController, IDeplo...
# O(1) constant def func_constaant(values): return values[0] lst = [1,2,3] print(func_constaant(lst)) #---------------------------------- # O(n) Linear def func_linear(lst): for val in lst: print(val) print(func_linear(lst)) #---------------------------------- #O(n^2) Quadratic def func_quad...
def readFile(): f=open('/Users/ArpitAggarwal/workspace/jython-basics/com/test.csv', 'r') print f for line in f: print line.rstrip() f.close def copyCSVToTextFile(): f=open('/Users/ArpitAggarwal/workspace/jython-basics/com/test.csv', 'r') output = open('/Users/ArpitAggarwal/workspace/jyt...
class Solution(object): def wiggleMaxLength(self, nums): """ :type nums: List[int] :rtype: int """ if not nums: return 0 if len(nums)==1: return 1 if len(nums)==2: return 2 if nums[0]!=nums[1] else 1 ans=len(nums) prev=nums[0] up=-1 ...
from copy import copy import re class Issue(object): def __init__(self,json): self.__key = json['key'] self.__blocks = [i['outwardIssue']['key'] for i in json['fields']['issuelinks'] if 'outwardIssue' in i.keys()] self.__blocked_by = [i['inwardIssue']['key'] for i in json['fields']['issueli...
############################### # Count symbols in the message ############################### import pprint # Set up some message message = 'This is a test message.' # Initialize empty dictionary count = {} # For each symbol in the message ... for symbol in message: # ... if the symbol IS NOT present in the di...
from fourthpack.pages.home.pizza_page import PizzaPage import unittest import pytest @pytest.mark.usefixtures("OneTimeSetUp", "SetUp") class orderPizzaTest(unittest.TestCase): def __init__(self, driver): super().__init__(driver) self.driver = driver @pytest.fixture(autouse=True) def objectSe...
# Angkan Biswas # 16.04.2020 # To mark face in taken picture. # Note: 1. Download 'haarcascade_frontalface_default.xml' # $ wget https://github.com/opencv/opencv/blob/master/data/haarcascades/haarcascade_frontalface_default.xml # 2. Install 'opencv-contrib-python' # $ pip install opencv-contrib-python import cv2 mode...
## # This module requires Metasploit: https://metasploit.com/download # Current source: https://github.com/rapid7/metasploit-framework ## class MetasploitModule < Msf::Exploit::Remote Rank = ExcellentRanking include Msf::Exploit::Remote::HttpClient include Msf::Exploit::CmdStager def initialize(info = {}) ...
from __future__ import unicode_literals from pyramid.httpexceptions import HTTPBadRequest from pyramid.view import view_config from ... import models from ...db import db_transaction from ...renderers import file_adapter from ..base import ControllerBase from ..base import view_defaults from .resources import FileInd...
instructions = map(lambda x: x.strip(), open('input.txt').readlines()) keypad = [ ' ', ' 1 ', ' 234 ', ' 56789 ', ' ABC ', ' D ', ' ' ] code = '' current = [3, 1] for instruction in instructions: for move in instruction: if move == 'U' and keypad[current[0]-1][current[1]] != ' ': ...
#!/usr/bin/python3.5 ''' This program takes EHMM lab files as input and writes numeric text features as output Inputs: [1] Unique phones list [2] EHMM lab directory Outputs: [1] Output directory Note1: This is intended for seq2seq/end2end learning and hence durations are not used. Author: Sivanand Achanta Date ...
# Licensed to the StackStorm, Inc ('StackStorm') under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use th...
# -*- coding: utf-8 -*- """ Created on Fri Nov 15 19:29:29 2019 @author: CEC """ a = int (input("Ingrese un numero entre -10 a 10: ")) v=[] for i in range(-11, 10): i+=1 v.append(i) print(v[4][1]) ''' if a <= i: print("No es mayor que", i) elif a>= i: print("Si es ma...
""" General-purpose utility functions. """ import re def camelcase_to_underscore(camelcase_str): """ Replace CamelCase with underscores in camelcase_str (and lower case). """ underscore = re.sub(r'(.)([A-Z][a-z]+)', r'\1_\2', camelcase_str) lower_underscore = re.sub(r'([a-z0-9])([A-Z])', r'\1_\2'...
from keystoneclient.access import AccessInfoV2 from keystoneclient.auth.identity import BaseIdentityPlugin from keystoneclient.auth.identity.access import AccessInfoPlugin from keystoneclient.auth.identity.v2 import Password from keystoneclient.session import Session import keystoneclient.v2_0.client as keystone_sclien...
from nltk.corpus import wordnet, stopwords from nltk.corpus import sentiwordnet as swn from nltk.tokenize import word_tokenize stop_words = set(stopwords.words('english')) def getDetails(word): syns = wordnet.synsets(word) print("Synsets: {}".format(syns)) for syn in syns: print("Synset name:" + ...
from flask import Flask from flask_sqlalchemy import SQLAlchemy app = Flask(__name__) username = "root" pwd = "root" ip = "127.0.0.1" port = "3306" database = "hogwarts" # 设置mysql 链接方法是 app.config['SQLALCHEMY_DATABASE_URI'] = f'mysql+pymysql://{username}:{pwd}@{ip}:{port}/{database}?charset=utf8' # 解决warning问题 app.co...
from flask import Flask from config import db class Applicant(db.Model): __tablename__ = 'applicants' id = db.Column(db.Integer, primary_key=True) fname = db.Column(db.String(50), index=False, unique=False, nul...
from django.urls import path from .views import HomePage, ContactPage urlpatterns = [ path('', HomePage.as_view(), name='home_detail_home'), path('contact/', ContactPage.as_view(), name='home_detail_contact'), ]
""" single root plots - compares 2 root uptake profiles in one plot (root xylem potential, soil-root interface potential, resulting sink) from xls result files (in results/) """ import matplotlib.pyplot as plt import numpy as np import pandas as pd add_str = "_comp" # "_wet", "_dry" # fnames = ["singleroot_cyl_con...
# @Copyright(C), OldFive, 2020. # @Date : 2021/3/24 0024 15:30:05 # @Author : OldFive # @Version : 0.1 # @Description : # @History : # @Other: # ▒█████ ██▓ ▓█████▄ █████▒██▓ ██▒ █▓▓█████ # ▒██▒ ██▒▓██▒ ▒██▀ ██▌▓██ ▒▓██▒▓██░ █▒▓█ ▀ # ▒██░ ██▒▒██░ ░██ █▌▒████ ░▒██▒ ▓██ █▒░▒███ # ▒██ ██░▒██░ ...
#Binary search #As opposed to linear search it assigns a left and right value to a sorted array, halves it, and assigns a middle value, then checks if the mid value is the searched value # if so => search successful # if not => whether the searched value is bigger or smaller than the mid value, it changes the positi...
# -*- coding: utf-8 -*- """ =============================================== Project Name: Working with Python ----------------------------------------------- Developer: Operate:--Orion Analysis Team-- Program:--Vector Data Analysis Team-- ............................................... Author(Analyst):朱立松--Mr...
# Generated by Django 2.0.6 on 2020-09-15 11:09 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('index', '0001_initial'), ] operations = [ migrations.AlterField( model_name='tboo...
#importing libraries here import pandas as pd import numpy as np import seaborn as sns #import data df = pd.read_csv('fake_reg.csv') X = df[['feature1', 'feature2']].values y = df['price'].values from sklearn.model_selection import train_test_split #spliting data X_train, X_test, y_train ,y_test = train_test_...
# Generated by Django 2.2 on 2019-05-26 08:19 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('hist', '0003_auto_20190525_2113'), ] operations = [ migrations.AlterField( model_name='decision', name='decisionDate',...
from django.conf import settings as django_settings from rest_framework import permissions from rest_framework.compat import is_authenticated class IsOwnerOrDeny(permissions.BasePermission): """ Custom permission to only allow owners of an object to edit it. """ def has_permission(self, req...
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import logging import tornado.ioloop import tornado.web import tornado.escape from tornado.options import define, options import config from handlers import uimodules import routers def config_logging(): level = config.app.logging.get("level") fmt = c...
print("1 : Getting datatype of any value--------- ") x=67 # print("Type of x is : ",type(x)) print (type(x)) print Complex=1j print (type(Complex))
from PySide6 import QtGui, QtWidgets, QtCore import pyqtgraph as pg import sys, math, time from collections import deque import libmapper as mpr ''' TODO show network interfaces, allow setting show metadata ''' class Tree(QtWidgets.QTreeWidget): def __init__(self): super(Tree, self).__init__() sel...
from selenium.webdriver.common.by import By class BasePageLocators: BASE_PAGE_LOADED_LOCATOR = '' QUERY_LOCATOR = (By.NAME, 'q') GO_LOCATOR = (By.ID, 'submit') INPUT_SUBMIT_LOCATOR = (By.XPATH, "//input[@type='submit']") class LoginPageLocators(BasePageLocators): COMPREHENSIONS = (By.XPATH, '//...
n=int(input()) for i in range(n): a=input() a=a.upper() cnt=(len(a)//2) for j in range(cnt): if a[j]!=a[-1-j]: print("#%d No"%(i+1)) break else: print("#%d Yes"%(i+1)) #s[::-1]->리버스 시켜주는 구문
# FIXME python2 from __future__ import absolute_import, unicode_literals from future.utils import python_2_unicode_compatible import logging from copy import deepcopy from datetime import datetime from lxml.builder import E from lxml.etree import Element, _Element from lxml.objectify import ObjectifiedElement import...
# -*- coding: utf-8 -*- """ Created on Wed Feb 12 16:40:22 2020 @author: salman """ import selenium from selenium import webdriver from selenium.webdriver.chrome.options import Options import os from os import path from selenium.common.exceptions import NoSuchElementException from selenium.common.except...
"""add rank to issue Revision ID: 4d5027f9faac Revises: 6d3439e14660 Create Date: 2019-03-23 13:37:47.267698 """ from alembic import op import sqlalchemy as sa from pabu.tools import get_table # revision identifiers, used by Alembic. revision = '4d5027f9faac' down_revision = '6d3439e14660' branch_labels = None depen...
import pandas as pd import numpy as np df = pd.read_excel("input.xlsx") print(df) series_obj = list(df.columns) print("Choose sequence From this :- ",*series_obj[:-1]) user_series_ip = [] print() print("Enter timeseries sequence: ") for i in range(len(series_obj)-1): x = input("=> ") user_series_ip.append(x...
import random def play(): words = ["python", "java", "kotlin", "javascript"] word = random.choice(words) found = set() print("H A N G M A N") print() for i in range(8): print(generate_display(word, found)) guess = input("Input a letter: ") if guess in word: ...
#!/usr/bin/env python3.7 """ Mastering Object-Oriented Python 2e Code Examples for Mastering Object-Oriented Python 2nd Edition Chapter 17. Example 2. """ import unittest # SQLite testing # ========================= # This is integration testing, not unit testing. # Integration means we use the database # instead ...
# coding=utf-8 # Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team. # Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved. # # 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 cop...
import re from flask import session from app.lib.coins import Coin from app import app, db from passlib.hash import pbkdf2_sha256 class Players: __initial_balance = app.config['INITIAL_BALANCE'] def __init__(self): pass @staticmethod def exists(username): res = db.select('players'...
# cars = ['mazda', 'volvo', 'bmw'] # cars.append('jigul') # del cars[-1] # print(cars[-1].title()) # --- # cars = ['mazda', 'volvo', 'bmw'] # cars.append('jigul') # cars.remove('jigul') # print(cars[-1].title()) #--- # cars = ['mazda', 'volvo', 'bmw'] # cars.append('jigul') # cars.sort...
from numpy import * #importa a biblioteca para se trabalhar com vetores medias = array(eval(input("Digite as notas dos estudantes: "))) #entrada das medias dos estudantes while(size(medias) > 1): #o laco while eh necessaria para se repetir a pergunta indefinidamente aprovado = 0 #contador de aprovados, nota > 5 mon ...
from time import time import glm from itbl import Ray, Shader from itbl.accelerators import SDF, BVHAccel from itbl.cameras import TrackballCamera from itbl.shapes import Box from itbl.util import get_color, get_data from itbl.viewer import Application, Viewer from itbl.viewer.backend import * from wilson import * im...
import sys import sqlite3 from sqlite3 import Error import time import threading from urllib.parse import urlparse import socket from socket import error as socket_error """ function: init() parameter: None return: none This function will get the value for clustercfg and ddlfile then declare them as global values """ d...
############################################################################## # # Copyright (c) 2001, 2002 Zope Corporation and Contributors. # All Rights Reserved. # # This software is subject to the provisions of the Zope Public License, # Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution. # T...
# Generated by Django 2.0.13 on 2019-10-15 08:09 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('cc', '0006_authentication'), ] operations = [ migrations.RenameField( model_name='issuetracker', old_name='Components', ...
from typing import List class Solution: def merge(self, intervals: List[List[int]]) -> List[List[int]]: intervals.sort(key=lambda x: (x[0], x[1])) res = [intervals[0]] for i in range(1, len(intervals)): if intervals[i][0] <= res[-1][1]: res[-1][1] = max(...
from unittest import TestCase from BribeNet.bribery.temporal.action.multiBriberyAction import MultiBriberyAction, \ BriberyActionsAtDifferentTimesException, BriberyActionsOnDifferentGraphsException, \ NoActionsToFormMultiActionException from BribeNet.bribery.temporal.action import * from BribeNet.bribery.tempo...
import torch # dataset 参数 batch_size = 128 # word to sequence 参数 min_word_count = 5 #最小词频 max_word_count = None #最大词频 max_features = None #除未知字符和填充字符外,词的最大个数 max_sentence_len = 20 #一个句子的最大长度 embedding_dim = 100 #embedding后每个单词的维度 # LSTM 网络参数 hidden_size = 64 num_layer = 2 bidirectional = True if bidirectional: ...
#!/usr/bin/env python # coding: utf-8 # In[1]: from control import * import numpy as np import matplotlib.pyplot as plt from scipy import signal from scipy.signal import * from scipy.signal import cont2discrete, lti, dlti, dstep # In[2]: #reference signal t = np.linspace(0, 1, 50) yd = 9*np.sin(3.1*t) ; yd[49] ...
# -*- coding: utf-8 -*- """ Created on Wed Jul 3 14:35:53 2019 @author: Antonin """ import numpy as np import matplotlib.pyplot as plt import pickle as pkl import seaborn as sns sns.set(style="ticks") path="C:/Users/Antonin/Documents/Documents/ENS 2A/Stage M1/Results/2019-07-15/ManualRates/MNIST/...
from django.conf import settings from django.utils import timezone from api.user.constants import USER_ACTIVITY_EVENT_TYPES from api.user.models import UserActvitiyLog class UserActivityLogMiddleware(object): def __init__(self, get_response): self.get_response = get_response def __call__(self, reque...
# -*- coding:utf-8 -*- from . import FlaskConfig class DevelopmentConfig(FlaskConfig): """开发模式下的配置""" # 查询时会显示原始SQL语句 SQLALCHEMY_ECHO = True ENV = 'development'
# -*- coding:utf8 -*- """ Created on 16/9/26 上午11:46 @author: fmc """ from __future__ import nested_scopes, generators, division, absolute_import, with_statement, print_function import logging from rest_framework import serializers from ..models.cluster import ClusterModel, ClusterTemplateModel, ClusterTemplateVersi...
from dateutil.parser import parse from datetime import datetime import pandas as pd import numpy as np import hashlib import time import datetime from datetime import date, timedelta import requests, re, json import bs4 from bs4 import BeautifulSoup import pymongo from pymongo import MongoClient from apscheduler.sch...
from django.db import models from django.contrib.auth.models import User Category = [ ('データサイエンス', 'DataScience'), ('機械学習', 'Machine Learning'), ('ディープラーニング', 'Deep Learning'), ('データ分析', 'Data Analysis'), ('Python 基礎', 'Python Basic'), ('Django', 'Django'), ('環境構築', 'environ_set'), ('その...
from django.urls import path import cart.views urlpatterns = [ path('add/<kimchi_id>', cart.views.add_to_cart, name="add_to_cart_route"), path('view/', cart.views.view_cart, name="view_cart_route"), path('remove/<kimchi_id>', cart.views.remove_from_cart, name="remove_from_cart_route"), path('...
""" ******************************************************************************* * Ledger Blue * (c) 2016 Ledger * * 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....
''' This module contains logic of pixel transforation. which include gamma correction factor calualtion and transformation logic. Adaptive gamma correction techinqe ''' import cv2 import numpy as np import math import logging logger=logging.getLogger(__name__) def calculate_gamma_factor(image): ''' calculat...
#!/usr/bin/env python # -*- coding: utf-8 -*- import socket import sys import struct import json import urllib2 def gmap(x,y, id): f = open('/var/www/html/%s.html' % id,'w') gmap_page = """ <!DOCTYPE html> <html> <body> <h1>Your tracker at Electrodragon.com</h1> <div id="googleMap" style="width:100%;heigh...
import wx from SeChainController.MainController import MainController from SeChainController import Property class MainApp(wx.App): def OnInit(self): frame = MainFrame() frame.drow_frame(None, -1, 'Se-Chain') frame.Show(True) Property.ui_frame = frame self.SetTopWindow(frame...
import pandas as pd df = pd.read_csv("C:/bank-additional-full.csv", sep=";") df2 = df[:30] print(df2) print(type(df2)) df3 = df2['"job"'] ###Simple test### import pandas as pd df4 = pd.DataFrame({'cid':['c01', 'c02', 'c03'], 'time': [43, 543, 34]}) print(df4) print(df4['time']) print(type(df4)) ### Ir...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from json_field import JSONField from django.db import models from util.randz import make_8_key class Discharge(models.Model): uuid = models.CharField(blank=True, unique=True, max_length=50) # Message date = models.DateTimeField(null=True,...
# -*- coding: utf-8 -*- def is_new_ip(c_key, cache, ip): aid_ip_pool = cache.get(c_key) ip_new = True if aid_ip_pool: if isinstance(aid_ip_pool, set): ip_new = ip not in aid_ip_pool if not aid_ip_pool: aid_ip_pool = set() return ip_new, aid_ip_pool
from flask import Flask from flask_restful import Resource, Api from flask_restful import reqparse from flask import json app = Flask(__name__) api = Api(app) parser = reqparse.RequestParser() parser.add_argument('userName') parser.add_argument('passWord') parser.add_argument('userArg', location='args') class User(o...
import json import spacy from test_set_with_placeholder import test_with_placeholder from test_set_with_placeholder import test_with_placeholder_name_and_surname from test_set_with_placeholder import test_with_placeholder_common_word def get_ground_truths(text, ents): gt = [] for start, end, _ in ents['entiti...
from __future__ import unicode_literals from django.db import models # Create your models here. from django.db import models class Teacher(models.Model): first_name=models.CharField(max_length=30) last_name=models.CharField(max_length=30) office_details=models.CharField(max_length=60) phone=models.Cha...
from tkinter import * import datetime from folderfinder import findfolder hotelfolder = findfolder() import ctypes import json user32 = ctypes.windll.user32 screensizex = int(0.2*user32.GetSystemMetrics(0)) screensizey= int(0.4*user32.GetSystemMetrics(1)) root = Tk() root.geometry(str(screensizex)+"x"+str(scr...