text
stringlengths
38
1.54M
import os CODE_DIR = os.path.dirname(__file__) ROOT_DIR = os.path.dirname(CODE_DIR) DATA_DIR = os.path.join(ROOT_DIR, 'data') COLLECTION_NAME = "startups" QDRANT_HOST = os.environ.get("QDRANT_HOST", "localhost") QDRANT_PORT = os.environ.get("QDRANT_PORT", 6333)
# Licensed to the Apache Software Foundation (ASF) 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...
import os import urllib from mongomock import MongoClient def get_database(): config_path = os.environ.get('LUNNICONFIG') if not config_path: raise "MISS CONFIGURATION" with open(config_path) as f: for line in f: command = line[:-1] command = command.split('=') ...
"""create post table Revision ID: bdcf5521b1c1 Revises: b44300fa6522 Create Date: 2021-01-24 21:47:59.239258 """ from alembic import op import sqlalchemy as sa # revision identifiers, used by Alembic. revision = 'bdcf5521b1c1' down_revision = 'b44300fa6522' branch_labels = None depends_on = None def upgrade(): ...
import socket import threading import logging import datetime import sys FORMAT = "%(asctime)s %(threadName)s %(thread)d %(message)s" logging.basicConfig(format=FORMAT,level=logging.INFO) class ChatServer: def __init__(self,ip='0.0.0.0',port=8000): self.addr = (ip,port) self.sock = s...
def import_args(test,*args): print('param:',test) for item in args: print('other params:',item) args = ['hello',2019] import_args('123',*args)
""" kde ~~~ Implements some general "kernel density estimation" methods which, while not drawn directly from the literature, can be thought of as generalisation of the `prohotpot` and `retrohotspot` methods. """ from . import predictors as _predictors import numpy as _np from . import kernels as _kernels class Cons...
import re import os import argparse import sys import errno import optparse import sqlite3 import uuid import email import email.utils from email.message import EmailMessage from email.parser import BytesParser, Parser from email.policy import default from datetime import datetime import hashlib import notesdb impo...
''' Auto login code to keep a c9 workspace up @author Sercrash @date 18/05/2016 ''' # Imports import sys, time, threading, random, datetime, timeout, os.path from random import randint global ejecuciones ejecuciones = 0 # Class definition class KeepUp: def __init__(self): # Constructor self.version = "v1....
# Generated by Django 2.1.1 on 2018-10-16 17:04 import discourz_app.models from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Account', fields=[ ...
import pandas as pd import numpy as np import seaborn as sns import matplotlib.pyplot as plt from sklearn.model_selection import train_test_split from sklearn.utils import class_weight #Exploring Data ''' df['Age'].mean() #Average age of 44 df['Survived'] #13% survival rate, yoinks! df.describe() a = sns.catplot(x='Se...
import unittest import pandas as pd from Funcoes_Axiliares import Funcoes_Axiliares import sys, os sys.path.insert(-1,os.path.abspath('../../../Pyker')) from cientista.Validar import Regra_descartar_linha_repetida class Regra_descartar_linha_repetida_test(unittest.TestCase,Funcoes_Axiliares): def test_repara(self...
import torch def iou(pr, gt, eps=1e-7, threshold=None, activation='sigmoid'): """ Source: https://github.com/catalyst-team/catalyst/ Args: pr (torch.Tensor): A list of predicted elements gt (torch.Tensor): A list of elements that are to be predicted eps (float): epsilon to...
# encoding: utf-8 ''' Created on 26 Sep 2017 @author: MetalInvest ''' try: from kuanke.user_space_api import * except ImportError as ie: print(str(ie)) from jqdata import * import pandas as pd import numpy as np class HerdHead(object): def __init__(self, params): self.ga...
from django.contrib import admin from .models import * @admin.register(Task) class TaskAdmin(admin.ModelAdmin): exclude = ('created_at','updated_at')
from torch.utils.data import Dataset from common.utils import get_img, get_img_recog class AEDataSet(Dataset): def __init__(self, home_path, path_list, transform=None, crop=True): """DataSet for Autoencoder Args: home_path (str): home dir path path_list (list): image file...
import argparse import os import sys from PyQt5 import QtWidgets from gui.GameWindow import GameWindow def main(): parser = argparse.ArgumentParser( usage='{} rom'.format( os.path.basename( sys.argv[0])), description='CHIP8 emulator. Play a game which is 30 years old!...
import subprocess from tkinter import * from PIL import Image, ImageTk root = Tk() root.iconbitmap("img/master.ico") root.title("Azure VM Control") mainframe = Frame(root) mainframe.grid(column=0, row=0, sticky=(N, W, E, S)) mainframe.columnconfigure(0, weight=1) mainframe.rowconfigure(0, weight=1) mainframe.pack(pa...
import time import os import datetime greeting = os.getenv("GREETINGS", "hello") greeting_jp = os.getenv("GREETINGS_JP", "konnichiwa") time.sleep(20) out = f'{greeting} in Japanese is {greeting_jp}' for i in range(19): print(i, out, flush=True) time.sleep(3)
import itertools from collections import deque import pygame import random import screen_utils import config def lines(screen, lines_lifespan=2000): verbose = config.verbose running = config.running palette, palette_name = screen_utils.get_palette() colors = itertools.cycle(palette) if verbose: ...
import argparse import json import time from datetime import datetime, date from enum import Enum from http import HTTPStatus import requests import sqlalchemy from attr import dataclass from sqlalchemy import Column, INTEGER, DATE, TIMESTAMP, String, UniqueConstraint from .common_tool_methods import remove_suffix, s...
import dash from dash.dependencies import Input, Output, State import dash_core_components as dcc import dash_html_components as html import numpy as np import pandas as pd from app import app, df_to_table, Graph, update_graph, indicator, marks from scipy.stats import norm # calculate the greeks # ['delta', ...
from numpy import * mat = array(eval(input("Matricula dos alunos: "))) x = zeros(2,dtype=int) for elemento in mat: if (elemento % 2 != 0): x[1] = x[1] + 1 # Acumulador dos impares v = zeros(x[1], dtype=int) i=0 for elemento2 in mat: if(elemento2 % 2 != 0): v[i] = elemento2 i = i + 1 print(v)
# Name: Efi Pecani # ID: 307765230 from tkinter import * #import all of this stuff in order to wor kwith tkinter methods import tkinter as tk from tkinter import filedialog from tkinter import ttk, messagebox from PIL import ImageTk from PIL import Image import os, sys import tkinter.font as tkFont from ...
#!/usr/bin/env python import subprocess import optparse import re def get_argument(): parser = optparse.OptionParser() parser.add_option("-i","--interface", dest="interface", help="Interface to change its MAC address") parser.add_option("-m","--mac", dest="new_mac", help="MAC address the user want") (...
from __future__ import division, print_function import opticstools as ot import numpy as np import matplotlib.pyplot as plt from matplotlib.ticker import FormatStrFormatter try: import ipdb except: #The following ling is dodgy, but still enables set_trace() import pdb as ipdb import scipy.ndimage as nd imp...
"""Definition of additional qt helper objects.""" from collections import deque import logging from os import path as op import pyqtgraph as pg from PyQt5 import uic from pyqtgraph.Qt import (QtCore, QtGui, QtWidgets) from .utils import create_button def warning(txt, title="Warning"): """Inform user about missi...
def lol(a): b=0 c=0 a=a-75 b+=1 c+=6 rou=1 while a>=30: rou+=1 b+=1 a-=30 if b<3: c+=6 elif b==3: b=0 c+=7 if rou%2==0: c-=1 return (a,b,c) time=input("輸入遊戲時間").split(":") second=int(time[0])*...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations import django.core.validators class Migration(migrations.Migration): dependencies = [ ('MyANSRSource', '0067_project_customercontact'), ] operations = [ migrations.AlterModelOptions(...
import logging import os import librosa import numpy as np from elephantcallscounter.data_transformations.filters import Filters from elephantcallscounter.data_transformations.noise_reduction import \ NoiseReduction from elephantcallscounter.data_visualizations.plots import Plots from elephantcallscounter.utils.p...
class AllBooksPageLocators: BOOKS='div.page_inner section li.col-xs-6' PAGER='div.page_inner section ul.pager li.current'
#coding=utf-8 import math def move(x,y,step,angle): nx=x+step*math.cos(angle) ny=y+step*math.sin(angle) return nx,ny x1,y1=move(0,0,100,math.pi/6) print(x1,y1) result=move(0,0,200,math.pi/6) print(result)
# import required packages import pandas as pd import numpy as np import os, gc, time, warnings import itertools from scipy import sparse import scipy.stats as ss from scipy.sparse import csr_matrix, hstack, vstack import matplotlib.pyplot as plt, matplotlib.gridspec as gridspec import seaborn as sns from word...
def get_unicode(text: str) -> bytes: """Returns the unicode for input text Parameters ---------- text : str Text to encode Returns ------- bytes Text with characters encoded in raw unicode. """ return text.encode("raw_unicode_escape") def check_positive_integer(va...
# Definition for a binary tree node. class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Solution: """ 110. 平衡二叉树 https://leetcode-cn.com/problems/balanced-binary-tree/ 给定一个二叉树,判断它是否是高度平衡的二叉树。 本题中,一棵高...
print(__doc__) # --------- import sys import os COMMON_DIR = os.path.abspath(__file__ + '/../../common/') sys.path.insert(0, COMMON_DIR) from constants import * sys.path.insert(0, UTILS_DIR) from file_utils import * # --------- # Code source: Gael Varoqueux # Modified for Documentation merge by Jaques Grobler # L...
# -*- coding: utf-8 -*- # Generated by Django 1.11.9 on 2018-01-25 03:26 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('students', '0008_auto_20180121_1649'), ] operations = [ migrations.AlterFie...
""" 要实现的功能: 从中国国家地理网上解析网页源码,循环获取图片的资源,并下载到本地 这是自己写的************** """ # 一.获取图片资源 # 二.保存在本地 # 原版程序出现的问题是:判断的第一步是是否有文件夹而不是有文件 # 可以组合 # r :只读 # r+ : 读写 # w : 新建(会对原有文件进行覆盖) # a : 追加 # b : 二进制文件 """ 同时添加或者减少缩进的快捷方式: tab+shift或者 shift+tab """ import os import requests from bs4 import BeautifulSoup import re # 用正则表达式来解析网页的...
#!/usr/bin/env python3 #! -*- coding:utf8 -*- import sys if sys.version_info.major != 3: print("Python2 not supported, Please use python3 run again.") sys.exit(1) import argparse import setproctitle import os,time import common.daemon as daemon # init log handler project_path = os.path.dirname(os.path.absp...
"""Contains the primary entrypoint and exit handling code for the Twitter Ingress tooling.""" import logging import sys from os import environ import tweepy from ingress import ES_CONNECTION_STRING from ingress.utils import get_singleton_instance, setup_mappings from ingress.listeners import QueueListener LOG = lo...
import re File1 = open('test', 'r') regex = re.compile(r'\b(?:22822)#[^#]+#') string = File1.read() itemdesc = regex.findall(string) for word in itemdesc: print (word)
import os import sys import json import pdb from collections import Counter def read_json(filename): with open(filename) as f: a=json.load(f) return a def count_key(key_type,object): a=[object[0]['type'] for k in object if k.get('type')==key_type] #print(a) retur...
''' Created on Oct 23, 2009 @author: capitalmarkettools ''' import unittest, datetime from src.bo.Date import Date class Test(unittest.TestCase): "Unit test for Date" def setUp(self): self.date = Date(day=14, month=5, year=2009) def testFromPythonDate(self): d = datetime.date(...
# Generated by Django 2.1.5 on 2019-05-29 15:19 from django.db import migrations, models import django.db.models.deletion import django.utils.timezone import model_utils.fields class Migration(migrations.Migration): dependencies = [ ('api', '0074_auto_20190529_1436'), ] operations = [ m...
from django.db import models class User(models.Model): firstname = models.CharField(max_length=255) lastname = models.CharField(max_length=255) email = models.CharField(max_length=255) age = models.IntegerField() created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeF...
#!/usr/bin/env python # -*- coding: utf-8 -*- from agentzero.meta import BaseStrategy as Strategy from agentzero.metrics.consumer import MetricConsumer __all__ = ['Strategy', 'MetricConsumer']
import argparse from scrapy.crawler import CrawlerProcess from scrapy.utils.project import get_project_settings from args.spiders.email_extract import EmailExtractSpider def main(sites): settings = get_project_settings() settings['FEEDS'] = { 'extracted_emails.csv': { 'format': 'csv', ...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ App 类: app 常用的方法:比如 启动应用,关闭应用,重启应用,进入首页 """ from appium import webdriver from test_appium.page.basepage import BasePage from test_appium.page.mainpage import MainPage class App(BasePage): def start(self): """ 启动应用 如果driver已经被实例化,就复用已有的dr...
import pickle import numpy as np import h5py from qml.aglaia.aglaia import ARMP_G from sklearn.base import clone data = h5py.File("/Volumes/Transcend/data_sets/CN_isobutane_model/pruned_cn_isobutane/train_isopentane_cn_dft.hdf5", "r") n_samples = 2 xyz = np.array(data.get("xyz")[:n_samples]) ene = np.array(data.get(...
import pandas as pd import warnings warnings.filterwarnings('ignore') from collections import defaultdict import platform import struct import numpy as np import numpy import random import tensorflow as tf import os import pickle as pickle import matplotlib.pyplot as plt import sys from datetime import datetime import ...
def findAllInitActivity(log): return list(set([l[0] for l in log])) def findOrCreateInitActivity(log): init = findAllInitActivity(log) if len(init) > 1: return 'a_i' else: return init[0] def findAllEndActivity(log): return list(set([l[-1] for l in log])) def findOrCreateEnd...
from snakemake.utils import R # def getContigNames(): # if isinstance(config['resources'][ORGANISM]['contigNames'], Error): # return ["ERROR"] # f = open(config['resources'][ORGANISM]['contigNames'],'r') # result = [] # for line in f: # result.append(line.strip()) # return result # ...
# -*- coding: utf-8 -*- """ Created on Fri Feb 2 15:31:04 2018 @author: Tuong Lam & Simon Nilsson """ import imageio as imio import numpy as np import re import os import sys def fingerprint_parser(index_file_dir, index_file_name): """ Parser for Precise Biometrics fingerprint database with alignment data. ...
# CSE 101 - IP HW2 # K-Map Minimization # Name: DUSHYANT PANCHAL # Roll Number: 2018033 # Section: A # Group: 1 # Date: 12-10-2018 import unittest from HW2_2018033 import * class testpoint(unittest.TestCase): def test_minFunc(self): self.assertEqual(minFunc(3,'(0,1,2,3,4,5,6,7) d -'),"1") self.assertEqual(min...
MISSING_TOKEN = 'Missing access token' INVALID_TOKEN = 'Invalid access token' INVALID_PASSWORD = 'Your password is invalid, please try again' UNAUTHORIZED = 'The user is not authorized to perform this action' LOGGED_IN = 'You already logged in' INVALID_CREDENTIALS = 'Invalid username or password' USERNAME_DUPLICATED =...
#!/usr/bin/env python # Author: Giulia Muzio ''' Script for saving the permuted genes; the permutation is done by following the degree-permutation strategy File in input: - 'data/ppi.pkl': PPI network in form of pandas DataFrame. The keys of the data frame are the names of the ...
from collections import deque from threading import Condition from typing import BinaryIO, Deque, Optional from pytils.mixins import DaemonHandler from ._base import IOReceiver, IOSender __all__ = [ 'QueuedReceiver', 'QueuedSender', ] _DEFAULT_MAX_QUEUE_SIZE = 4096 class QueuedSender(DaemonHandler, IOSende...
from .models import Post, Comment, Category, SubCategory, Tag from django.views.generic import ListView, DetailView, FormView from django.views.generic.edit import ModelFormMixin from django.shortcuts import redirect, get_object_or_404 from .forms import CommentCreateForm, PostSearchForm from django.shortcuts impo...
def helloWorld(string): print(string) if __name__ == '__main__': string = "Hello World" helloWorld(string)
import os import Game.config.internal as internal import Game.program.misc.exceptions as exceptions import Game.program.misc.sdl as sdl class BaseOverlay: def __init__(self, name, location, size, background_color, *args, **kwargs): super(BaseOverlay, self).__init__(*args, **kwargs) # Name of th...
#학교에서 코딩 대회를 주최하는데 댓글 이벤트를 진행하기로 했다. #댓글 작성자중에 랜덤으로 1명은 치킨, 3명은 커피 쿠폰을 받게 된다. # 댓글은 20명이 작성하였고 편의상 아이디는 1~20으로 가정한다 # 댓글 내용과 상관 없이 무작위로 추첨되며 중복은 불가한 프로그램을 작성하시오. # (출력 예) # -- 당첨자 발표 -- # 치킨 당첨자 : 5 # 커피 당첨자 :[2,3,4] # -- 축하합니다 -- from random import * users = range(1,21) users = list(users) #print(type(users)) winner...
from functools import wraps import os, inspect currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))) parentdir = os.path.dirname(currentdir) os.sys.path.insert(0, parentdir) from common import music_graph_client as mgc from common.user_base import UserBase from server import music_grap...
## *************************************** # Authors: Jing Xie, Xin Li # Updated Date: 2019-4-30 # Emails: jing.xie@ucdconnect.ie # *************************************** import re import json import os.path import ntpath class DssParser: def __init__(self, master_file): self.master_file = ntpath.basen...
# Databricks notebook source # MAGIC %run "../helper_functions" # COMMAND ---------- baseTable = spark.table(dbutils.widgets.get("baseTable_table_path")) baseUsersCountPath = dbutils.widgets.get("baseUsersCount_table_path") # baseTable = spark.table('insight.baseTable') # baseUsersCountPath = 'insight.baseUsersCount...
# https://leetcode.com/problems/course-schedule-ii/ # 210. Course Schedule II # There are a total of n courses you have to take, labeled from 0 to n-1. # Some courses may have prerequisites, for example to take course 0 you have to first take course 1, which is expressed as a pair: [0,1] # Given the total number of cou...
import os import smtplib from email.message import EmailMessage # email addresses and passwords are stored as environment variables to be more secure # EMAIL_ADDRESS = os.getenv('WORK_EMAIL') # EMAIL_PASSWORD = os.getenv('WORK_APP_PASS') def send_text_message(to, message, teacher): # 'to' is a variable that is a gat...
#!/usr/bin/env python import rospy from flexbe_core import EventState, Logger class hsr_BooleanDummy(EventState): ''' Example for a state to demonstrate which functionality is available for state implementation. This example lets the behavior wait until the given target_time has passed since the behavior h...
""" Each ListNode holds a reference to its previous node as well as its next node in the List. """ class ListNode: def __init__(self, value, prev=None, next=None): self.prev = prev self.value = value self.next = next """ Our doubly-linked list class. It holds references to the ...
from spanserver import SpanAPI from ._version import __version__ from ._name import SERVICE_NAME # the service api is declared here api = SpanAPI( title=SERVICE_NAME, version=__version__, openapi="3.0.0", docs_route="/docs" )
import os import json import functools from abc import ABC import tornado.httpserver import tornado.ioloop import tornado.options import tornado.web import tornado.gen import pymysql from nsq import Writer, Error from dequeue.redis_dequeue import PriorityQueue, get_redis_from_settings class BaseHandler(tornado.web...
#!../../python3.9/bin/python import sys import argparse import time import numpy as np import matplotlib.pyplot as plt from generadorFiveBitProblem import fivebit from reca import ProblemClassification def visualizer_5bit(automat, i, I, R, C): plt.figure plt.imshow(automat, cmap='Greys', interpolation='near...
# Form implementation generated from reading ui file 'resources/ui/tools_dialog.ui' # # Created by: PyQt6 UI code generator 6.4.2 # # WARNING: Any manual changes made to this file will be lost when pyuic6 is # run again. Do not edit this file unless you know what you are doing. from PyQt6 import QtCore, QtGui, QtWid...
from django.conf.urls import url from django.contrib.auth.views import LogoutView from apps.users import views urlpatterns = [ url(r'^login/$', views.LoginView.as_view(), name='login'), url(r'^logout/$', LogoutView.as_view(), name='logout'), ]
import os import pickle import sys torchfuel_path = os.path.dirname( os.path.dirname(os.path.dirname(os.path.dirname(os.path.realpath(__file__)))) ) sys.path.append(torchfuel_path) from torchfuel.utils.state import Namespace, State def test_ns(): ns = Namespace() ns.test = 10 print(ns.stored_objects...
from keras.layers import GRU, Activation, Input, Reshape, Concatenate, Lambda, Dropout from keras import Model import keras import functools import operator import numpy as np from processing import DataGenerator from data import Data DROPOUT_RATE = 0.3 # NODES_LAYERS_DMS = (100, 100) # EDGES_LAYERS_DMS = (100, 100) ...
"""Geometry calculations. Copyright 2011 University of Auckland. This file is part of PyTOUGH. PyTOUGH is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option)...
# kPicture.py import pyqtgraph as pg from pyqtgraph import QtCore, QtGui # dat = data.NewData() 指标数据 # ddat = dat.ddata['000001.SZ'].iloc[-100:][['open','high','low','close','vol','ma10','ma20','ma30']] # ddat['t'] = range(1, ddat.shape[0] + 1) # wdat = dat.wdata['000001.SZ'].iloc[-100:][['open','high','low','close'...
from urllib.parse import urlencode from django import template register = template.Library() @register.simple_tag(takes_context=True) def page_replace(context, new_page, page_name="page"): query = dict(context['request'].GET) query[page_name] = new_page return urlencode(query, doseq=True)
# -*- coding: utf-8 -*- # @Time : 2020/12/25 下午 02:35 # @Author : Yuanxuan # @FileName: run_start.py.py # @Software: PyCharm import os import time """ 笔记 os.getcwd() 获取当前文件的路径 os.path.dirname() 获取当前文件的文件夹的路径,即上一级的路径 os.path.join() 拼接路径 """ # 项目文件夹的路径 BASE_DIR_PATH = os.path.dirname(os.getcwd()) # 元素控件 ELEMENT_PATH...
import numpy as np import pickle import matplotlib import pyfftw from math import pi as PI from decimal import Decimal from matplotlib import cm, rc from matplotlib.colors import LinearSegmentedColormap from mpl_toolkits.mplot3d import Axes3D #from matplotlib import animation #from JSAnimation import IPython_display m...
import os import argparse parser = argparse.ArgumentParser() parser.add_argument('-hours', type=int, help='number of gpu hours to request for job', default=24) parser.add_argument('-allocation', type=str, help='Allocation name for billing', default='deepmpc') parser.add_argument('-part', type=str, help='datasubs...
#문자열자료형 print('풍선') print('나비') print('ㅋㅋㅋㅋㅋㅋㅋ') print('ㅋ' * 7) #boolean #참/거짓 print(5 > 10) print(5 < 10) print(True + 1) print(not True) print(not False) print(not (5 > 10))
from collections import defaultdict import heapq def ceil(x, y): return (x + y - 1) // y n, m, s = map(int, input().split()) E = defaultdict(dict) for i in range(m): u, v, a, b = map(int, input().split()) E[u - 1][v - 1] = (b, a) E[v - 1][u - 1] = (b, a) penalty = [list(map(int, input().split())) fo...
import numpy as np import cv2 img = cv2.imread('WeChat Image_20200221164050.jpg', 0) cv2.namedWindow('image', cv2.WINDOW_NORMAL) cv2.imshow('image', img) cv2.waitKey(0) ret, mask = cv2.threshold(img, 190, 255, cv2.THRESH_BINARY) cv2.namedWindow('mask of characters', cv2.WINDOW_NORMAL) cv2.imshow('mask of characters', ...
import re import numpy as np import joblib memory = joblib.Memory('joblib') # no apostrophe to remove e.g. "president's" office, no bracket to remove e.g. (V.O.) character_pattern = r"\b[A-Z]{2}[A-Z\.]+(?: [A-Z\.]{3,})*\b" character_pattern = r"(?:^|(?:[a-z]+[.!?]\s+))([A-Z-]{2,}[\.\(\)\':;-]*(?:\s+[A-Z-]{2,}[\.\(\)\...
import os import concurrent.futures import pandas as pd from collections import Counter from time import time from sys import platform from tqdm import tqdm def main(): csv_store_path = os.environ['GP_HIST_PATH'] results = [] ts = time() idf = pd.read_pickle("./ignore/rev100k.pkl").sort_values(by=...
import urllib.request import json import csv import re import datetime from time import sleep import requests import time class CollectCommitUser(): def Request(self,url): id = 'rlrlaa123' pw = 'ehehdd009' # auth = base64.encodestring(id + ':' + pw) auth = id+':'+pw return r...
import os import flask from flask import Flask, request import telebot import json import urllib.request import datetime import pytz import requests def json_getweather() : url = "https://api.weatherlink.com/v1/NoaaExt.json?user=001D0A0124D3&pass=zaharberkut2019&apiToken=ED47A9235AF1472A8B5BC594D830B39D" dat...
import pysat import datetime as dt import matplotlib.pyplot as plt print('making inst') ivm = pysat.Instrument(platform='cnofs', name='ivm') start = dt.datetime(2014,3,1) stop = dt.datetime(2014,3,2) date_array = pysat.utils.time.create_date_range(start, stop) output_resolution = (320, 240) my_dpi = 192 figsize = tu...
from Logic.TextFunctions import * from Logic.GetInput import * class cd: """Context manager for changing the current working directory""" def __init__(self, new_path): self.newPath = os.path.expanduser(new_path) def __enter__(self): self.savedPath = os.getcwd() os.chdir(self.newPa...
# Author : ThammeGowda Narayanaswamy # Email : tnarayan@usc.edu # Student ID : 2074669439 # Subject : Naive Bayes Classifier (continuous features) implementation # for CSCI 567 Fall 16 Homework 1 # Date : September 17, 2016 from __future__ import print_function import sys import os impor...
from prefect import task, Flow @task def hello_world(): print("Hello World!") return "Hello Prefect!" @task def prefect_say(s: str): print(s) with Flow("my_first_flow") as f: r = hello_world() s2 = prefect_say(r) f.visualize() f.run()
n=int(input()) arr=[int(x) for x in input().split()] print("Before sorting") print(arr) for i in range(0,n-1): min=i for j in range(i+1,n): if(arr[min]>=arr[j]): min=j temp=arr[min] arr[min]=arr[i] arr[i]=temp print("After sorting") print(arr)
x = 3.1 y = x//1 if (x-y ==0): print("Es entero") else: print("es flotante")
''' 将所有输入字符大写输出 可以回车输入 ''' lines = [] while True: oring_string = input() if oring_string: lines.append(oring_string.upper()) else : break print(' '.join(lines)) ''' 学习点:这里最主要的是回车输入, 如果简单的用upper, 不写循环,那么会出现回车输入直接输出内容,这里用一个while 循环和if循环,如果输入为空,直接停止循环。 学习一下while True 的作用吧 ...
# 检测字符串是否只由数字组成。 # str.isdigit() # 返回值:字符串只包含数字则返回 True 否则返回 False。 str = "12345" print(str.isdigit()) # True str2 = "12345s" print(str2.isdigit()) # False str3 = "123 456 79" print(str3.isdigit()) # False
m = int(input("Enter rows: ")) n = int(input("Enter columns: ")) print("Enter array 1: ") arr1 = [list(map(int, input().split())) for i in range(m)] print("Enter array 2: ") arr2 = [list(map(int, input().split())) for i in range(m)] for i in range(m): for j in range(n): print(arr1[i][j]+arr2[i][j]...
from product.form import Productform from django.shortcuts import render,redirect from django.http import HttpResponse,JsonResponse from rest_framework import serializers from rest_framework.parsers import JSONParser from .models import Product from .serializer import ProductSerializer from django.views.decorators.cs...
# -*- coding: utf-8 -*- { 'name': "VietERP Mailbox", 'summary': """ Simple Odoo mailbox""", 'description': """ 1. Main features: - Sending email from odoo - Receiving email from odoo - Composing email from odoo - Choosing template when composing email 2. Why choose this? - Qui...
import requests import os import ast import random # --------------- Helpers that build all of the responses ---------------------- def build_speechlet_response(title, output, reprompt_text, should_end_session): return { 'outputSpeech': { 'type': 'PlainText', 'text': output ...