content
stringlengths
5
1.05M
from matplotlib import pyplot # Loan Calculator App def get_loan_info(): """Get the basic information of a loan and store it in a dictionary""" # Create a blank dist to represent a loan loan = {} # Get user input for the categories of the loan loan['principal'] = float(input("\nEnter the loan am...
""" Tipo None O tipo de dado None em Python representa o tipo sem tipo, ou poderia ser conhecido também como tipo vazio, porém, falar que é um tipo sem tipo é mais apropriado. OBS: O tipo None é SEMPRE especificado com a primeira letra maiúscula. Certo: None Errado: none Quando utilizamos? - Podemos utilizar None...
# Princeton University licenses this file to You 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 writin...
from django.conf.urls import url from modernrpc.views import RPCEntryPoint from . import views app_name = 'frontpage' urlpatterns = [ url(r'^rpc/', RPCEntryPoint.as_view()), ]
#!/usr/bin/python # This script checks whether the files supplied on the command line conform # to the Google Java style (as enforced by the google-java-format program, # but with improvements to the formatting of annotations in comments). # If any files would be affected by running run-google-java-format.py, # this s...
from django.contrib.auth import backends from django.contrib.auth.models import Permission from .utils import get_permissions_model class ModelBackend(backends.ModelBackend): """ Authenticates against settings.AUTH_USER_MODEL. This class overrides `_get_group_permissions` to find permissions based on ...
#!/usr/bin/env python # Copyright (c) Microsoft. All rights reserved. # Licensed under the MIT license. See LICENSE file in the project root for # full license information. import json import os class EdgeConfiguration: """ This class represents the edge hub configuration that is applied to an edgehub device...
from pubnub import utils from pubnub.endpoints.objects_v2.objects_endpoint import ObjectsEndpoint, ListEndpoint, \ IncludeCustomEndpoint, UuidEndpoint, ChannelIncludeEndpoint from pubnub.enums import PNOperationType from pubnub.enums import HttpMethod from pubnub.models.consumer.objects_v2.memberships import PNRemo...
# -*- coding: utf8 -*- #/usr/bin/python3.7 from datetime import datetime, timezone import telegram from telegram.ext import Updater, Filters, MessageHandler, CallbackQueryHandler, CallbackContext from telegram import InlineKeyboardMarkup, InlineKeyboardButton, ParseMode, Message import os import codecs from Config im...
from Block import Block genesisTransactions =["a saoshi sent ivan 999900 bitcoin","hal finney sent 10 bitcoins to ivan"] genesisBlock = Block(0, genesisTransactions) block2Transactions = ["ivan sent 10 bitcoin to satoshi", "satoshi sent 10 bitcoin to starbuck"] block2 = Block(genesisBlock.getblockHash(), block2Tran...
""" A federated learning server using FedAsync. Reference: Xie, C., Koyejo, S., Gupta, I. (2019). "Asynchronous federated optimization," in Proc. 12th Annual Workshop on Optimization for Machine Learning (OPT 2020). https://opt-ml.org/papers/2020/paper_28.pdf """ import logging import os from collections import Orde...
#!/usr/local/bin/python # encoding: utf-8 """ *Convert a python list of dictionaries to pretty csv output* :Author: David Young :Date Created: June 28, 2016 """ ################# GLOBAL IMPORTS #################### import sys import os import io import csv from decimal import Decimal from datetime import date...
# -*- coding: utf-8 -*- import pytest from model.contact import Contact from fixture.application import Application @pytest.fixture def app(request): fixture = Application() request.addfinalizer(fixture.destroy) return fixture def test_add_contact(app): app.open_home_page() app.session.login...
from numpy import * from .finite_polygons import voronoi_finite_polygons_2d
#!/usr/bin/env python ''' The Environment is necessary for lexical scoping. The book touches upon the difference between lexical and dynamic scoping with the latter being extremely rare in practice because of its need to be executed at runtime to pinpoint exactly what each variable will be. Lexical scoping is preferre...
""" This class is used to create the following OpenSees TCL Commands: Plain Pattern Uniform Excitation Pattern Multi-Support Excitation Pattern DRM Load Pattern """ __author__ = 'marafi' from OpenSeesAPI.OpenSees import OpenSees class UniformExcitation(OpenSees): """ pattern UniformExcitation $patternTag $di...
import sys,bisect,string,math,time,functools,random,fractions from heapq import heappush,heappop,heapify from collections import deque,defaultdict,Counter from itertools import permutations,combinations,groupby def Golf():*a,=map(int,open(0)) def I():return int(input()) def S_():return input() def IS():return in...
""" Exposes regular REST commands as services. For more details about this platform, please refer to the documentation at https://home-assistant.io/components/hassio/ """ import asyncio import logging import os import re import aiohttp from aiohttp import web from aiohttp.web_exceptions import HTTPBadGateway from aio...
"""Given two binary strings a and b, return their sum as a binary string. Example 1: Input: a = "11", b = "1" Output: "100" Example 2: Input: a = "1010", b = "1011" Output:'10101' """ class Solution: def addBinary(self, a: str, b: str) -> str: result = [] carry = 0 i, j = len(a) - 1, ...
# Faça um programa que tenha uma tupla com várias palavras (desconsiderar os acentos) # depois disso você deve mostrar, para cada palavra quais são as suas vogais pala = ('APRENDER', 'PROGRAMAR', 'LINGUAGEM', 'PYTHON', 'CURSO', 'GRATIS', 'ESTUDAR', 'PRATICAR', 'TRABALHAR', 'MERCADO', 'PROGRAMADOR', 'FUTURO') f...
import torch def where_update(w, v, data): v = torch.tensor(v, dtype=data.dtype, device=data.device) return torch.where(w, v, data) def torch_rgb_to_hls(images): """ Transform a batch of RGB images into HLS format. Parameters ---------- images : torch.Tensor (shape (N, 3, H, W)) ...
#!/usr/bin/env python3 import sys import numpy as np sys.path.append('_setup/model') from model import * N = 5 import korali e = korali.Experiment() e["Problem"]["Type"] = "Propagation" e["Problem"]["Execution Model"] = lambda modelData: logistic_reference(modelData) e["Variables"][0]["Name"] = "V1" e["Variables"][...
import discord from discord.ext import commands from modules import utils, paginator import asyncio import aiohttp import time import base64 import iso8601 from typing import List, Optional, Tuple, Dict from datetime import datetime, timezone from math import ceil, floor, inf class UbisoftAPIError(Exception): pa...
import os class Config: NEWS_API_BASE_URL ='https://newsapi.org/v2/everything?q=apple&from=2021-06-08&to=2021-06-08&sortBy=popularity&apiKey=6fd6f306204d4fc79908618ff7bc14ea' NEWS_ARTICLE_URL = 'https://newsapi.org/v2/everything?q=Apple&from=2021-06-09&sortBy=popularity&apiKey={}' NEWS_API_KEY = os.env...
def g(): counter = 200 for use_POStagging in range (0, 2): for use_temporalComp in range (0, 2): for use_counterFact in range (0, 2): for use_sentiment in range (0, 2): for pre_drop_stop_words in range (0, 2): for pre_automated_gramma_corector in range (0, 2): for pre_automated_gr...
from tornado import web from sprockets.http import app, mixins import sprockets.http class StatusHandler(mixins.ErrorLogger, mixins.ErrorWriter, web.RequestHandler): """Example that exercises the mix-ins in this library.""" def get(self, status_code): """ Returns the requ...
""" Check which images are available. Script that looks at the ADNIMERGE file and checks how many of the subjects have either a MRI or a PET scan downloaded. It also checks for the same file existance in the BIDS directory. The output of this Script is a .csv file with the availabiliy information of all subjects menti...
# -*- coding: utf-8 -*- """Iris-folower data set.ipynb Automatically generated by Colaboratory. Original file is located at https://colab.research.google.com/drive/1wXrRdFBPpyP9erw9QNPqDoGxF-0A6fZL """ import pandas as pd import numpy as np import matplotlib.pyplot as plt import seaborn as sns from sklearn.model...
__author__ = "jacksonsr45@gmail.com" import sqlite3 class User: def __init__(self): self.error = False self.msg = " " def __create__(self): conn = sqlite3.connect('login.db') cursor = conn.cursor() try: cursor.execute('CREATE TABLE IF NOT EXISTS user ( id ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import cv2 import numpy as np import os dimension = 42 * 28 dirname = 'centered' files = [fname for fname in os.listdir(dirname) if fname.endswith('.png')] files = sorted(files, key=lambda f: int(f.split('_')[0])) X = np.empty((len(files), dimension)) Y = np.zeros((le...
def aumentar(n=0, taxa=0, f=False): a = n + (n * taxa / 100) return a if not f else moeda(a) def diminuir(n=0, taxa=0, f=False): a = n - (n * taxa / 100) return a if not f else moeda(a) def dobro(n=0, f=False): a = n * 2 return a if not f else moeda(a) def metade(n=0, f=False): a = n *...
# -*- coding: utf-8 -*- import os from tencentcloud.common import credential from tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKException # 导入对应产品模块的client models。 from tencentcloud.cvm.v20170312 import cvm_client, models import json # 导入可选配置类 from tencentcloud.common.profile.client_p...
# -*- coding: utf-8 -*- """ @date: 2020/5/20 下午4:12 @file: anchor_box.py @author: zj @description: """ from itertools import product import torch from rpn.utils import box_utils class AnchorBox(object): def __init__(self, cfg): anchor_config = cfg.MODEL.ANCHORS self.stride = anchor_config.STR...
# This script submits a FASTA file to the MEME web service at NBCR # and downloads the resulting output to the directory meme_out. # Based on the script pdb2pqrclient.pl included in the 2.0.0 Opal-Python # toolkit, available at http://www.nbcr.net/software/opal/ # Import the Opal libraries from AppService_client impor...
#1020 dias=int(input()) ano = dias // 365 mes = (dias % 365) //30 dia = (dias % 365) % 30 print(f"{ano} ano(s)\n{mes} mes(es)\n{dia} dia(s)")
import json import os import sys import inspect import argparse import typing import logging as log from pathlib import Path from typing import Optional, List, Dict, Union, Collection, Any import toml def build( conf: Union[str, Dict], assets: Optional[Dict[str, Any]] = None, base: Optional[str] = None, ...
from django.db import models from django.db.models.fields.related import ManyToManyField from django.contrib.auth.models import User from tinymce.models import HTMLField from cloudinary.models import CloudinaryField from django.contrib.auth.models import User from django.db.models.signals import post_save from django.d...
# Copyright 2020 Half-Shot # # 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 writing, so...
"""General functions for mathematical and numerical operations. Functions --------- - confidence_bands - Bin by `xx` to calculate confidence intervals in `yy`. - confidence_intervals - Compute the values bounding desired confidence intervals. - cumstats - Calculate a cumulative averag...
### All utility functions for combinatorial search over perturbation mask import numpy as np import itertools import random import math from utils import * import os import time import scipy.io as scio import datetime import re import matplotlib.pyplot as plt import pylab import os import csv from skimage import tr...
# Generated by Django 3.1.1 on 2021-02-27 04:07 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Post', fields=[ ...
import dash_core_components as dcc import dash_bootstrap_components as dbc import dash_html_components as html from dash.dependencies import Input, Output from app import app from sections import navbar from sections import footer from sections import pic from sections import bio from sections import prog from sectio...
from __future__ import unicode_literals from django.core.cache import cache from .utils import AppTestCase from .testapp.models import Level2 class ModelInheritanceTests(AppTestCase): """ Tests with model attributes for multiple object levels """ def test_init_args(self): """ Test wh...
import binascii import struct class Buffer: DefaultSize = 1450 def __init__(self, str_ = ""): if isinstance(str_,str): self.Data = str_.encode() else: self.Data = str_ self.ActualSize = len(str_) def __str__(self): return self.Data.decode("utf-8"...
import Python_API #Initializes Runtime from Python_API import _java_gateway def PrintEvent(timestamp, inEvents, outEvents): ''' Prints Stream Event to Log :param timestamp: :param inEvents: :param outEvents: :return: ''' _java_gateway.entry_point.printEvent(timestamp,inEvents,outEvent...
from collections import OrderedDict from tempfile import TemporaryDirectory from django.test import override_settings from geotrek.authent.tests.factories import StructureFactory from georiviere.tests import CommonRiverTest from georiviere.proceeding.models import Proceeding from georiviere.proceeding.tests.factories...
import requests import urllib import json from pandas import DataFrame def request_daily_stock_price(date, bid, uid): """ Get daily stock price data including some of financial data from the KRX Parameters ---------- date : string, e.g. '2018-02-02' or '20180202' bid : bid for each screen num...
# Generated by the protocol buffer compiler. DO NOT EDIT! # source: karps/proto/std.proto import sys _b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1')) from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf import reflection a...
from app.schemas import Item, ItemCreate from app.crud.base import CRUDBase from app.utils import redis_manager class CRUDItem(CRUDBase[Item, ItemCreate]): pass item = CRUDItem(Item, redis_manager)
import os import sys import asyncio sys.path.append(os.path.dirname(os.path.abspath(__file__)).rsplit('/',1)[0]) from homeaccountant.log.logger import getLogger, log_wrapper from homeaccountant.server.api.app import WebAPI logger = getLogger() log_wrapper.start() api = WebAPI() try: asyncio.get_event_loop().ru...
# Taken from https://github.com/alessandromaggio/quicksnmp # Quick SNMP (quicksnmp) by alessandromaggio from pysnmp import hlapi def construct_object_types(list_of_oids): object_types = [] for oid in list_of_oids: object_types.append(hlapi.ObjectType(hlapi.ObjectIdentity(oid))) return o...
import re import math from enum import Enum import os os.system("") class TokenEnum(Enum): num = 1 newline = 2 skip = 3 lparen = 4 rparen = 5 compopr = 6 binopr = 7 const = 8 func = 9 end = 10 mismatch = 11 class Token(): def __init__(self, type, value, line, start, ...
""" Processes two dump files. """ from mw import xml_dump files = ["examples/dump.xml", "examples/dump2.xml"] def page_info(dump, path): for page in dump: yield page.id, page.namespace, page.title for page_id, page_namespace, page_title in xml_dump.map(files, page_info): print("\t".join([str(page_i...
from twisted.internet import reactor from twisted.internet.protocol import Protocol,Factory import argparse class Chat(Protocol): def __init__(self, users): self.users = users self.name = None self.state = "GETNAME" def connectionMade(self): print("Connection made") se...
import torch, os import torch.nn as nn import torch.utils import torch.utils.data import numpy as np from torch.autograd import Variable from models.graph.gcn.gcn_model import GCN from models.graph.gat.gat_model import GAT from utils.adj_matrix import * from utils.heatmaps import * import matplotlib.pyplot as plt from ...
# --*-- coding: utf-8 --*-- import os import sys BASE_DIR = os.path.abspath(os.path.join(os.path.dirname(__file__),"..")) sys.path.append(BASE_DIR) import time from news_crawler.crawler import crawl from settings import * from user_service.update_user_keyword import * def start(): cursor = mydb.cursor() cursor...
# SPDX-FileCopyrightText: 2021 Wolfgang Traylor <wolfgang.traylor@senckenberg.de> # # SPDX-License-Identifier: MIT import gzip import os import re import shutil from termcolor import cprint from trace_for_guess.find_input import find_files def gunzip(filename, targetdir): """Decompress a gzip-compressed file i...
#!/usr/bin/python import os, sys, requests, json from datetime import datetime import time import random myCMD = sys.argv[2]; def callWebservicePost(entity, jsonString): #set up the url and headers# fast server urlF = "http://35.163.116.152:8080/SensorThingsServer-1.0/v1.0/" + entity# slow server urlS = "http://...
from django.template import Template from utils.device import templates_for_device class TemplateForDeviceMiddleware(object): """ Inserts device-specific templates to the template list. """ def process_template_response(self, request, response): if hasattr(response, "template_name"): ...
import nuke nodebar = nuke.menu("Nodes") #============================================================================== # Add Fuser & zpRender items to 3D menu: menu = nodebar.findItem("3D") if menu is not None: menu.addCommand("Stereo Camera", "nuke.createNode('StereoCam2')", icon="Camera.png") gmenu = me...
import re import unittest import paramiko from helpers.ssh_server_actions import exec_commands from main.maincontroller import MainController from view_models.configuration_proxy import PIN_INCORRECT_ERROR_MSG class XroadLoginSoftwareToken(unittest.TestCase): """ CP_05 Log in to a Software Security Token ...
# Problem: https://dashboard.programmingpathshala.com/practice/question?questionId=32&sectionId=1&moduleId=1&topicId=2&subtopicId=25&assignmentId=5 t = int(input()) n = [] q = [] for i in range(t): tm = int(input()) n.append(tm) tp = [int(i) for i in input().split()] q.append(tp) m = 10**6 spf = [-1]...
# Generated by Django 2.0.8 on 2019-06-03 13:31 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('home', '0007_merge_20190320_0931'), ('home', '0007_social_media'), ] operations = [ ]
from generated.callexecuter_metrics_pb2 import Metrics def protobuf_deserialize(data): metrics = Metrics() metrics.ParseFromString(data) return metrics
from decimal import ROUND_DOWN import pytest from prices import Money def test_addition(): money = Money(10, 'BTC') + Money(20, 'BTC') assert money.amount == 30 assert money == Money(30, 'BTC') with pytest.raises(ValueError): Money(10, 'BTC') + Money(30, 'USD') with pytest.raises(TypeErr...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Window functions for input field shaping. * :func:`.window.aperture`: Round (circular) aperture function. * :func:`.window.blackman`: A 2D Blackman window function. * :func:`.window.gaussian`: A 2D Gaussian window function. * :func:`.window.gaussian_beam`: A Gaussian ...
print("this will not run because of the custom parse on the .py file")
import tensorflow as tf from easydict import EasyDict as edict def get_optimizer(schedule: tf.keras.optimizers.schedules.LearningRateSchedule, cfg: edict): """ """ if schedule is not None and 'learning_rate' in cfg.optimizer.kwargs: del cfg.optimizer.kwargs['learning_rate'] ...
import numpy as np from scipy import io import matplotlib.pyplot as plt from matplotlib import colors import cv2 def find_closest_centroids(X, initial_centroids): K = initial_centroids.shape[0] idx = np.zeros((X.shape[0], 1)) for i in range(X.shape[0]): distance = np.inf for j in range(K):...
# Copyright 2013 Devsim LLC # # 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 writing, s...
from aiohttp import web from app.predictor import get_prediction import logging import json async def handler(request: web.Request) -> web.Response: request.app['config'] return web.Response(status=200, text='Some text') async def hello_handler(request: web.Request) -> web.Response: return web.Response(...
import asyncio import time from aiohttp import ClientSession # type: ignore from uhlive.stream.conversation import Conversation, Ok, build_conversation_url async def stream_file(audio_path, socket, client, codec): chunk_size = 4000 if codec.startswith("g711") else 8000 with open(audio_path, "rb") as audio_...
#!/usr/bin/env python3 # Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: MIT-0 # Setter updating tag groups in DynamoDB import logging import boto3 import botocore from admin import ExecutionStatus # Instantiate logging for this module using its file name ...
# -*- coding: utf-8 -*- # ***************************************************************************** # NICOS, the Networked Instrument Control System of the MLZ # Copyright (c) 2009-2022 by the NICOS contributors (see AUTHORS) # # This program is free software; you can redistribute it and/or modify it under # the t...
# Copyright (c) 2010-2020, sikuli.org, sikulix.com - MIT license # # 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 b...
import asyncio from apscheduler.schedulers.asyncio import AsyncIOScheduler from .dates import EASTERN_STANDARD_TIME class DaemonHelper: """ Simple wrapper class to wire up cron and interval tasks with AsyncIoScheduler """ @staticmethod def add(job_fn, **kwargs) -> None: ...
from fastaImport import * def findSharedMotif(seq_dict) : '''takes dict with sequences as input and returns a longest common substring of the collection''' seq_list = list( seq_dict.values() ) seq_list = sorted(seq_list, key=len) shortest_seq = seq_list.pop(0) shortest_seq_len = len(shortest_seq) for chunk_...
import os import joblib import logging from real_estate_analysis.Model.Model import ModelObject logger = logging.getLogger(__name__) def validate_model(model, dict_scores, file_name): """ Check if a new model performs better than an existing model. If True, save the model and archive the previous model ...
# -*- coding: utf-8 -*- import win32api class KEYCODE: ALT = 18 F4 = 115 class Operator: def __init__(self): pass def press(self, keycode): self.keydown(keycode) self.keyup(keycode) def keydown(self, keycode): win32api.keybd_event(keycode, 0, 0) def keyup(se...
#! /home/pavel/rtStockPrices/python3-env/bin/python import pandas as pd import datetime import sys import smtplib import base64 import sqlite3 import logging import os import io_util mainDir = os.path.dirname(os.path.abspath(__file__)) logFile = mainDir + '/rtPrices.log' dbName = mainDir + '/rtPrice...
# You are given an integer array A. From some starting index, you can make a series of jumps. # The (1st, 3rd, 5th, ...) jumps in the series are called odd numbered jumps, # and the (2nd, 4th, 6th, ...) jumps in the series are called even numbered jumps. # You may from index i jump forward to index j (with i < j) i...
from CommonServerPython import * from CommonServerUserPython import * ''' CONSTANTS ''' DATE_FORMAT = '%Y-%m-%dT%H:%M:%SZ' ''' CLIENT CLASS ''' class Client(BaseClient): def _httpp_request(self, method, url_suffix='', full_url=None, headers=None, auth=None, json_data=None, params={}, da...
import argparse from bs4 import BeautifulSoup from utils import parse_html, gen_report import requests arg_parser = argparse.ArgumentParser(description='Generate a report of the references in a Wikipedia article') arg_parser.add_argument('wiki_link', help='link to the Wikipedia article', type=str) arg_parser.add_argum...
# -*- coding: utf-8 -*- """ Created on Sat Feb 3 08:41:33 2018 @author: xingrongtech """ from analyticlab.system.exceptions import tooMuchDataForTestException, tooLessDataForTestException from analyticlab.system.numberformat import f sTable = {} sTable[0.95] = {8:0.99, 9:0.97, 10:0.95, 12:0.91, 15:0.85, 20:0.77, 25:...
# Generated by Django 3.2.7 on 2021-10-31 14:07 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('garnbarn_api', '0021_assignment_reminder_time'), ] operations = [ migrations.RenameField( model_name='assignment', old_name=...
import re from tabela_tokens import TabelaTokens class AnalisadorLexico: def __init__(self, dados): self.indice = 0 self.lista_tokens = [] self.tabela_tokens = TabelaTokens().tabela_tokens self.palavra_tratada = dados[0] self.palavra_original = dados[1] sel...
def bake_to_keyframes(frame_start=1, frame_end=250, step=1): pass def connect(con_type='FIXED', pivot_type='CENTER', connection_pattern='SELECTED_TO_ACTIVE'): pass def constraint_add(type='FIXED'): pass def constraint_remove(): pass def mass_calculate(material='DEFAULT', density=1.0): pass ...
# -*- coding: utf-8 -*- """ This code is auto generated from troposphere_mate.code_generator.__init__.py scripts. """ import sys if sys.version_info.major >= 3 and sys.version_info.minor >= 5: # pragma: no cover from typing import Union, List, Any import troposphere.policies from troposphere import Template, ...
# This software is distributed under the 3-clause BSD License. # NOTE: as of March 2022, consider aircondB.py as an alternative to aircond.py # Use bundle_pickler.py to create bundle pickles # NOTE: As of 3 March 2022, you can't compare pickle bundle problems with non-pickled. See _demands_creator in aircondB.py for mo...
from collections import deque from imutils.video import VideoStream import numpy as np import argparse import cv2 import imutils import time t=time.time() d=0 disp=0 i=0 cenx=[] ceny=[] ap = argparse.ArgumentParser() ap.add_argument("-v", "--video", help="path to the (optional) video file") ap.add_argu...
#!/usr/bin/env python3 # Run with: spark-submit train.py from pyspark.ml.classification import LogisticRegression from pyspark.ml.feature import StopWordsRemover, Tokenizer, Word2Vec from pyspark.sql import Row, SparkSession import csv, re spark = SparkSession \ .builder \ .appName("Sentiment Analysis") \ ...
# used by makeGrid to print contents nicely to console def printGrid(grid): for row in grid: rowStr = ''; for item in row: rowStr = rowStr + item + ' ' print(rowStr) # constructs grid with r rows and c columns and fills each element with value of char # returns grid and prints grid to screen # call...
""":mod:`Portfolio` -- Provides an interface for loading a user's stock portfolio .. module:: Portfolio :synopsis: Provides an interface for loading a user's stock portfolio .. moduleauthor:: Kelly McBride <kemcbride28@gmail.com> """ from neolib.stock.Stock import Stock import requests class Portfolio: """Pr...
""" Map-reduce implementation """ from collections import defaultdict def map_reduce(sequence, map_func, reduce_func): """ * Groups items in iter using map_func * For each item from all groups reduce_func is called Returned tuple contains (k, v) pairs with k coming from map_func and v from reduce_fun...
from sympy import * import json import sys from sympy.integrals.manualintegrate import integral_steps from sympy.parsing.sympy_parser import parse_expr from enum import Enum class Equiv(str,Enum): identical = "identical" equiv = "equiv" equivCalc = "equivCalc" different = "different" class Simpler(str...
# -*- coding: utf-8 -*- """ Created on Wed May 15 15:30:41 2019 @author: jercas """ """ leetcode-14: 最长公共前缀 EASY '字符串' 编写一个函数来查找字符串数组中的最长公共前缀。 如果不存在公共前缀,返回空字符串 ""。 """ """ Thinking: 0.Python特性-字符串排序解法:Python中字符串按照ascII码排序,如sorted(['abb','aba','abac']) -> ['aba','abac','abb'] -> min:aba, max:abb; 在此基础上,只...
# SPDX-FileCopyrightText: 2017 Scott Shawcroft, written for Adafruit Industries # SPDX-FileCopyrightText: Copyright (c) 2021 John Furcean # # SPDX-License-Identifier: MIT """ `wiiclassic` ================================================================================ CircuitPython library for the Nintendo Wii Classic...
# --- # jupyter: # jupytext: # formats: ipynb,py # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.9.1+dev # kernelspec: # display_name: Python [conda env:generic_expression] * # language: python # name: conda-env-g...
#!/usr/bin/python3 ''' Script to look for new webcam images created by the motion program and email them via GMail. At the time of writing, you need to switch your Google account onto 'Allow less secure apps: ON'. Therefore it's recommended to set up a new GMail account specifically for this script so that the impa...
import hashlib def merkle(hList): if len(hList) == 1: return hList[0] newHList = [] for i in range(0, len(hList)-1, 2): newHList.append(merklehhash(hList[i],hList[i+1])) if len(hList) % 2 == 1: newHList.append(merklehhash(hList[-1],hList[-1])) return merkle(newHList) def m...