text
stringlengths
38
1.54M
# Generated by Django 2.2 on 2020-05-28 16:06 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('Fabricas', '0004_auto_20200527_2245'), ] operations = [ migrations.CreateModel( name='Prueba', fields=[ ...
from . import utilities components_manager_mock = { "port": 8082, "bind": "0.0.0.0", "hostname": "manager", "container": "wukongsun/moon_manager:v4.3.1", "external": { "port": 30001, "hostname": "88.88.88.2" } } openstack_keystone_mock = { "url": "http://keystone:5000/v3"...
__author__ = 'tang' from hashlib import sha256 def encode(password): gen = sha256() gen.update(password) return gen.hexdigest()
"""travellerProject URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/3.0/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Cl...
valores = [3,3,3,2,2,2,1,1,1,1,] #Se hace con pila y cola def contarMasRep(lista): contar = contarMasRep(valores)
import cv2 import dropbox import time import random start_time = time.time() def take_snapshot(): number = random.randint(0,100) videoCamera = cv2.VideoCapture(0) result = True while(result): ret,frame = videoCamera.read() image_name = "img"+str(number)+".png" ...
import argparse import numpy as np from scipy.misc import logsumexp from numpy import logaddexp LETTER_TO_INDEX = {'A':0, 'C':1, 'G':2, 'T':3, '^':4, '$':5} def build_transition_matrix(num_states, motif_len, p, q): transition_matrix = np.zeros((num_states, num_states)) transition_matrix[0, 1] = q transiti...
""" GROMACS ANALYSER (for molecular dynamics trajectories) This script is for analysing the trajectories obtained by gromacs software. It will use the MDtraj module for such analysis. There will be some flag options which the user can pick on and the files and plots will be saved in a new ...
#!/usr/bin/env python # -*- coding: utf-8 -*- import json from alipay.aop.api.constant.ParamConstants import * class RefundSubFee(object): def __init__(self): self._refund_charge_fee = None self._switch_fee_rate = None @property def refund_charge_fee(self): return self._refund_c...
from django.shortcuts import render, redirect, HttpResponse from .models import AgileCard, AgileCardForm from django.contrib.auth.decorators import login_required @login_required def cards(request): if request.method == 'POST': new_card = AgileCardForm(request.POST) new_card.save() return ...
from __future__ import print_function import pandas as pd import numpy as np from keras.preprocessing import sequence from keras.models import Sequential from keras.layers import Dense, Embedding, Dropout, LSTM from keras.preprocessing.text import Tokenizer from keras.preprocessing.sequence import pad_sequences from sk...
import random aa = [0,0,0,0] # 4칸 리스트 # C사용할 때는 메모리 확보를 해놔야 함 for i in range(4): num = random.randint(0,99) aa[i] = num print(aa)
# -*- coding: utf-8 -*- """ Created on Sat Jul 20 14:25:52 2019 @author: VAIBHAV """ import numpy as np import matplotlib.pyplot as plt import pandas as pd dataset = pd.read_csv('Salary_Data.csv') x = dataset.iloc[:,:-1].values y = dataset.iloc[:,1].values #SPLIT DATASET INTO TRAINING AND TEST SET f...
from django.shortcuts import render from django.shortcuts import HttpResponse from django.shortcuts import redirect # Create your views here. accountInfo = {'admin':'123', 'Manchester':'921'} onlineAccount = [] def gontoLogin(request): info = {} if 'account' in request.COOKIES: info['...
import decomp_network import plot_pf_output pflotran_exe='../pflotran-interface/src/pflotran/pflotran' simlength=365 pools = [ decomp_network.decomp_pool(name='cellulose',CN=50,constraints={'initial':1e2},kind='immobile'), decomp_network.decomp_pool(name='HRimm',constraints={'initial':1e-20},kind='immobile'), decom...
import re from os import path import glob import chardet from .base import Base class Source(Base): def __init__(self, vim): super().__init__(vim) self.name = 'latex-bib' self.filetypes = ['tex'] self.input_pattern = r'(\\cite{|\\citep{|\\citet{)[^"#\'()={}%\\]*?' self.inp...
import unittest import pyfribidi class TestFribidi(unittest.TestCase): text = "سلام test تست" result = 'ﺖﺴﺗ test ﻡﻼﺳ' def test_log2vis(self): result = pyfribidi.log2vis(self.text) self.assertEqual(self.result, result) if __name__ == '__main__': unittest.main()
"""data_analysis URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/3.0/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class...
import cv2 import os import numpy as np import time from time import sleep import copy from multiprocessing.pool import ThreadPool from collections import deque print(cv2.__version__) print('Esc - End') # define framerate and period of framerate framerate = 236 showTime = int((1 / framerate) * 1000) ...
""" Operadores Lógicos and, or, not in e not in """ """ nome = "Juliana" if 'Ju' not in nome: print('Executei.') else: print("Existe o texto.") """ usuario = input('Nome de usuário: ') senha = input('Senha do usuário: ') usuario_bd = 'Juliana' senha_bd = '123456' if usuario_bd == usuario and senha_bd == sen...
import pandas as pd import numpy as np def preprocessing(data, keep_columns, target_column, target_values): """ Create Week_number from WeekStarting Drop two unnecessary columns: WeekStarting, Revenue """ df = data[keep_columns].fillna('other') # First, we need to address any imbalan...
class ListaPlanograma(object): lista_planograma = [ { "id":1, "nome":"planograma 1", "pdm":{"id":1} }, { "id":2, "nome":"planograma 2", "pdm":{"id":2} }, { "id":3, "nome":"planogr...
import re import logging from copy import copy from bs4 import BeautifulSoup from .util import download_page, rebuild_string class CamBridge: base_url = 'https://dictionary.cambridge.org/dictionary/' def __init__(self, language): self.language = language self.prefix_url = self.base_url + ...
import pandas as pd import numpy as np import shapefile import sys import math import bokeh.plotting as bp # Hack: append common/ to sys.path sys.path.append("../common") sys.path.append("../queries") import anova # Given a shapeObject return a list of list for latitude and longitudes values # - Handle scenari...
# Generated by Django 3.1.1 on 2020-09-06 23:11 import cloudinary.models from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('account', '0004_auto_20200906_1315'), ] operations = [ migrations.AddField( model_name='profile', ...
import sys from random import randint def generate_numbers(filename, numbers): #arr = [] s = '' for i in range(int(numbers)): s += str(randint(1, 1000)) + ' ' with open (filename, "w") as f: f.write(s) def main(): generate_numbers(sys.argv[1], int(sys.argv[2])) if __name__ == '...
#!/usr/bin/python import collections as col f = open('input', 'r') c = 0 # count def find_hash(str): res = col.Counter(str) res = sorted(res.items(), key=lambda pair: (-pair[1], pair[0])) res = list(c[0] for c in res) return ''.join(res)[:5] for l in f: str = l.strip().replace('[','-').replace(']','').split('-...
import numpy as np from statistics import mean def calibrate(time, amplitude): ###################################### # Enter calibration code here: ###################################### rail = 0 risingedge = [] fallingedge = [] diffrise = [] i = 0 k = 1 #edge detection and stam...
"""Utilities for getting native speaker audio from Forvo.com. `get_mp3_link` queries Forvo.com for a given word in a given language, and returns the download URL of the audio file from the XML response. """ __author__ = 'shor.joel@gmail.com (Joel Shor)' import logging import urllib2 import xml.etree.ElementTree as ...
from sklearn.manifold import TSNE import seaborn as sns import matplotlib.pyplot as plt import numpy as np import matplotlib matplotlib.use('tkagg') def visualize(train_data_before, test_data_before, train_data_after, test_data_after, args): z = np.concatenate((train_data_before, train_data_after, test_data_before...
# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! import grpc from proto import user_pb2 as proto_dot_user__pb2 class UserStub(object): # missing associated documentation comment in .proto file pass def __init__(self, channel): """Constructor. Args: channel: A grpc...
# 파일에 쓰기 : 파일을 쓰기 모드(w)로 열고 , # 파일객체의 write() 함수를 이용하여 파일에 출력 # data='hello' # f = open('file2.txt','w') # 파일 객체f # f.write(data) # f.close() data='안녕하세요' f = open('file2.txt','w',encoding='utf-8') # 파일 객체f f.write(data) f.close() # 한글이 깨져 보임 #utf-8 형식으로 저장 : 한글이 깨지지 않음
import pygame as pg import settings from constants import OUT_FSCR, OUT_NONE, OUT_QUIT class Controller(): def __init__(self): self._bdown_events = set() # buttons newly pressed this frame self._bpressed = set() # buttons still pressed right now. def poll(self): """ ...
# 包含Settings类,这个类只包含方法_init_(),它初始化控制飞船外观与飞船速度的属性 class Settings(): """存储外星人入侵的所有设置的类""" def __init__(self): """初始化游戏设置""" # 屏幕设置 self.screen_width = 1200 # 窗口大小 self.screen_height = 800 # 窗口大小 self.bg_color = (230,230,230) # 窗口背景色 # 飞船设置 self.shi...
import gym import random import numpy as np import pdb from pybrain.tools.shortcuts import buildNetwork from pybrain.structure import SoftmaxLayer,SigmoidLayer from pybrain.datasets import SupervisedDataSet from pybrain.supervised.trainers import BackpropTrainer def getAction(probs): index = np.argmax(probs) return ...
''' @Author: your name @Date: 2020-06-17 13:06:18 @LastEditTime: 2020-06-19 15:13:45 @LastEditors: Please set LastEditors @Description: In User Settings Edit @FilePath: /final/task2_crnn/main.py ''' import argparse import os from Trainer import Solver from dataLoader import get_loader from torch.backends import cudnn i...
class Solution: def calculate(self, s: str) -> int: def update(op, num): if op == '+': stack.append(num) elif op == '-': stack.append(-num) elif op == '*': stack.append(stack.pop() * num) elif op == '/': ...
class Solution: def minSubArrayLen(self, s, nums) -> int: if sum(nums) < s: return 0 #min_len = len(nums) start = 0 result = len(nums) sum_nums = 0 for i in range(len(nums)): sum_nums += nums[i] while (sum_nums >= s): ...
import threading import time sem = threading.Semaphore() global s s = 2 def thing1(): time.sleep(1) s = s + 3 sem.release() def thing2(): print(s) t = threading.Thread(target = thing1) t.run() t1 = threading.Thread(target = thing2) t1.run()
import logging import random import numpy as np import pandas as pd from sklearn.model_selection import train_test_split from pathlib import Path from random import choice, sample MAX_TOKENS_PER_DOC = 256 def get_train_test_apikeys(df, split=0.20): df = pd.read_pickle(df) # add weights to the apikeys; thes...
# # Copyright (c) 2023 Airbyte, Inc., all rights reserved. # import base64 import logging from typing import Any, Iterable, List, Mapping, Optional, Set import pendulum import requests from airbyte_cdk.models import SyncMode from cached_property import cached_property from facebook_business.adobjects.abstractobject i...
import discord import os import requests import json import random from replit import db import asyncio import logging from discord.ext import commands import random class Fun(commands.Cog): def __init__(self, client): self.client = client #hi @commands.command() async def hi(self, ctx): embed=disco...
valores = list() for cont in range(0,10): valores.append(int(input(f"Informe o valor {cont+1}: "))) print(valores) for indice,cont in range(0,10): if valores[itens] % 2 == 0: valores.pop(itens) #valores remove (cont) print(f"Lista sem os valores pares: {valores}\n\n")
from django import forms from rbac import models from django.utils.safestring import mark_safe # 角色的Form class RoleForm(forms.ModelForm): class Meta: model = models.Role fields = ['name'] widgets = { 'name': forms.widgets.Input(attrs={"class": 'form-control'}) ...
a=[3,1,2,4] c=[] d=[] for i in range(len(a)): if(a[i]%2==0): c.append(a[i]) c.sort() else: d.append(a[i]) d.sort() c=c+d print(c)
from flask import Flask, jsonify, request from flasgger import Swagger app = Flask(__name__) app.config['SWAGGER'] = { 'title': 'API doc', 'uiversion': 3, 'openapi' : '3.0.2' } @app.route('/ping', methods=['GET']) def ping(): return "The service is up and running :)" @app.route('/api', methods=['P...
# -*- coding: utf-8 -*- from django.conf.urls import url import events.views urlpatterns = [ url(r'^accounts/lists', events.views.edit_subscription_lists), url(r'^events/_edit', events.views.edit_subscription_list), url('^events/_load_events$', events.views.events_list_items, name='events_list_items'), ...
# -*- coding: utf-8 -*- """ Created on Thu Apr 25 10:36:13 2019 @author: LXI-294-VINU """ from PyQt5 import QtCore, QtGui, QtWidgets from PyQt5.QtCore import QObject, pyqtSlot from MainWindowV13 import Ui_MainWindow import sys from Model import Model class MainWindowUIClass( Ui_MainWindo...
# coding: utf-8 import sys sys.path.insert(0, '/srv/http/LINE-bot') from chat import app as application
# !pip -q install nltk requests # # TODO please clean me up, OO me. This is raw notebook sludge. # import requests import os import random import numpy as np import pandas as pd import nltk import json import re from tqdm import tqdm import sys from sklearn.feature_extraction.text import CountVectorizer from sklearn.fe...
from django.http import Http404 from django.shortcuts import render, get_object_or_404 from .models import Album # Create your views here. def index(request): all_albums = Album.objects.all() return render(request, 'music/index.html', {'all_albums': all_albums,}) def detail(request, album_id): album = ...
# create function for determining prime number def is_prime(number): for i in range(2,number): if (number % i) == 0: return False return True print(is_prime(3)) print(is_prime(25)) #list empty_list = [] my_list1 = [1,2,3] print(my_list1) my_list1.append(4) print(my_list1) empty_list.ap...
from django import forms from django.contrib.auth.forms import UserCreationForm from .models import StoreUser class StoreUserCreationForm(UserCreationForm): def __init__(self, *args, **kwargs): super(StoreUserCreationForm, self).__init__(*args, **kwargs) for visible in self.visible_fields(): ...
#!/usr/bin/python # -*- coding:utf8 -*- # @Author : MrTuo # @Time : 2017/10/4 下午9:04 # @File : Save2JSONbyBeautifulSoup.py # @Software : PyCharm # 使用BeautifulSoup解析网页,存储为json格式,解析盗墓笔记首页'http://seputu.com/'为例 import json import requests import sys from bs4 import BeautifulSoup reload(sys) sys.setdefaultencoding('utf-8'...
# -*- coding: utf-8 -*- from reportlab.lib.enums import TA_JUSTIFY from reportlab.graphics.barcode import code39, code128, code93 from reportlab.pdfbase import pdfmetrics from reportlab.pdfbase.cidfonts import UnicodeCIDFont from reportlab.pdfbase.ttfonts import TTFont from reportlab.lib.styles import getSampleS...
# python自己实现 # import cv2 as cv # from scipy import signal # import numpy as np # import math # # # # n阶的二项展开式系数,构建一维高斯平滑矩阵 # def getsmooth(n): # smooth = np.zeros([1, n], np.float32) # for i in range(n): # smooth[0][i] = math.factorial(n - 1) / (math.factorial(i) * math.factorial(n - i - 1)) # retu...
# coding: utf-8 __author__ = "sunxr" __version__ = "V1.0" class Workbench: """友工程后台外框架元素定位""" SELECT = ("xpath", ".//*[@id='username']/span[3]") # 下拉按钮 USERNAME = ("xpath", ".//*[@id='username']/span[2]") # 当前登录用户名 LOGOUT = ("xpath", ".//*[@id='moreMenu']/li[5]/a") # 注销 APPCENTER = ("xpath",...
from csv import DictWriter import cPickle as pickle pfields = ['id', 'title', 'nickname', 'fname', 'mname', 'lname', 'suffix'] pgmfields = ['person_id', 'program'] divfields = ['person_id', 'division'] pfile = open('people.csv', 'w') pwriter = DictWriter(pfile, fieldnames=pfields, extrasaction='ignore') pgmfile = o...
# !/usr/bin/env python # -*- coding:utf-8 -*- __author__ = 'bit4' __github__ = 'https://github.com/bit4woo' import httplib import re import time import requests #https://developer.github.com/v3/search/#search-repositories class search_github: def __init__(self, word, limit, useragent, proxy=None): self.e...
#coding:utf-8 from PyQt4.QtCore import pyqtSignal, QObject from collections import deque from threading import Lock class QTypeSignal(QObject): sendmsg = pyqtSignal(object)#定义一个信号槽,传入一个参数位参数 def __init__(self): QObject.__init__(self)#用super初始化会出错 def run(self): self.sendmsg.emit('send')#发信...
from keras.models import Model from keras.layers import Conv2D, MaxPool2D, Input, concatenate, Dense, Flatten, BatchNormalization from keras.optimizers import Adam, RMSprop from keras.callbacks import ReduceLROnPlateau from keras_applications.resnet import ResNet101 from keras import backend, layers, utils, models # re...
from rest_framework import serializers from .models import Profile, Project, countries, categories, technologies, colors class ProfileSerializer(serializers.ModelSerializer): class Meta: model = Profile fields = '__all__' class ProjectSerializer(serializers.ModelSerializer): class Meta: ...
class Fighter: def __init__(self): self.health = 100 self.attacks = {} def receiveEffects(self, effects): self.health -= effects def getAttackOptions(self): return self.attacks.keys() def getAttackEffects(self, attack): return self.attacks[attack] class T...
# 导入 HttpResponse 模块 from django.http import HttpResponse from .models import PeopleRequest from django.shortcuts import render from django.http import JsonResponse
alpha = 1 CHOSUNGS = [u'ㄱ',u'ㄲ',u'ㄴ',u'ㄷ',u'ㄸ',u'ㄹ',u'ㅁ',u'ㅂ',u'ㅃ',u'ㅅ',u'ㅆ',u'ㅇ',u'ㅈ',u'ㅉ',u'ㅊ',u'ㅋ',u'ㅌ',u'ㅍ',u'ㅎ'] JOONGSUNGS = [u'ㅏ',u'ㅐ',u'ㅑ',u'ㅒ',u'ㅓ',u'ㅔ',u'ㅕ',u'ㅖ',u'ㅗ',u'ㅘ',u'ㅙ',u'ㅚ',u'ㅛ',u'ㅜ',u'ㅝ',u'ㅞ',u'ㅟ',u'ㅠ',u'ㅡ',u'ㅢ',u'ㅣ'] JONGSUNGS = [u'',u'ㄱ',u'ㄲ',u'ㄳ',u'ㄴ',u'ㄵ',u'ㄶ',u'ㄷ',u'ㄹ',u'ㄺ',u'ㄻ',u'ㄼ',u'ㄽ',u'ㄾ'...
import renmas.core scene = renmas.core.Scene() geometry = renmas.core.ShapeDatabase() mat_db = renmas.core.MaterialDatabase() light_db = renmas.core.LightDatabase() import renmas.integrators renderer = renmas.core.Renderer() ren = renmas.core.RendererUtils(renderer) log = renmas.core.log
#N 枚のカードがあります. i 枚目のカードには, a iという数が書かれています. #Alice と Bob は, これらのカードを使ってゲームを行います. ゲームでは, Alice と Bob が交互に 1 枚ずつカードを取っていきます. Alice が先にカードを取ります. #2 人がすべてのカードを取ったときゲームは終了し, 取ったカードの数の合計がその人の得点になります. 2 人とも自分の得点を最大化するように最適な戦略を取った時, Alice は Bob より何点多く取るか求めてください. n = int(input()) i = map(int, input().split()) i_list = [num fo...
__author__ = 'thor' import numpy as np import io import pandas as pd import itertools from collections import Counter from nltk.corpus import wordnet as wn def print_word_definitions(word): print(word_definitions_string(word)) def word_definitions_string(word): return '\n'.join( [ '%d: ...
import datetime def get_interval(day): distance_to_friday = day.isoweekday() - 5 if distance_to_friday > 0: start = day - datetime.timedelta(days=(distance_to_friday + 7)) # start of interval end = day - datetime.timedelta(days=distance_to_friday) # end of interval else: start = day...
from tqdm import tqdm from environment.config import * from environment.which_arff_dataset import which_arff_dataset from tqdm import tqdm from strategies.pyHard.pyhard_unlabeled_framework import pyhard_unlabeled_framework from copy import deepcopy from environment.results_to_file import result_to_file from thre...
"""DAG to execute data extract, transform, and load pipeline from Amazon S3 to Amazon Redshift""" from datetime import datetime, timedelta import os from airflow import DAG from airflow.operators.dummy_operator import DummyOperator from airflow.operators import (StageToRedshiftOperator, LoadFactOperator, ...
from django.conf.urls import url, include from django.urls import path from .models import UnmatchedAutamaResource, AccountsResource, RegistrationResource, MessagingResource, MyMatchesResource from tastypie.api import Api v1_api = Api(api_name='v1') v1_api.register(UnmatchedAutamaResource()) v1_api.register(AccountsRe...
import unittest from threading_tools import SynchronizedNumber NUM_TRIALS = 2500 class TestSynchronizedBasicMath(unittest.TestCase): # # testing __neg__() # def test_sync_neg(self): sync_num1 = SynchronizedNumber(50.0) res_sync_num = -sync_num1 assert res_sync_num == -50, '...
import tensorflow as tf from tensorflow.keras.layers import Conv2D def block(num_filter, input_shape): block1 = tf.keras.Sequential() block1.add(Conv2D(num_filter,(1,1),strides=1,activation='relu')) block1.add(Conv2D(num_filter,(3,3),strides=2,padding="same",activation='relu')) block1.add(Conv2D(num_fi...
''' Created on Nov 12, 2018 @author: hols ''' import sys a, b = sys.argv[1:3] fa = open(a, 'r') fb = open(b, 'r') la = fa.readlines() lb = fb.readlines() inter_ab = [] a_w_b = [] b_w_a = [] ka = [] kb = [] for l in la: if not l in ka: ka.append(l) if l in lb: if not (l in inter_ab): ...
# coding=utf-8 # Smallest multiple # Problem 5 # https://projecteuler.net/problem=5 # # 2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder. # What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20? from functools import r...
import boto3 import json import os import requests import sys import tempfile import urllib3 sas_omm_protocol = 'http' def s3_client(access_key, secret_key, url): if s3_client.s3_client != None: return s3_client.s3_client s3_client.s3_client = boto3.client('s3', endpoint_url=url, ...
import logging import socket import numpy as np from asml.autogen.services import StreamService from asml.autogen.services.ttypes import ComponentType from asml.network.stream import StreamClient from asml.network.registry import RegistryClient from asml.network.server import Server from asml.parser.factory import Par...
''' namespace src.finance.SelectOrdering ''' ######################################################################## # SelectOrdering.Date ######################################################################## class Date(): def title(self): return 'Date' def sortOrder(self): re...
# -*- coding: utf-8 -*- # # Copyright (c) 2019, Intel Corporation. All rights reserved. # SPDX-License-Identifier: BSD-2-Clause # import platform COPYRIGHT = "2020" def banner(name, ver_str, extra=""): """Create a simple header with version and host information""" print("\n" + "#" * 75) print("Intel (R) ...
listOfStrings = ["Nibbler", "Bender", "Fry", "Leela"] for i in range(0, len(listOfStrings)): print str(i) + " = " + listOfStrings[i] # more magical version print "Part 2" for name in listOfStrings: print name
from refactor.tilde_essentials.evaluation import TestEvaluator from refactor.tilde_essentials.example import Example try: from src.ClauseWrapper import ClauseWrapper, HypothesisWrapper from src.subsumption_checking import check_subsumption except ImportError as err: from refactor.query_testing_back_end.djan...
from haizea.core.leases import Lease from common import * def get_config(): c = load_configfile("base_config_simulator.conf") c.add_section("pricing") return c def test_pricing1(): c = get_config() c.set("scheduling", "policy-pricing", "free") h = load_tracefile(c, "price1.lwf") h.start...
import cv2 import pytesseract pytesseract.pytesseract.tesseract_cmd = 'C:\\Program Files\\Tesseract-OCR\\tesseract.exe' #img = cv2.imread(r'C:\Users\muska\Downloads\111.jpg ') img = cv2.imread("Resources/111.jpg") img = cv2.cvtColor(img,cv2.COLOR_BGR2RGB) #img = cv2.resize(img,(540,320)) img1 = pytesseract.image_to_st...
species( label = '[CH2]C(C[CH]C)CCC(515)', structure = SMILES('[CH2]C(C[CH]C)CCC'), E0 = (157.756,'kJ/mol'), modes = [ HarmonicOscillator(frequencies=([2750,2770,2790,2810,2830,2850,1425,1437.5,1450,1225,1250,1275,1270,1305,1340,700,750,800,300,350,400,3025,407.5,1350,352.5,1380,1390,370,380,290...
# -*- coding: utf-8 -*- import local_config as config import tornado import vk from tornado.httpserver import HTTPServer from tornado.ioloop import PeriodicCallback, IOLoop from tornado.queues import Queue, QueueEmpty from telebot import TeleBot, types import pdb # periodic launch of async tasks to process tasks in ...
from django.db import models from django.urls import reverse from django.utils.translation import gettext_lazy as _ COLOR_CHOICES = ( ('green', 'GREEN'), ('blue', 'BLUE'), ('red', 'RED'), ('orange', 'ORANGE'), ('black', 'BLACK'), ) class MyModel(models.Model): color = models.CharField(max_len...
# https://leetcode.com/problems/minimize-deviation-in-array/description/ """ You are given an array nums of n positive integers. You can perform two types of operations on any element of the array any number of times: If the element is even, divide it by 2. For example, if the array is [1,2,3,4], then you can do this...
# Generated by Django 2.2 on 2019-05-01 06:51 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('konchiwa', '0002_auto_20190501_1545'), ] operations = [ migrations.AlterField( model_name='article', name='journal_ID'...
# 构建发布压缩包 import os import re import shutil import subprocess from log import logger from qq_login import QQLogin from version import now_version def package(dir_src, dir_all_release, release_dir_name, release_7z_name, dir_github_action_artifact): old_cwd = os.getcwd() # 需要复制的文件与目录 files_to_copy = [] ...
from django.contrib import admin from django_markdown.admin import MarkdownModelAdmin from qaforum.models import (QaAnswer, QaAnswerComment, QaQuestion, QaQuestionComment) admin.site.register(QaQuestion) admin.site.register(QaAnswer, MarkdownModelAdmin) admin.site.register(QaAnswerComment) admin...
import shutil import pandas as pd from tkinter import * from tkinter import filedialog, ttk from os import walk def get_data_from_excel(): global ce_que_on_veut_copier global path_data path_data = filedialog.askopenfilename(initialdir="C://Users//p094836//Desktop//", title="choose your Excell file", ...
""" Solution for problem 20 of Project Euler. Find the sum of the digits in the number 100! """ def solve(): """ Serves as the driver for problem 20. """ factorial_value = 1 for i in range(1, 101)[::-1]: factorial_value *= i total = 0 while factorial_value > 1: total += f...
import codecs import copy as cp from collections import Counter import numpy as np import pickle sents2vec, sentences, labels = [], [], [] unique_words = {} idx = 0 words_freqs = {} max_label = 0 max_sentence_length = 0 classes_freqs = {} with codecs.open('train.txt', 'r', encoding='utf-8') as reader: for line in...
# -*- coding: utf-8 -*- # @Time: 2020/3/13 15:24 # @Author: Rollbear # @Filename: converter.py from entity.topic import Topic def scanner(p_lines: list): """ Markdown格式解析器 分析标题、子标题、正文之间的关系,构造一个树形结构 :param p_lines: 以行为元素的列表 :return: 解析产生的Topic对象 """ lines = p_lines.copy() root_topic =...
def validBraces(string): result = [] for i in string: if i in "({[": result.append(i) elif len(result) != 0: if (i == ')') & (result[-1] == '('): result.pop() elif (i == '}') & (result[-1] == '{'): result.pop() elif result[-1] == '[': ...
from pickle import load, dump a = load(open('dickens_texts.pickle')) new_file = open('great_expectations.txt', 'w') print type(a[0]) new_file.write(a[0])
from django.apps import AppConfig class PhotoContentConfig(AppConfig): name = 'photo_content'
import gym from gym import wrappers from gym import spaces import constants as C class OpenAIGym: """ Wrapper class to interact with OpenAIGym Game attributes: env [gym.Environment] - environment of game game_name [string] - name of game being played render [bool] - set to true if game should be vi...
import logging from djangocities.cities.models import City from djangocities.iam.jwt import load_user from djangocities.pages.models import Page from djangocities.sites.models import Site def create_default_page(site): page = Page.objects.create(site=site, file_name="index.html") return page d...