text
stringlengths
38
1.54M
import numpy as np import pandas as pd import math import requests import xlsxwriter from scipy import stats from scipy.stats import percentileofscore as score #IMPORT OUR LIST OF STOCKS stocks = pd.read_csv("C:\\V'S LIFE\\4_Project\\Algro-Trading\\actual_output\\Project 1\\sp_500_stocks.csv",'r') #ACQUIRING...
from django.views.generic import View from django.views.decorators.cache import never_cache from django.utils.decorators import method_decorator from django.contrib.auth.decorators import login_required from gbe.models import Profile from django.shortcuts import ( get_object_or_404, render, ) from gbe.functions...
import os import click from mgshell.version import __version__ @click.group() def cli(): pass @cli.command() def version(): click.echo("mgshell %s" % __version__)
message = "Hello world! This is python!" print(message) message = "I'm taking a crash course." print(message) message = "Now let's get crazy!" print(message)
from .base.worker import Worker class Counter(Worker): def __init__(self): """ A worker that counts and manually checks for messages. """ super().__init__() self.count = 0 self.timeout = 2 # We should respond to messages in < 2 seconds. def on_start(self): ...
#!/usr/bin/env python # # 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 "Li...
# -*- coding: utf-8 -*- from panda3d.core import TextNode, TransparencyAttrib from direct.gui.OnscreenText import OnscreenText from direct.gui.OnscreenImage import OnscreenImage from base import Manager class HUDManager(Manager): def __init__(self): self._hud = [] self._info = None self._...
# coding=utf-8 # list: 属于序列类型 def test1(): # list创建 s = [1, 2, "hi", (2, 3)] # 或者 s = list([1, 2, "hi", (2, 3)]) t = [[i + j for j in range(3)] for i in range(2)] # 序列类型通用操作符 print("hi" in s) # True print("hi" not in s) # False print(s + t) # [1, 2, 'hi', (2, 3), [0, 1, 2], [0, 1, 2]] ...
from keras.models import Sequential from scipy.misc import imread import matplotlib.pyplot as plt import numpy as np import keras from keras.layers import Dense import pandas as pd from keras import backend as K from keras.applications.resnet50 import ResNet50 from keras.preprocessing import image from keras.applicatio...
import sys import glob import math import re from ROOT import * from array import * gROOT.SetBatch(True) gStyle.SetOptStat(0) gStyle.SetPalette(1) gROOT.LoadMacro("../style/AtlasStyle.C") gROOT.LoadMacro("../style/AtlasUtils.C") SetAtlasStyle() y_axis_label = "S/#sqrt(B)" ############################# btagStrategy = "F...
from rest_framework import serializers from .models import Schedule, ScheduleHour from doctor.serializers import DoctorSerializer class ScheduleHourSerializer(serializers.ModelSerializer): class Meta: model = ScheduleHour fields = ( 'hour', ) class ScheduleSerializer(serial...
from collections import defaultdict import traceback import zmq import time import signal import threading import matplotlib.pyplot as plt import matplotlib.animation as animation from management.portfolio import Portfolio from management.order_book import OrderBooks from agents.trader import Trader from utils.state ...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.core.urlresolvers import reverse from django.db import models # Create your models here. class Album(models.Model): artist=models.CharField(max_length=250) album_title=models.CharField(max_length=250) genre=models.CharField(...
from atila import Atila import confutil import skitai import asyncore import os from rs4 import jwt as jwt_ import time def test_cli (app, dbpath): @app.route ("/hello") @app.route ("/") def index (was): return "Hello, World" @app.route ("/petse/<int:id>") def pets_error (was): ...
import random def gamewin(a,b): if b==a: print("yor are tied") print("play again") elif b=="s": if a=="g": print("you win") else: print("comp has win") elif b=="g": if a=="s": print("comp has win") else: print(...
# Copyright 2013-2023 Aerospike, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writ...
import logging # pylint: disable=C0302 from unittest.mock import patch from sqlalchemy import desc from web3.datastructures import AttributeDict from src.models.indexing.cid_data import CIDData from src.tasks.backfill_cid_data import backfill_cid_data from src.utils import redis_connection from src.utils.db_session ...
#!/usr/bin/env python # -*- coding: utf-8 -*- # File : is_a_cat.py # Author: PengLei # Date : 2018/10/18 # 利用神经网络判断一张图片是否是一只猫 import numpy as np import matplotlib.pyplot as plt import h5py from lr_utils import load_dataset train_set_x_orig , train_set_y , test_set_x_orig , test_set_y , classes = load_dataset() ind...
#!/usr/bin/python # -*- coding:utf-8 -*- import urllib.parse import urllib.request import lxml from bs4 import BeautifulSoup import re import ssl import time import os """ 1. add comments 2. add daily """ class main_arxiv(object): def __init__(self, query_word: str, domain='cs.CV/', query_mode='all', ...
#lex_auth_0127382206342184961397 def check_anagram(data1, data2): data1 = data1.lower() data2 = data2.lower() if set(data1) != set(data2) or len(data1) != len(data2): return False for i in range(len(data1)): if data1[i] == data2[i]: return False return True #start wr...
""" import matplotlib matplotlib.use(‘TkAgg’) import matplotlib.pyplot as plt import numpy as np x = np.linspace(0, 20, 100) # Create a list of evenly-spaced numbers over the range plt.plot(x, np.sin(x)) # Plot the sine of each x point plt.show() """ import dash import dash_core_components as dcc import das...
from tkinter import * from tkinter import messagebox class Gui(Tk): # Initialise the Gui object # Self = the function belongs to this name # Pass = placeholder. Does nothing def __init__(self): super().__init__() #Load Resources self.tick_image = PhotoImage(file="tick.gif") ...
import usb import array import copy import time import zlib import enum import goodweSample import iGoodwe class State( enum.Enum): OFFLINE = 1 CONNECTED = 2 DISCOVER = 3 ALLOC = 4 ALLOC_CONF = 5 ALLOC_ASK = 6 RUNNING = 7 class CC: reg = 0x00 read = 0x01 class FC: # Register function...
#!/usr/bin/env python import cv2 from cv2 import aruco import math import tempfile import numpy as np import logging import olympe from olympe.messages.ardrone3.Piloting import TakeOff, Landing, PCMD, moveBy, CancelMoveBy from olympe.messages.ardrone3.PilotingState import FlyingStateChanged from olympe.messages.ardro...
from compressor.templatetags.compress import CompressorNode from django.template.base import Template def seizaki_compress(context, data, name): """ Data is the string from the template (the list of js files in this case) Name is either 'js' or 'css' (the sekizai namespace) We basically just manually ...
# ----------------------------------------------------------------------------- # Copyright (c) 2014--, The Qiita Development Team. # # Distributed under the terms of the BSD 3-clause License. # # The full license is in the file LICENSE, distributed with this software. # ------------------------------------------------...
from tkinter import * class Menubar(): def __init__(self,window:Tk): super().__init__() self.menubar = Menu(window) self.menu:list = [] window.config(menu=self.menubar) def __getitem__(self, index) -> Menu: return self.menu[index] def get_menu(self,in...
#!/usr/bin/python #func_default.py #2.7.6 def say(message, times = 1): print message * times pass say('Hello') say('World', 5)
# -*- coding: utf-8 -*- """ Created on Sat Mar 24 20:59:40 2018 诊断PM板命令脚本 @author: Administrator """ import pandas as pd # ============================================================================= # 设置环境变量 # ============================================================================= data_path = r'D:\4G_voltage' ...
import os import torch import argparse #from utils.train import * from Decoder.DecoderRNN import * from Encoder.encoderRNN import * from Transformer import * from Decoder.AttnDecoderRNN import * device = torch.device("cuda") print(device) parser = argparse.ArgumentParser(description='Transformer Generate') parser.ad...
from AWSIoTPythonSDK.MQTTLib import AWSIoTMQTTShadowClient, AWSIoTMQTTClient from OxhrmMonitor import OxiHRMonitor import numpy as np import time clientid = 'basicPubSub2' #HOST = 'arpzdkw2j3op9-ats.iot.ap-northeast-2.amazonaws.com' HOST = 'iotcore.iot.ap-northeast-2.amazonaws.com' CA = 'root-CA.crt' PRI_KEY = 'privat...
# views.py # # Authors: # - Coumes Quentin <coumes.quentin@gmail.com> import json import logging import os import threading import time from io import SEEK_END import docker from django.conf import settings from django.http import (HttpResponse, HttpResponseBadRequest, HttpResponseNotAllowed, ...
import numpy import theano import theano.tensor as T class Layer(object): def components(self): return [] def ancestors(self): return [x for x in y.ancestors() for y in self.output] # TODO def negative_log_loss(self, predictor): return - T.log(self.output[predictor.label]) def get_component_v...
# -*- coding: utf-8 -*- # # ドラクエ10の冒険者の広場画像の一括ダウンロード # import getpass import os import re import sys import cookielib import mechanize from bs4 import BeautifulSoup as bs def do_login(b, us, pw, ci): # ログイン画面 r = b.open('http://hiroba.dqx.jp/sc/login') print(b.geturl()) b.select_form(name='mainForm') ...
hello = 'Hello' print(isinstance(hello, str)) print(isinstance(hello, object)) print(issubclass(str, object)) data = (20, 'fkit') print(isinstance(data, (list, tuple))) print(issubclass(str, (list, tuple))) print(issubclass(str, (list, tuple, object)))
import numpy as np import zmq from zmq_utils import send_array_fast, recv_array_fast import time import argparse parser = argparse.ArgumentParser("Overhead test CLI") parser.add_argument("--height", type=int, default=2000) parser.add_argument("--width", type=int, default=1000) parser.add_argument("--channels", type=in...
import os import sys import time import subprocess retries = range(0,15) scale_factor = [10, 20, 25, 30, 40, 50] print sys.argv if len(sys.argv) >= 1: n = sys.argv[1] else: n = 1 if len(sys.argv) >= 2: flambda = sys.argv[2] else: flambda = "SLEEP5" dirname = "build/" + flambda + "_retry_expt_" + str(t...
#!/usr/bin/env python """ jmyers may 11 2010 march 29 2012: Get rid of MITI format and write things in fullerDiaSource format. Split up the "fullerDiaSource"-format DIAsources by night and put them in separate files. apr. 3 2012: Also, write out a per-obsHist file which holds all dias from a given image. """ #...
#!/usr/bin/env python # -*- coding: utf-8 -*- __date__ = '2018/4/3 18:53' __author__ = 'ooo' import torch import torch.utils.model_zoo as model_zoo from torchvision.models.resnet import BasicBlock, Bottleneck, model_urls from torch import nn import math import visdom import os class ResNet(nn.Module): """ 修改...
count=0 while (count <9): print count count =count +1 print "good bye" for a in range (0,11,12): print a desserts=["ice cream","chocolate","asana"] special_dessert="chocolate" for special_dessert in deserts: if desserts == special_dessert: print dessert + "is my favorite dessert": else: print desse...
from fastapi import APIRouter, Depends from fastapi.security import HTTPBasic, HTTPBasicCredentials from app.core.routers.auth import get_current_username from starlette.responses import HTMLResponse, JSONResponse router = APIRouter() security = HTTPBasic() @router.get("/get", description="Hello World!", response_de...
import argparse from naoqi import ALProxy def main(robot_ip, port=9559): motion_proxy = ALProxy("ALMotion" , robot_ip, port) motion_proxy.wakeup() motion_proxy.openHand('LHand') if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("--ip", type=str, default="127.0.0.1", ...
class Equipment(): name = '' speed = 0 blocking = 0 agility = 0 scoring = 0 # takes basically any argument passed in when creating an instance and sets attribute # ex. Monster(adjective='awesome') makes a 'self.adjective = awesome' def __init__(self, **kwargs): for key, value in...
''' Finding the Largest or Smallest N Items Problem: You want to make a list of the largest or smallest N items in a collection. ''' import heapq # Example 1 nums = [1, 8, 56, 45, 32, 5, 70, 23, 12, 6, 4, 34, 16, 35, 76, 50] print(heapq.nlargest(3, nums)) # [76, 70, 56] print(heapq.nsmallest(3, nums)) # [1, 4, 5] ...
from planner_project import app from flask import request from planner_project.data_access import mysql from planner_project.common import api_response, request_back_helper, custom_error from planner_project.sql.backweb import config_sql # 获取基础配置列表 @app.route("/backweb/config/select_base_config_list", methods=['POST'...
from django.contrib import admin from home.models import Contact from home.models import smoothie from home.models import receipe from home.models import frontimage # Register your models here. admin.site.register(Contact) admin.site.register(smoothie) admin.site.register(receipe) admin.site.register(frontimage)
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def getMinimumDifference(self, root): """ :type root: TreeNode :rtype: int """ ...
import cv2 import numpy as np import matplotlib.pyplot as plt img = cv2.imread("imori_dark.jpg") plt.hist(img.ravel(), bins=255, rwidth=0.8, range=(0, 255)) plt.savefig("my_answer_20.png") plt.show()
#coding:utf-8 from timeit import Timer # li1 = [1,2] # li2 = [23,5] # li = li1 + li2 #列表迭代 # li = [i for i in range(10000)] #列表生成器 # li = list(range(10000)) #直接转换成列表 def t1(): li = [] #往空列表追加值 for i in range(10000): li.append(i) #append只能追加一个值 def t2(): li = [] for i...
# https://colab.research.google.com/notebooks/magenta/onsets_frames_transcription/onsets_frames_transcription.ipynb import tensorflow as tf import librosa import numpy as np from magenta.common import tf_utils from magenta.music import audio_io import magenta.music as mm from magenta.models.onsets_frames_transcription...
from flask import render_template, request from app import app from resources.functions import * @app.route('/') def index(): content = index_content() return render_template('user/index.html', **content) @app.route('/home') def home(): content = home_content() return render_template('user/index.html', **content...
import unittest from node import Node class TestNodeClass(unittest.TestCase): def testConstructor(self): testNode = Node(1) self.assertEqual(testNode.getHead(), 1) self.assertEqual(testNode.getTail(), None) def testConcatenation(self): testNode = Node(1) testNode.s...
from os import listdir from os.path import join, exists from PIL import Image import numpy as np import torch import torch.utils.data as data from torch.utils.data import DataLoader import torchvision.transforms as transforms from skimage import io, feature, color, img_as_uint, util from skimage.transform im...
# this is a project solely made for education purposes it creates a list of all possible combination inside a text in the same folder where the code is running ... you can use this for brute force attacking from itertools import permutations import os cases = str(input("Give all the letters or numbers separated by s...
import json import logging from flask import Flask, request, Response from flask_cors import CORS import pricewars_merchant from models import SoldOffer def json_response(message): return Response(json.dumps(message), status=200, mimetype='application/json') class MerchantServer: def __init__(self, merch...
""" CLASE LISTA--------------------------------------------------------------- """ # Ya que python trata una lista como un objeto, y todos sus elementos internos tambien # Python ofrece metodos para realizar operaciones con listas # LENGTH-------------------------------------------------------------------------- # Fun...
import os import sys import re PROJECT_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))) DefaultRulePath = os.path.join(PROJECT_DIR, *['docs', 'suricata_home', 'emerging.rules', 'rules']) AutoTakeRulePath = os.path.join(PROJECT_DIR, *list("docs/suricata_home/suricata-...
import os import glob import tensorflow as tf # train (first 2975), validation (last 500) image_paths = (sorted(glob.glob(os.path.join(os.getcwd(), 'leftImg8bit', 'train', '*', '*.png'))) + sorted(glob.glob(os.path.join(os.getcwd(), 'leftImg8bit', 'val', '*', '*.png')))) for i, path in enumerate(imag...
from django.db import models # Create your models here. class table(models.Model): name = models.CharField(max_length=50) number = models.CharField(max_length=15) items = models.CharField(max_length=100) price = models.DecimalField(decimal_places=2, max_digits=6) def __str__(self): return ...
#coding=utf-8 """ #第一题 name1 = str(raw_input ("Please enter fist name: ")) name2 = str(raw_input ("Please enter second name: ")) name3 = str(raw_input ("Please enter third name: ")) name4 = str(raw_input ("Please enter fourth name: ")) name5 = str(raw_inpu...
import traceback from PyQt5 import QtWidgets from add_auto_cust import Ui_Dialog from db_tools import autowork_db from datetime import time, timedelta, datetime from count_parts_dialog import Count_Parts from count_orders_dialog import Count_Orders from extended_qtablewidgetitem import Ext_TableItem class AddAutoCust(...
# Generated by Django 2.2.7 on 2020-10-24 17:42 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Question', fields=[ ...
def isBacktoHome(comands): x, y = 0, 0 for comand in comands: if comand == 'U': x += 1 elif comand == 'D': x -= 1 elif comand == 'L': y += 1 elif comand == 'R': y -= 1 return x == y == 0 if isBacktoHome(input()): print("True") else: print("False")
def solution(keymap, targets): keydict = {} for keys in keymap: for i, key in enumerate(keys, 1): if key not in keydict: keydict[key] = i elif keydict[key] > i: keydict[key] = i result = [] for target in targets: _sum = 0...
from flask_sqlalchemy import SQLAlchemy from .user import UserRepository db = SQLAlchemy() __all__ = ["UserRepository"]
import scrapy import re from googletrans import Translator from crawler.items import NewItem translator = Translator(service_urls=[ 'translate.google.com', 'translate.google.co.kr', ]) class ExampleSpider(scrapy.Spider): name = "newStartup" allowed_domains = ["startupranking.com"] start_ur...
import numpy as np import pandas as pd f = pd.DataFrame(np.array([[1, 2], [3, 4], [5, 6]]), columns=["x", "y"], index=["a", "b", "c"]) print(f)
# -*- coding: utf-8 -*- """ Created on Mon Nov 12 17:36:46 2018 @author: Henri_2 This script trains a recursive neural network with midi data """ from __future__ import print_function import pickle from make_sequence import make_sequence from get_notes import get_notes from create_network import create_network from...
""" 剑指 Offer 25. 合并两个排序的链表 输入两个递增排序的链表,合并这两个链表并使新链表中的节点仍然是递增排序的。 示例1: 输入:1->2->4, 1->3->4 输出:1->1->2->3->4->4 限制: 0 <= 链表长度 <= 1000 注意:本题与主站 21 题相同:https://leetcode-cn.com/problems/merge-two-sorted-lists/ date : 12-16-2020 """ # Definition for singly-linked list. from typing import Optional class ListNode: ...
# step_02_dbpedia_website_links.py """ This script interprets the URLs municipalities websites from DBPedia. At a later stage these URLs are used to find out the respective transparency portals. Usage: python step_02_dbpedia_website_links.py Este script interpreta as URLs dos sites dos municípios a pa...
# -*- coding: utf-8 -*- """ @author: Chenglong Chen <c.chenglong@gmail.com> @brief: basic features """ import re from collections import Counter import numpy as np import pandas as pd from sklearn.preprocessing import LabelBinarizer from Code.Chenglong import config from Code.Chenglong.utils import ngram_utils, nlp...
''' Created on Feb 27, 2015 @author: Matthias ''' import os import numpy as np import matplotlib.pyplot as plt def f(x,y): return x * y def g(x): return x * x if __name__ == '__main__': print os.listdir(os.getcwd()) abc = [] C = np.matrix([[1, 2], [3, 4]]) print C B = C.reshape([2,2]) ...
## Flask authentication for bokeh from functools import wraps from flask import request, Response, redirect, Flask,render_template from bokeh.util import session_id app = Flask(__name__) def check_auth(username, password): return username == 'xxxxx' and password == 'xxxxx' def authenticate(): """Sends a 401...
import random """ The SimRandom class is a wrapper around random, providing only the randint(bound) method -- returns a random number between 0 and bound-1. The reason for this class is that SimRandom is deterministic, it gives the same numbers in any simulation run. So, for testing, the "random" choice of ...
import struct DHCP_MESSAGE_PARSE_STRING = '!ccccIHHIIII6s10s192s4s' DHCP_MAGIC_BYTES = b'\x63\x82\x53\x63' DHCP_TAG_PAD = 0x00 # 0 DHCP_TAG_END = 0xff # 255 DHCP_TAG_SUBNET_MASK = 0x01 # 1 DHCP_TAG_ROUTER_ADDRESSES = 0x03 # 3 DHCP_TAG_DOMAIN_NAME_SERVERS = 0x06 # 6 DHCP_TAG_HOST_NAME = 0x0C # 12 DHCP_TAG_DOMA...
""" 作业提交格式 + 使用源代码的方式提交,题目用 `注释` 的方式写在源代码里面。 + 作业文件命名:第几次作业-编号-作业编号-姓名.py(例如01-00-01-正心.py) 自己的编号到这个文档中查找:【腾讯文档】作业提交表https://docs.qq.com/sheet/DU01wRUNRb1B5S1l6?c=H46A0BI0 + 作业提交格式为 第几次作业-编号-姓名.zip(发送两个作业的压缩包) 例如正心的第一次作业提交文件为 01-00-正心.zip + 提交到QQ邮箱:2328074219@qq.com + 作业在第二天上课前讲解...
from rest_framework import serializers from api.models.surveys import Survey class SurveySerializer(serializers.ModelSerializer): class Meta: model = Survey fields = ( 'id', 'creator', 'site_name', 'coordinates_lat', 'coordinates_long', ...
#!/usr/bin/env python3 #SBATCH -o eval-gk-svr-%j.out #SBATCH -e eval-gk-svr-%j.err #SBATCH -t 12:00:00 import argparse # Imports for training SVRs from sklearn.model_selection import train_test_split, KFold, GridSearchCV from sklearn import svm from sklearn.metrics import accuracy_score, mean_squared_error import p...
while 1: b = 1 bolensayisi = int() print("Programdan çıkmak için q 'ya basınız.") y = (input("Lütfen bir sayı giriniz:")) if y == 'q': print("Programdan çıkılıyor....") break else: x: int = int(y) while 1: if b <= x: if ...
#!python """ It is well known that if the square root of a natural number is not an integer, then it is irrational. The decimal expansion of such square roots is infinite without any repeating pattern at all. The square root of two is 1.41421356237309504880..., and the digital sum of the first one hundred decimal digi...
#TODO: define function guess_the_number #TODO: use random.randint to get a number between 1 and 20 #TODO: ask user to input their guess #TODO: loop to keep giving the player three guesses until they've guessed correctly #TODO: give the player cues if the guess is not correct #TODO: let the player k...
# -*- coding: utf-8 -*- import os, json from urllib.parse import quote import scrapy from scrapy.spiders import CrawlSpider, Rule from scrapy.linkextractors import LinkExtractor from ejob.items import JobItem from ejob.item_loaders import LagouJobItemLoader class LagouJobSpiderSpider(scrapy.spiders.CrawlSpider): nam...
''' test_list = ['one','two','three'] #for i in test_list: for i in range(0,len(test_list)): -> range는 숫자를 가지고 있는 아이로 인덱싱이 필요 print(test_list[i]) ''' ''' a = (1,2,3,4,5,6,7,8,9,10) for i in a: if(i %2 !=0): print(i) else: continue ''' ''' a='안녕하세요. 저는 누구입니다.' b = a.split(' ')...
# -*- coding: utf-8 -*- import shutil import cv2 as cv import os import numpy as np import random ''' opencv数据增强 对图片进行色彩增强、高斯噪声、水平镜像、放大、旋转、剪切 并对每张图片保存每一种数据增强的图片 ''' def contrast_brightness_image(src1, a, g, path_out): ''' 色彩增强(通过调节对比度和亮度) ''' h, w, ch = src1.shap...
file_to_read = open('data_in_genres.txt', 'r') file_to_write = open('data_out_test.sql', 'w') data = file_to_read.read() print("Result before - file_to_read_albums.read():") print(type(data)) print(data) data_lines = data.split('\n')[:-1] print("Result after - data.split(\'\n\')[:-1]:") print(type(data_lines)) print(d...
"""A module for Jython emulating (a small part of) CPython's multiprocessing. With this, pygrametl can be made to use multiprocessing, but actually use threads when used from Jython (where there is no GIL). """ # Copyright (c) 2011-2020, Aalborg University (pygrametl@cs.aau.dk) # All rights reserved. # Redistri...
#! /usr/bin/env python import sys import os import loginFile import gui root="" top="" def init(root, top): root=root top=top print("Start the engines on something I suppose") def login(username,password): with open(loginFile.homeDir/('credentials.txt'))as file: lines=file.readlines() f...
from pathlib import Path from flask import Flask from flask import request from nerds.web.input import InputDocumentFile from nerds.web.load import ModelLoader from nerds.web.response import Response app = Flask(__name__) response = Response() # load pre-trained models here # it's a temporal solution that will be r...
# Copyright (c) 2023. Lena "Teekeks" During <info@teawork.de> """ EventSub Webhook ---------------- .. warning:: Rework in progress, docs not accurate EventSub lets you listen for events that happen on Twitch. The EventSub client runs in its own thread, calling the given callback function whenever an event happens....
# coding:utf8 from pyspark.sql import SparkSession from pyspark.sql.types import StructType, StringType, IntegerType if __name__ == '__main__': # 0. 构建执行环境入口对象SparkSession spark = SparkSession.builder.\ appName("test").\ master("local[*]").\ getOrCreate() sc = spark.sparkContext ...
from fastapi import APIRouter from app.api.api_v1.endpoints import quotes, login, users, utils, tags api_router = APIRouter() api_router.include_router(login.router, tags=["login"]) api_router.include_router(users.router, prefix="/users", tags=["users"]) api_router.include_router(utils.router, prefix="/utils", tags=[...
from __future__ import absolute_import, division, print_function, unicode_literals # isort:skip # noqa import unittest from textwrap import dedent from typing import ( DefaultDict, Dict, List, Mapping, Optional, Set, Tuple, Union, ) import six from ..base import generate_interfaces ...
import psycopg2 import os from dotenv import load_dotenv import json from psycopg2.extras import execute_values load_dotenv() DB_NAME=os.getenv("DB_NAME") DB_USER=os.getenv("DB_USER") DB_PASSWORD=os.getenv("DB_PASSWORD") DB_HOST=os.getenv("DB_HOST") connection = psycopg2.connect(dbname=DB_NAME, user=DB_USER, ...
from app import manager, db from models import Role from main import * # noqa: F401, F403 @manager.command def insert(): db.session.add_all(Role.app_roles()) db.session.commit() if __name__ == '__main__': manager.run()
## 0. Copia un texto largo como variable string texto. ## 1. Normaliza texto: elimina caracteres estraños y todas minusculas ## 2. Estadisticas de palabas (contar palabras) ## 3. Estadisticas de transicion de palabras (2-gram model) [Use sklearn CountVectorizer] ## 4. Using NLTK do a Part of Speech tagging (POS t...
''' 11. Canvas adalah widget tkinter yang berfungsi sebagai media output. ''' from tkinter import * #1. Membuat GUI root = Tk() #2. Costumize GUI #I. canvas widget canvas_widget = Canvas(root, bg="blue", width=100, height= 50) canvas_widget.pack() #3. Menampilkan GUI root.mainloop()
from appJar import gui from Controller.DeviceManager import * import os, sys from threading import Timer import time import copy from Controller.LogManager import * import os import platform import subprocess from Controller.TestManager import * class MainWindow: timer = None app = gui("COS USB KEY") lo...
with open('input.txt') as f: paths = [ line.strip().split(',') for line in f ] v = {'L': (-1, 0), 'R': (1, 0), 'U': (0, 1), 'D': (0, -1)} def add(p0, p1): return (p0[0]+p1[0], p0[1]+p1[1]) def sample_path(path): p = (0, 0) locations = set() dists = {} length = 0 while len(path): c...
import unittest import sys, os sys.path.append(os.path.join(os.path.dirname(__file__), '../..')) from app.models import User class UserModelTestCase(unittest.TestCase): def test_something(self): self.assertTrue('something' is not None) if __name__ == '__main__': unittest.main()
# !/usr/bin/env python # coding=utf8 __version__ = 'v1.0' # 先写个网易的测试一下 import time import requests from news_Setting import HEADER_NET class Crawl(): def __init__(self): self.session = requests.Session() headers = HEADER_NET self.session.headers.update(headers) # 获取页面,private, 内部访问,...