text
stringlengths
38
1.54M
#!/usr/local/bin/python3 from cgitb import enable enable() def get_comments(): #Function to take in user comments, add them to a database & display them from cgi import FieldStorage, escape import pymysql as db from os import environ comments = '' url = environ.get('SCRIPT_NAME') try: ...
from django import forms from .models import Inventory, Offers class StockSearchForm(forms.ModelForm): class Meta: model = Inventory fields = ['category', 'item_name', 'item_code']
#!/usr/bin/env python # -*- coding: utf-8 -*- # pylint:disable-msg= """ Define a base handler to initialize all requests All handlers inherit from the BaseHandler .. moduleauthor:: <> """ import sys import re import zlib import traceback import logging import httplib import urllib import threading import json imp...
from . import models from rest_framework import serializers class ChatSerializer(serializers.ModelSerializer): class Meta: model = models.Chat fields = ( 'service_provider', 'customer', 'sender', 'text', )
#!/usr/bin/env python # -*- coding: utf-8 -*- import logging from bs4 import BeautifulSoup try: import urllib.request as urllib2 except ImportError: import urllib2 """ Description: Asks for soup. Might misinterpret your order as an insult... """ def html_page(url): logging.debug('requesting: {0}'.format(ur...
from functionality.function_base import FunctionBase from functionality.typedef import * import cv2 class Find(FunctionBase): def _get_param_def(self): print('got to check params') return { (Image, Image, Integer): self._find, } def _find(self, template, img, width): ...
import os import tempfile TMP_DIR = os.getenv("TMPDIR") or ("/fast/algo/tmp" if os.path.exists("/fast/algo/tmp") else "/tmp") def check_kwargs(**kwargs): if "dir" in kwargs: raise ValueError("Cannot set dir in keyword arguments") def mkdtemp(**kwargs): check_kwargs...
class Gestionnaire: def __init__(self): self.__listeabonner = {} self.__listeclient = {} @property def listeabonner(self): return self.__listeabonner @listeabonner.setter def listeabonner(self, id, carte): self.__listeabonner[id] = carte @property def listeclient(self...
#!/usr/bin/env python3 if __name__ == '__main__': for i in range(0,100,1): print(str(i) + ' ', end='') if (i%3) == 0: print('fizz', end='') if (i%5) == 0: print('buzz', end='') print('')
from selenium import webdriver from selenium.webdriver.common.keys import Keys driver = webdriver.Firefox() driver.get(r'http://google.com') element = driver.find_element_by_link_text('Business') driver.implicitly_wait(5) element.click()
#! /usr/bin/env python import glob, os, ast import pygame def init_datafile_mapSurface(expStartTime, subjectID, trialNum, filename=None): if filename is None: filename = os.path.join("../Processeddata/ERC_WP3_Year1_Study1_") + str(subjectID) + "_" + str(expStartTime) + "_visual_foraging_mapSurface_recreated...
def offToOn(panelValue): preview = op(me.var('preview')) source = op('..') preview.op('set_source')[0,0] = source.path preview.op('label/define')['label', 1] = source.name def onToOff(panelValue): pass
import urequests from mpython import * #连接网络 my_wifi = wifi() my_wifi.connectWiFi('', '') # 访问ip地址 api r = requests.get("http://ip-api.com/json/") print(r) print(r.content) # 返回响应的内容 print(r.text) # 以文本方式返回响应的内容 print(r.content) print(r.json()) # 返回响应的json编码内容并转为dict类型 # It's mandatory to close response objects a...
import json from unittest.mock import patch from django.test import TestCase from rest_framework.test import APIClient from orchestra.models import Todo from orchestra.tests.helpers.fixtures import TodoFactory from orchestra.tests.helpers.fixtures import TodoListTemplateFactory from orchestra.tests.helpers.fixtures i...
# Program to convert numeric date to string format. # example 03/12/2018 --> March 12, 2018 # Creathing months tuple to access month names form the date. months = [0,] infile = open('months.txt', 'r') for line in infile: line = line.strip() months.append(line) infile.close() MONTHS = tuple(months) def mai...
import os import sys script_dir = os.path.dirname(os.path.realpath(__file__)) sys.path.insert(0, os.path.join(script_dir, "lib"))
import numpy as np from task import Task from params import Params from task_dist import Task_Dist from machine import Machine from task_dist import Task_Dist class Env: def __init__(self, cur_time, time_step): self.params = Params() self.cur_time = cur_time self.time_step = time_step self.machines = [] sel...
import viz class Ship: def __init__(self, x, y): self.x = x self.y = y viz.startLayer(viz.QUADS) viz.vertexColor(1, 0, 0) viz.pointSize(100) viz.vertex(-5,0) viz.vertex(+5, 10) viz.vertex(+5, 0) viz.vertex(-5, 10) viz.endLayer() viz.startLayer(viz.QUADS) viz.vertexColor(0, 0, 1) viz.point...
# import modules import winapps # get each application with list_installed() for item in winapps.list_installed(): print(item)
# -*- coding: utf-8 -*- # Copyright notice # -------------------------------------------------------------------- # Copyright (C) 2019 Deltares # Rob Rikken # Rob.Rikken@deltares.nl # # # This library is free software: you can redistribute it and/or modify # it under the terms of th...
print("Hello world") def even_odd(num): """ To check whether the given number is even or odd""" try: if num%2==0: print("even number") else: print("odd number") except(Exception,en): print(en) num=5 even_odd(num)
import telepot class manicomio: def __init__(self, bot, chat_id, msg): self.bot = bot self.chat_id = chat_id self.msg = msg def check_command(self, msg): log = open('log_commands.txt', 'a') links = open('links.txt', 'a') adm_id = [] try: ...
import time import scrapy from scrapy_splash import SplashRequest from aliscrapy.items import TheGioiDiDong class AliscrapySpider(scrapy.Spider): name = "thegioididong" custom_settings = { "DOWNLOAD_DELAY": 5, "CONCURRENT_REQUESTS_PER_DOMAIN": 2 } count_page = 0 start_urls = [ ...
from collections import defaultdict for _ in range(int(input())): n, m, x = map(int, input().split()) arr_a = list(map(int, input().split())) arr_a.sort() arr_b = list(map(int, input().split())) def_dict = defaultdict(int) for i in range(len(arr_b)): def_dict[arr_b[i]] = 1 ...
""" 跨创造者分配权限 管理者、监控者权限授权 CY """ from UIAutomation.Page.Mobile.ExitAppPage import ExitAppPage from UIAutomation.Page.Mobile.LoginPage import LoginPage from UIAutomation.Page.Mobile.LongCardPage import LongCardPage from UIAutomation.TestCase.BaseTestCase import BaseTestCase from UIAutomation.Utils import get_user_id cl...
from django.contrib.auth.decorators import login_required from django.shortcuts import render from bookmarks.views.partials import contexts @login_required def active_bookmark_list(request): bookmark_list_context = contexts.ActiveBookmarkListContext(request) return render(request, 'bookmarks/bookmark_list.h...
from multiprocessing.dummy import Pool as ThreadPool import requests import time def getsource(url): try: html = requests.get(url) return html.text except : return None def single_thread(urls): t1=time.time() for i in urls: print(i) getsource(i) t2=time.ti...
# -*- coding: utf-8 -*- import os import json import tccli.options_define as OptionsDefine import tccli.format_output as FormatOutput from tccli.nice_command import NiceCommand import tccli.error_msg as ErrorMsg import tccli.help_template as HelpTemplate from tccli import __version__ from tccli.utils import Utils from ...
#!/usr/bin/env python import rospy from light_robot.msg import complx import random pub = rospy.Publisher("complex_topic", complx,queue_size = 10) rospy.init_node("complex_node") rate = rospy.Rate(1) while not rospy.is_shutdown(): com_num = complx() com_num.real = int(10*random.random()) com_num.imaginary = int...
import scrapy from scrapy import Request from parctice_one.items import ParcticeOneItem import time #scrapy crawl par_one class parctice_one(scrapy.Spider): name='par_one' def start_requests(self): url='http://www.mzitu.com/all/' yield scrapy.Request( url=url, callback=s...
import json def category_fee(i): category_fees = [] # calculate prices module,Logic to calculate the fee # Category_fee =Session fee + Minimum billing+ Maximum session fee # print(i['session Fee'], i['max_session fee'], i['min billing amount']) if i['max_session fee'] == 'False' and i['min billin...
from nltk.corpus import conll2002 from ner import generate_features_and_labels dev_sents = list(conll2002.iob_sents('esp.testa')) feats, labels = generate_features_and_labels(dev_sents) with open("results-mlp-lbfgs-200-0pos-prop.txt", "r") as f: line_count = 0 wrong_count = 0 for line in f: word, ...
''' when addressing the imbalance of dataset the predicted probability of a example can be perturbed but the rank-ordering of all the examples remain... How can I set up the voting committee to capture the most ppopular rank ordering. - try NOT correcting for imbalance in the dataset using the voting committee ''' f...
from collections import OrderedDict from django.contrib.auth.models import User from rest_framework import serializers from restbook.models import Record # one should also append a serializer for models.UserManager # to have a route for adding admin users. class UserSerializer(serializers.ModelSerializer): rec...
import pytest from ..variance import variance def test_variance(): def func(x): return 2*(x-1) var = variance(func, interval=[1, 2], num_division=100) assert pytest.approx(var, 1e-4) == 1/18
from common import * from . import sepia ID = 46 SCG_SECOND_FLOOR = 4600 SCG_FIRST_FLOOR = 4601 def setup(areas, ow): areas[ID] = { 'name': 'Sepia City Gym', 'emoji': '', 'dialog': '', 'map': [[SCG_SECOND_FLOOR], [SCG_FIRST_FLOOR]] } # Second Floor as...
# -*- coding: utf-8 -*- # pylint: disable=all """ Least Cost Xmission Command Line Interface """ import click import logging import os from rex.utilities.loggers import init_mult, create_dirs from rex.utilities.cli_dtypes import STR, INTLIST, INT from rex.utilities.hpc import SLURM from rex.utilities.utilities import ...
# Copyright (c) 2020 The University of Manchester # # 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or ...
import re import argparse parser = argparse.ArgumentParser() parser.add_argument('--goldfile', type=str, required=True) parser.add_argument('--predfile', type=str, required=True) args = parser.parse_args() def clean_data(line): line = line.split() line = [word.lower() for word in line] line...
#!/user/bin/env python # -*- coding:utf-8 -*- import torch import torch.nn.functional as F import matplotlib.pyplot as plt #torch.manual_seed(1) #假数据 x=torch.unsqueeze(torch.linspace(-1,1,100),dim=1) y=x.pow(2)+0.2*torch.rand(x.size()) def save(): #使用方法二建网络 net1=torch.nn.Sequential( torch.nn.Linear(1...
# Django from django.test import TestCase from django.contrib.auth.models import User from django.utils import timezone from django.conf import settings # Django REST from rest_framework.test import APIClient, APITestCase # App from comment.models import Comment from author.models import Author, Follow from post.models...
import AppKit from PyObjCTools.TestSupport import TestCase, min_os_level class TestNSButton(TestCase): def testMethods(self): self.assertResultIsBOOL(AppKit.NSButton.isBordered) self.assertArgIsBOOL(AppKit.NSButton.setBordered_, 0) self.assertResultIsBOOL(AppKit.NSButton.isTransparent) ...
from rest_framework.serializers import ModelSerializer from .models import Category class CategorySerializer(ModelSerializer): class Meta: model = Category fields = ('id', 'name', 'parent', 'children',)
# Uses python3 import sys def get_change(m): #Maximum no. of tens + max fives + spare change return m//10 + (m%10)//5 + (m%5) if __name__ == '__main__': m = int(sys.stdin.read()) print(get_change(m))
#!/usr/bin/env python import os import json import requests import logging from flask import Flask, jsonify, request, Response from functools import wraps logging.basicConfig(level=logging.INFO, format='%(asctime)s %(levelname)s: %(message)s') logger = logging.getLogger(__name__) port = os.getenv('PORT', 3000) debug...
import numpy as np import os def epsilon_greedy(instance, arms, randomSeed, horizon, f, epsilon, scale = 2, threshold = 0, highs = 0): """ :param instance: :param arms: :param randomSeed: :param horizon: :param f: :param epsilon: :param scale: :param threshold: :param...
#!/usr/bin/env python # -*- coding: UTF-8 -*- # Copyright 2017 Timothy Dozat # # 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 req...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations import mptt.fields import django.utils.timezone class Migration(migrations.Migration): dependencies = [ ('sites', '0001_initial'), ] operations = [ migrations.CreateModel( ...
from server.blueprints.bp_imports import * create = Blueprint("create", __name__) @create.route("/api/create/note", methods=["POST"]) @jwt_required() def create_note(): data = request.get_json() note_text = data["text"] note_deadline = data["deadline"] list_id = data["listId"] if note_text is No...
from homework2_rent import score_rent def test_rent(): expected_outcome = 0.48 assert score_rent() > expected_outcome test_rent()
import nbformat from tempfile import TemporaryDirectory from nbgrader.coursedir import CourseDirectory from nbgrader.utils import is_grade from e2xgrader.models import TemplateModel, PresetModel def create_temp_course(): tmp_dir = TemporaryDirectory() coursedir = CourseDirectory() coursedir.root = tmp_di...
from CvPythonExtensions import * import CvUtil import CvScreensInterface import CvDebugTools import CvWBPopups import PyHelpers import Popup as PyPopup import CvCameraControls import CvTopCivs import sys import CvWorldBuilderScreen import CvAdvisorUtils import CvTechChooser gc = CyGlobalContext() localText = CyTransla...
import unittest from nmigen import * from cores.ring_buffer_address_storage import RingBufferAddressStorage from util.stream import StreamEndpoint from util.sim import SimPlatform from cores.axi.axi_endpoint import AxiEndpoint, Response, AddressChannel, BurstType, DataChannel from cores.axi.buffer_writer import AxiBu...
__author__ = 'grahamcrowell' """ this script recieves fullpath of a latex file, or latex project folder # python -O "C:/Users/user/Dropbox/sublime_config/pymake_latex/pymake_latex.py" "C:/Users/user/Source/Repos/reference_sheets/cpp/cpp_general/cpp_general.tex" Mac OSX sublime text 2: build-system: /Users/graham...
filename = 'lesson05_cats_of_ulthar.txt' # Открытие файла в режиме чтения with open(filename, 'r') as file_object: lines = file_object.readlines() cat_count = 0 # Цикл перебирает все слова в файле и считает, сколько раз встречается слово "кошка" for line in lines: for word in line.split(): if word ==...
# a value (with any type), and a collection of messages accompanying that value to be seen on frontend. # This will probably get bigger class ValueReport: def __init__(self, value, messages): self.value = value self.messages = messages
lista1 = [1,2,3,4,5] lista2 = ["olá","mundo","!"] lista3 = [0,"olá",9.99,True] for i in lista1: print(i) for i in lista2: print(i) for i in lista3: print(i)
# # sprite_classes.py # Clases defining a vector, the main character for the game, and the obstacles (balls) # Last Modified: 8/17/2017 # Modified By: Andrew Roberts # import numpy as np import pygame import math class Vector(): def __init__(self, x, y): self.x = x self.y = y def __add__(self, vec): try: ...
from appdirs import AppDirs import sys import zerorpc import os from tempfile import mkstemp, gettempdir from shutil import move import json from modules.VaultClient import VaultClient from modules.AccessManager import AccessManager from util import constants import logging from util.util import Util import uuid from c...
# # @lc app=leetcode id=211 lang=python3 # # [211] Add and Search Word - Data structure design # # https://leetcode.com/problems/add-and-search-word-data-structure-design/description/ # # algorithms # Medium (36.38%) # Likes: 2056 # Dislikes: 97 # Total Accepted: 208.2K # Total Submissions: 554K # Testcase Exampl...
import re def isPalindrome(data): print(data) result = "" if len(data)<=1: # print("Inside") result = "Yes" print(result) return(result) else: if data[0] == " ": isPalindrome(data[1:]) if data[-1] == " ": isPalindrome(data[:-1]) ...
x = int(input('Введите число: ')) if x % 2 == 1: print("Нечётное") elif x % 2 == 0: print('Чётное')
# vim: tabstop=4 shiftwidth=4 softtabstop=4 # # Copyright (c) 2013-2016 Wind River Systems, Inc. # # SPDX-License-Identifier: Apache-2.0 # from sqlalchemy import Column, MetaData, String, Table from sysinv.common import constants ENGINE = 'InnoDB' CHARSET = 'utf8' def _populate_rpm_type(idisk_table): disks =...
import csv myData = list() with open('./data.csv') as csvfile: with open('./datadabase.csv', 'w') as csvfile1: fieldnames = ['row ID','LINK'] writer = csv.DictWriter(csvfile1, fieldnames=fieldnames) writer.writeheader() reader = csv.DictReader(csvfile) for row in reader: ...
#!/usr/bin/env python """ Example use of mongoDB swiss knife """ from MongoDbUtilLean import MongoDbUtil def main(): daqFilesWatcherColl = MongoDbUtil('ro').database()['daq_files_watcher_P16id'] print daqFilesWatcherColl mx=5 print "dump first ",mx for it in daqFilesWatcherColl.find().limit(mx):...
""" Data simulation Quantiphyse plugin Data simulation process Author: Martin Craig <martin.craig@eng.ox.ac.uk> Copyright (c) 2016-2017 University of Oxford, Martin Craig """ import numpy as np from quantiphyse.data import NumpyData from quantiphyse.processes import Process from quantiphyse.utils import QpException...
# -*- coding: utf-8 -*- # Generated by Django 1.10.4 on 2016-12-08 09:54 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('healthy', '0003_auto_20161208_1153'), ] operations = [ migrations.AlterFiel...
""" ********************************************************************** Description: Charting Module to create graphs with Pygal and matplolib save files in .svg and .png Author: Victor Robles Project: Assigment 10 Revision: 08/23/2020 ************************************************...
# [Classic] # https://leetcode.com/problems/product-of-array-except-self/ # 238. Product of Array Except Self # History: # Facebook # 1. # Feb 15, 2020 # 2. # Apr 6, 2020 # 3. # Apr 22, 2020 # 4. # May 12, 2020 # Given an array nums of n integers where n > 1, return an array output such that output[i] is # equal to ...
#!/usr/bin/env python import os, sys, glob, shutil ALIAS = { 'true' : 'truth', 'simple' : 'rec_simple', 'charge' : 'rec_charge_blob', 'deblob' : 'rec_charge_cell', 'mc' : 'mc', 'deadarea' : 'channel-deadarea', 'flash' : 'op', 'cluster' : 'cluster' } def main(filename, op...
import design # Дизайн проекта import sys # Нужен для передачи argv в QApplication from PyQt5 import QtWidgets import os class ExampleApp(QtWidgets.QMainWindow, design.Ui_MainWindow): def __init__(self): # Это нужно для доступа к переменным, методам # и т.п. в дизайне super().__init__() ...
# hangman game import random HANGMAN_PICS = [''' +---+ | | | ===''', ''' +---+ 0 | | | ===''', ''' +---+ 0 | | | | ===''', ''' +---+ 0 | /| | | ===''', ''' +---+ ...
from rest_framework import serializers from myapi.models import Product, PriceRecording, Price class PriceSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Price fields = ('seller', 'price') class PriceRecordingSerializer(serializers.HyperlinkedModelSerializer): prices = PriceSerializer(...
# Name: Zhang Hao # ID : 1000899 # Time used to break hash5.txt : 67s # # # { '0d5b558d5f6744deaaf5b016c6c77a57': 'tpoin', # '1b31905c59f481958d2eb72158c27ac7': 'egunb', # '1b4baba3ae3be69857b323cf6b7fcd80': 'sso55', # '644674d142ba2174a80889f833b32563': 'owso9', # '6e313b70d12de950443527a33d80...
from os.path import join from xml.dom.minidom import Element from useless.base.xmlfile import TextElement from useless.db.midlevel import StatementCursor from useless.sqlgen.clause import Eq from paella.db.xmlgen import BaseVariableElement class ProfileVariableElement(BaseVariableElement): def __init__(self, tra...
import cv2 import numpy as np from methodtools import lru_cache from liveprint.pose import TorsoKeyPoints from liveprint.system_setup import PRCoords def adapt_pic(print_, image, torso: TorsoKeyPoints): """ This function crops and warps :param print_: picture to be transformed and placed over the backagr...
from weakref import ref as weakref from rb.ketama import Ketama from rb.utils import text_type, bytes_type, integer_types, crc32 from rb._rediscommands import COMMANDS class UnroutableCommand(Exception): """Raised if a command was issued that cannot be routed through the router to a single host. """ cl...
# Generated by Django 3.0.4 on 2020-04-07 18:38 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('home', '0003_sorting_remove_same'), ] operations = [ migrations.RemoveField( model_name='sorting', name='remove_same', ...
# Copyright 2009 the Melange authors. # # 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...
sudo raspi-config #In den Einstellungen auf Peripheriegeräte wechseln und bei Kamera auf “enable” wechseln. #Bilder #Über das Terminal kann ein Bild aufgenommen mittels folgendem Befehl: raspistill -o bild.jpg #Das gespeicherte Bild wird im Home abgelegt. #Video #Über das Terminal kann auch ein Video aufgenommen ...
from flask import Flask, jsonify from flask import Flask from matplotlib import style import numpy as np import pandas as pd import datetime as dt import matplotlib.pyplot as plt import sqlalchemy from sqlalchemy.ext.automap import automap_base from sqlalchemy.orm import Session from sqlalchemy import create_engin...
import main def test_process_negative_input(): try: main.process(-1) except SystemExit: assert (True) def test_process_word_input(): try: main.process('hello') except SystemExit: assert (True) def test_process_float_input(): try: main.process(4.5) ex...
import sys try: import pandas as pd except ImportError as e: print("pandas is required for this example. Please install with `pip install pandas` and then try again.") sys.exit() import numpy as np import kmapper as km import sklearn from sklearn import ensemble # For data we use the Wisconsin...
__author__ = 'marcopereira' from pandas import DataFrame import numpy as np import pandas as pd from parameters import WORKING_DIR import os class MC_Vasicek_Sim(object): def __init__(self, datelist,x, simNumber,t_step): #SDE parameters - Vasicek SDE # dr(t) = k(θ − r(t))dt + σdW(t) self.kappa = x...
from peachpy.x86_64 import ADD, SUB, JB, JAE, JZ, \ ALIGN, Loop, \ GeneralPurposeRegister32, GeneralPurposeRegister64 def software_pipelined_loop(reg_n, batch_elements, instruction_columns, instruction_offsets): # Check that we have an offset for each instruction column ass...
import json import os from operator import itemgetter from loader.Database import DBViewIndex, DBView, DBManager from loader.Actions import CommandType from exporter.Shared import AbilityData, SkillData, PlayerAction, ActionCondition from exporter.Mappings import WEAPON_TYPES, ELEMENTS, CLASS_TYPES MODE_CHANGE_TYPES ...
from django.conf.urls import url from browse import views from django.contrib.staticfiles.urls import staticfiles_urlpatterns urlpatterns=[ url(r'^$',views.view_order, name="home"), url(r'webhook_notify/', views.webhook_notification, name="webhook_notification"), url(r'update_order/$',views.update_order, n...
from copy import deepcopy class Connect4Game(object): """Plays a game of Connect 4 between two players""" def __init__(self, player1, player2): """Sets up the game between two players""" self.player1 = player1 self.player2 = player2 self.board = [7*[0] for i in range(6)] def play(self): """Runs the...
import os, random, requests, sys, json import faker from datetime import datetime from flask import render_template, flash, redirect, url_for, request from flask_paginate import Pagination, get_page_parameter from app import app, db from app.forms import LoginForm, RegistrationForm, EditProfileForm, PostForm from flask...
import os import numpy as np import random as rn import environment from keras.models import load_model os.environ['PYTHONHASHSEED'] = '0' np.random.seed(42) rn.seed(12345) #SETTING THE PARAMETERS number_actions = 5 direction_boundary = (number_actions - 1) / 2 temperature_step = 1.5 env = environment.Environment(op...
import sys import logging import re from easy_alert.setting.setting_error import SettingError from easy_alert.watcher.command_watcher import CommandWatcher from easy_alert.entity.level import Level if sys.version_info < (2, 7): import unittest2 as unittest else: import unittest class TestCommandWatcher(unitt...
class LazyView: def __init__(self, iterableFn): self.iterableFn = iterableFn self.memoized = None def filter(self, fn): return LazyView(lambda: filter(fn, self.iterableFn())) def map(self, fn): return LazyView(lambda: map(fn, self.iterableFn())) def flatmap(self, f...
#!/usr/bin/env python import math # See formulae here: http://www.maths.surrey.ac.uk/hosted-sites/R.Knott/Fibonacci/fibFormula.html?n=20 def getfibdigits(n): phi = (1+math.sqrt(5))/2 return n * math.log10(phi) - math.log10(math.sqrt(5)) i = 1 while True: if getfibdigits(i) >= 999: print i ...
#invoer woord = str(input('Geef verborgen woord: ')) geld = int(input('Gedraaid geldbedrag: ')) letter = str(input('Geef letter: ')) totaal_geld = 0 kaas = '' #bewerking while letter in woord and letter not in kaas: totaal_geld += geld kaas += letter letter = str(input('Geef letter: ')) if letter not in w...
from django.db import models from django.contrib.auth.models import User # Create your models here. class Product(models.Model): title = models.CharField(default='例:app名称', max_length=50) intro = models.TextField(default='app介绍') icon = models.ImageField(default='default.png', upload_to='image/') v...
#!/usr/bin/env python3 # (1 2 4 5) (1 3 4 6) = 1->2, 2->4->6, 6->1, 3->4, 4->5, 5->1->3 = (1 2 6)(3 4 5) a = [1, 2, 4, 5] b = [1, 3, 4, 6] ad = dict(zip(a, a[1:] + a[0:1])) bd = dict(zip(b, b[1:] + b[0:1])) jr = list(set([*ad.keys(), *bd.keys()])) im = [bd.get(j, j) for j in [ad.get(i, i) for i in jr]] print(jr) ...
# -*- coding: utf-8 -*- # (c) Copyright IBM Corp. 2010, 2019. All Rights Reserved. # pragma pylint: disable=unused-argument, no-self-use, line-too-long """Function implementation""" """ This module contains the ElasticFeedDestination for writing Resilient data to an Elasticseach index. """ import base64 import copy i...
from pyspark.mllib.feature import HashingTF,IDF from pyspark import SparkConf,SparkContext import math conf = SparkConf().setMaster("local").setAppName("big_data") sc = SparkContext(conf=conf) dirinput = "../bigdata/hw1/stock/amazon.txt" rdd = sc.textFile(dirinput).flatMap(lambda text:text.split()).map(lambda string: ...
from urllib.request import urlopen from pymongo import MongoClient import json import bs4 as bs import parse_industry_queries import requests uri = "mongodb+srv://stockUser:stockUserPassword@cluster0-tdhz8.gcp.mongodb.net/test?retryWrites=true&w=majority"; client = MongoClient(uri) db = client["stockInformation"] db_in...
import os, sys import multiprocessing from joblib import Parallel, delayed from pytube import YouTube from op_data import set_data, get_data from Utils import Utils cup_num = multiprocessing.cpu_count() utils = Utils() channels = get_data('data/news_channel.json') def send_request(download_path, video_id): # if...