text
stringlengths
38
1.54M
#%% import pandas as pd import numpy as np import matplotlib.pyplot as plt import os # %% def normalise(values: pd.Series)-> pd.Series: '''Function that transform a series by its Min Max normalization ''' return (values - values.min())/ (values.max() - values.min()) def plot_normalised_trends(df,columns,la...
import serial import RPi.GPIO as GPIO import time ser=serial.Serial("/dev/ttyACM0",9600) start_time = time.time() imu = open("IMU.txt","w") while time.time() - start_time <= 1: ser.readline() while time.time() - start_time <= 8: read_ser=ser.readline() if float(read_ser) == 0.00: pa...
# Copyright (c) 2021, salesforce.com, inc. # All rights reserved. # SPDX-License-Identifier: BSD-3-Clause # For full license text, see the LICENSE file in the repo root # or https://opensource.org/licenses/BSD-3-Clause import bz2 import os import pickle import queue import threading import urllib.request as urllib2 i...
import requests from bs4 import BeautifulSoup import lxml import smtplib BUY_PRICE = 75.00 URL = "https://www.amazon.com/SanDisk-1TB-Extreme-Portable-SDSSDE61-1T00-G25/dp/B08GTYFC37/ref=sr_1_38?dchild=1&qid=1631216238&s=computers-intl-ship&sr=1-38" test_url = "https://www.amazon.com/Instant-Pot-Duo-Evo-Plus...
#from normalization import normalize_corpus from flask import Flask, jsonify, request from flasgger import Swagger from sklearn.externals import joblib import numpy as np from flask_cors import CORS app = Flask(__name__) Swagger(app) CORS(app) @app.route('/input/task', methods=['POST']) def predict(): """ ...
#!/VND_TSP/virtual/bin python3.6 # -*- coding: utf-8 -*- import csv import sys import json def grafo(vertices, distancias, output): distancias[0].append(vertices) with open(output, 'w') as file: for key, value in distancias.items(): file.write('%s:%s\n' % (key, value)) def Main(iteraca...
############################################################################## # This example will create a derived result for each time step asynchronously ############################################################################## import rips import time # Internal function for creating a result from a small ch...
import cv2 import numpy as np cap = cv2.VideoCapture(0) type = ".jpeg" front_dir = "faceNew\\" file = open(front_dir+"currNum.txt","r") pics = open(front_dir+"myPics.txt","a") imNum=int(file.read()) while True: _, frame = cap.read() imNum += 1 path=front_dir + "im_{}".format(imNum) + type cv2...
###OPTIMISATION OF ALGORITHMIC TRADING STRATEGIES (ATS) ## ALGO TRADING STRATEGIES ARE FIXED AND DEFINED IN PROJECT_LIB2.PY IN SIGNAL() ## EXAMPLES: MACD(50,200), RSI(14), BOLLINGER BANDS ETC # PROGRAM WILL OPTIMISE THE WEIGHTS BETWEEN STRATEGIES PER ASSET, AND THEN OPTIMIZE THE WEIGHTS BETWEEN ASSETS # Most functi...
import numpy as np import itertools import pprint import pickle import sys class State: def __init__(self,n=None,q=None,T=None): if T is None: self.n = n self.q = q self.T = np.zeros([n,q,q]) else: self.n, self.q, _ = T.shape self.T = ...
from sklearn.neighbors import KNeighborsClassifier from sklearn.model_selection import train_test_split from sklearn.metrics import accuracy_score,confusion_matrix import pandas as pd def fn(p): if p==0: return "Counterfit" else: return "Not Counter Fit" t1=pd.read_csv("data_banknote_authentication.txt") t=t1...
from __future__ import division import os import pandas as pd import numpy as np import networkx as nx from networkx.algorithms.centrality import betweenness as bt import geopandas as gp from math import radians, cos, sin, asin, sqrt from shapely.geometry import LineString, Point def prepare_centroids_li...
from django.shortcuts import render from django.http import HttpResponse import json from django.views.decorators.csrf import csrf_exempt from chatterbot import ChatBot from chatterbot.trainers import ListTrainer import os #Create a chatbot chatbot=ChatBot('jarvis') trainer = ListTrainer(chatbot) from dja...
# -*- coding: utf-8 -*- # @Time : 2020/5/13 15:04 # @Author : lxd # @File : run.py from torchvision import transforms from utils.util import image_train_test_split from utils.ImageDataset import ImageDataset from torch.utils.data import DataLoader from utils.train import train from model.CNN_model import CNN_model ...
# Euler Problem #1: Multiples of 3 and 5 # http://projecteuler.net/problem=1 # Q: Find the sum of all the multiples of 3 or 5 below 1000. # A: 233168 # Closed form solution: # Sum the arithemetic series of multiples of 3 and 5, then subtract the arithmetic series of 15 to avoid double counting # Based off formula s = ...
# -*- coding: utf-8 -*- # Generated by Django 1.11 on 2017-06-05 17:22 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('boards', '0007_auto_20170605_1713'), ('boards', '0007_auto_20170605_1539'), ] operati...
from flask import Flask,render_template,request,redirect,url_for import sys sys.path.append("c:/program files/python37/lib/site-packages") import pygal from math import cos app = Flask(__name__) import random , os ,math,re list_of_chars = ['A', 'B', 'C', 'D', 'E', '1', '2', '3', '4', '5'] #---------------------------...
import cvas import sys client = cvas.client("8bttfegqwfX5Do6rgHIF4t/5Eco7uYm8MoSrpn6p6S8=", "http://localhost:5000") with open("C:\\Users\\adamj\\OneDrive\\Study\\DP\\AlgorithmAssets\\car1.jpg", 'rb') as readFile: file = client.upload_data(readFile.read(), "image/jpeg", ".jpg") if file is None: print("Error ...
import boto3 from moto import mock_s3 from Code.ReadFile import lambda_GetFileNames sbucketName = "AIGBUCKET" sfileName = "SampleFile.txt" sBody = "AIG Sample File" def test_lambda_get_file_names(): set_up_s3() event = { "BucketName": sbucketName } result = lambda_GetFileNames(event, None) ...
# write a python program to add two numbers num1 = 1.5 num2 = 6.3 sum = num1 + num2 print(f'Sum: {sum}') # write a python program to multiply two numbers num1 = 4 num2 = 3 prod = num1 * num2 print(f'Product: {prod}') # write a python function to add two user provided numbers and return the sum def ad...
from bidict import bidict from django.conf import settings class MessageHeader: __slots__ = ['msg_type', 'version'] msg_type: str version: int def __init__(self, msg_type, version=None): self.msg_type = msg_type if version is None: self.version = settings.BOBOLITH_PROTOCO...
import tkinter as Tk import tkinter.font as tkFont from tkinter import ttk from tkinter import OptionMenu import os.path import numpy as np from lxml import etree import os from picoh import picoh from copy import deepcopy import platform import threading import csv import os import random import sys from threading imp...
from magenta.music.protobuf import music_pb2 def twinkle_twinkle(): twinkle = music_pb2.NoteSequence() twinkle.notes.add(pitch=60, start_time=0.0, end_time=0.5, velocity=80) twinkle.notes.add(pitch=60, start_time=0.5, end_time=1.0, velocity=80) twinkle.notes.add(pitch=67, start_time=1.0, end_time=1.5...
#lattice1D.py from __future__ import division,print_function """Functions for computing time evolution of wavefunctions in a moving 1D optical lattice. Units are "natural", with 1=hbar=2m, for m=mass of particle, and electrical units such that the dipole strength is 1, i.e. Rabi frequency = electric field strength. ...
# python class # class Worker # (_init_) means initialization # self means 自己,本身 or instance本身 class Worker: def __init__(self,name, pay): self.name = name #self is the new object self.pay = pay def firstName(self): return self.name.split()[0] def lastName(self): return self.name.split()[-1]#split string ...
import pandas as pd import numpy as np from sklearn import datasets from sklearn.cross_validation import train_test_split from sklearn.preprocessing import StandardScaler def ReadIris(): df = pd.read_csv('https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data', header=None) df.tail() y ...
# wapf to find fact of an integer def fact(num): f = 1 for i in range(1, num+1): f = f * i return f n = 12 r = 2 perm = fact(n) / fact(n-r) comb = fact(n) / (fact(r) * fact(n-r)) print("perm = ", perm) print("comb = ", comb) # dev karo ek baar.. call karo baar baar # DRY ==> dont repeat your...
#!/usr/bin/python3 #@Author:CaiDeyang #@Time: 2018/9/9 20:02 import logging fh = logging.FileHandler("mysql.log") ch = logging.StreamHandler() ch.setLevel(logging.INFO) fh.setLevel(logging.DEBUG) formatter = logging.Formatter('%(asctime)s - %(filename)s - %(levelname)s - %(thread)d:%(message)s') ch.setFormatter(form...
####################################################################################################################### """ # Exercise 1 Write a program which performs the following tasks: 1. Download the Movielens datasets from the url ‘http://files.grouplens.org/datasets/movielens/ml25m.zip’ 2. Download the Movielens...
from src.data_utility import download_test, process_data, vectorize_data, read_topics from text_generator import text_generator_test from keras.models import load_model import os import json import pickle import numpy as np test_path = 'test/' max_news_length = 300 #download_test(test_path) #process_data(test_path, F...
# -*- coding: utf-8 -*- # Generated by Django 1.11.9 on 2019-10-25 03:24 from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('rbac', '0001_initial'), ] operations = [ migrations.RenameField( model_...
import datetime import mock from odoo.tests import tagged, SingleTransactionCase import logging _logger = logging.getLogger(__name__) @tagged('post_install', '-at_install', 'addon_hr_customizations', 'post_holiday_events') class TestPostHolidayEvents(SingleTransactionCase): @classmethod def setUpClass(self)...
from decimal import Decimal from strawberry.utils.debug import pretty_print_graphql_operation def test_pretty_print(mocker): mock = mocker.patch("builtins.print") pretty_print_graphql_operation("Example", "{ query }", variables={}) mock.assert_called_with("{ \x1b[38;5;125mquery\x1b[39m }\n") def test...
#-*-coding:utf8-*- ''' Created on 2014-10-12 @author: Administrator ''' #-*-coding:utf8-*- import sys import datetime from xml.etree import ElementTree as ET from com.util.pro_env import PROJECT_CONF_DIR import os if __name__ == '__main__': reload(sys) today = datetime.date.today(...
import scipy import numpy import configparser from tkinter import filedialog from collections import defaultdict import pandas as pd # Builds the state sets def build_states(): state_file = filedialog.askopenfile(title="Select a State Configuration File", filetypes=(("hdf5 files", "*.ini"), ...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models from django.template.defaultfilters import slugify from django_countries.fields import CountryField from profiles.models import Profile # Create your models here. class PropertyManager(models.Manager): def get_all_availa...
# https://www.codewars.com/kata/rot13/ def rot13(s): LOWER_A = ord('a') LOWER_Z = ord('z') def rot13_char(letter): letter_n = ord(letter.lower()) letter_og = ord(letter) if letter_n >= LOWER_A and letter_n <= LOWER_Z: return ( chr(letter_og + 13) ...
""" Function implementations for standup feature """ from datetime import datetime import message as msg import source_data import threading import error import time all_channels = source_data.data["channels"] all_users = source_data.data["users"] all_messages = source_data.data["messages"] def standup_start(token...
a=[1,2,3,4,5,6] r = int(input("enter the index")) try: print(a[r]) except: print("index out of range") finally: print("inside finally")
from berserker.utils import maybe_download_unzip from pathlib import Path import tensorflow as tf import numpy as np ASSETS_PATH = str(Path(__file__).parent / 'assets') _models_path = Path(__file__).parent / 'models' from berserker.transform import batch_preprocess, batch_postprocess MAX_SEQ_LENGTH = 512 SEQ_LENGTH ...
#!/usr/bin/python2 import os import sys os.system("yum install hadoop -y") os.system("yum install jdk -y") os.system("rm -rf /data") os.system("mkdir /data") #hdfs fh=open("/etc/hadoop/hdfs-site.xml","w") x='''<?xml version="1.0"?> <?xml-stylesheet type="text/xsl" href="configuration.xsl"?> <!-- Put site-specific pro...
from trip_builder import TripBuilder from charger_context import ChargerContext from trip import Stop from routing import Osrm from trip import Coordinate from trip import RoadSegment from trip import ChargerConnection from routing import Route from ..utility import RoundUp class DistanceTripBuilder(TripBuil...
# coding=utf-8 """ ZeldaPlayer Module """ import pygame from pygame.locals import (K_UP, K_DOWN, K_LEFT, K_RIGHT, RLEACCEL) from base.abstract_sprite_manager import AbstractSpriteManager from base.settings import FileUtil class PlayerSpritesImages(AbstractSpriteManager): """ Images to sprite """ def __init_...
import math for i in range(10) : print(i) drinks = { 'martini': {'vodka', 'vermouth'}, 'black russian': {'vodka', 'kahlua'}, 'white russian': {'cream', 'kahlua', 'vodka'}, 'manhattan': {'rye', 'vermouth', 'bitters'}, 'screwdriver': {'orange juice', 'vodka'} } for n, c i...
from faker import Faker import numpy as np import os import random import scipy.stats as stats import Consts from DriverModel import IDM, TruckPlatoon from Utils import MixtureModel from Vehicle import Car, Truck, PlatoonedTruck class Garage(object): def __init__(self, seed, short_seed, car_pct, truck_pct, car_l...
from django.http import HttpResponse, JsonResponse, FileResponse # Create your views here. from rest_framework.views import APIView from api.serializers import * from api.models import * import hashlib from rest_framework.parsers import MultiPartParser import hashlib import datetime import os def getHash(f): line...
# https://www.youtube.com/watch?v=5PusmXfZBKo def soma_2_numeros(a,b): print(f"a soma dos dois numeros é: {a + b}") def soma_3_numeros(a, b, c): print(f"a soma dos tres numeros é: {a + b + c}") soma_2_numeros(41,1) soma_3_numeros(39,1,2) #### def soma(*numeros): #valores arbitrários #quem manda é o operador ...
import time from selenium import webdriver import smtplib from email.mime.text import MIMEText from email.utils import formataddr class Run(): def __init__(self): self.statue = None def check(self): option = webdriver.ChromeOptions() option.add_argument('--headless') option.ad...
import os import psycopg2 from flask import current_app from decouple import config DATABASE_URL = config("DATABASE_URL") def add_champion(name, rank, level, star, siglevel, account): with psycopg2.connect(DATABASE_URL) as conn: with conn.cursor() as cur: cur.execute(f"INSERT INTO champion (n...
from flask import Blueprint, render_template from simpledu.models import User from simpledu.models import Course user = Blueprint('user', __name__, url_prefix='/user') @user.route('/<user_name>') def index(user_name): users = User.query.filter_by(username=user_name).first_or_404() courses = Course.query.all() ...
#-------------------------------------# # Python script for BEST address # # Author: Marc Bruyland (FOD BOSA) # # Contact: marc.bruyland@bosa.fgov.be # # June 2019 # #-------------------------------------# from BEST_Lib import * print('dicS..') dicS = getDic(fDicStreets) ...
import pygame import sys from projectile import Projectile from alien import Alien def check_keydown_events(ship, projectiles, event, screen, settings): """Helper function to check for KEYDOWN events and react to them""" if event.key == pygame.K_ESCAPE: sys.exit() elif event.key == pygame.K_RIGHT...
import _thread import pycom import socket import time import machine import ubinascii import gc import ujson import os from utils import Utils as utils from network import LoRa, WLAN from machine import SD from L76GNSS import L76GNSS from pytrack import Pytrack LORA_BAT_PSU = 0 LORA_BAT_CANNOT_MEASURE = 255 # Hardwar...
from flask import Flask from flask.ext.migrate import Migrate, MigrateCommand from flask.ext.script import Manager from flask.ext.sqlalchemy import SQLAlchemy from config import Configuration # import out configuration data. app = Flask(__name__) app.config.from_object(Configuration) #use values from out Configuratio...
from ..element.validator import Validator as ElementValidator from ...elements.button import Button class Validator(ElementValidator): @staticmethod def validate(element, selector): if element.tag_name.lower() not in ['input', 'button']: return None # TODO - Verify this is desired ...
def two_sum(arr, k): for i in range(len(arr)): for j in range(i+1, len(arr)): if (arr[i] + arr[j] == k): return True return False def two_sum_one_pass(arr, k): for i in range(len(arr)): complement = k - arr[i] if complement in arr[i+1:]: retur...
def vectormachine(): from sklearn.datasets import load_iris # importing datasets from sklearn.utils import shuffle # to shuffle the datasets from sklearn.model_selection import train_test_split # to split the datasets from sklearn.svm import SVC from sklearn.metrics import classification_report...
import os import numpy as np import pandas as pd import tensorflow as tf from sklearn.neighbors import BallTree currentPath = os.path.dirname(os.path.realpath(__file__)) wordVecFile = os.path.join(currentPath, 'wordVectors.bin') keyword_matrix_2018_filename = os.path.join(currentPath, "keyword_matrix_2018.csv") che...
from typing import Optional from fidesops.schemas.masking.masking_configuration import ( StringRewriteMaskingConfiguration, MaskingConfiguration, ) from fidesops.schemas.masking.masking_strategy_description import ( MaskingStrategyDescription, MaskingStrategyConfigurationDescription, ) from fidesops.se...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ] operations = [ migrations.CreateModel( name='Chat', fields=[ ('id', models.Au...
# (c) Copyright IBM Corp. 2010, 2018. All Rights Reserved. import pkg_resources try: __version__ = pkg_resources.get_distribution(__name__).version except pkg_resources.DistributionNotFound: pass
A = [input().split() for _ in range(4)] for i in range(4): for j in range(3): if A[i][j] == A[i][j + 1]: print('CONTINUE') exit() if A[j][i] == A[j + 1][i]: print('CONTINUE') exit() print('GAMEOVER')
from openerp.osv import osv, fields from datetime import datetime, timedelta import time import logging import utils logger = logging.getLogger('sale') class sale_shop(osv.osv): _name = "sale.shop" _inherit = "sale.shop" __logger = logging.getLogger(_name) _columns = { 'instance_id' : fields....
import sys import os import unittest import math import logging from osgeo import ogr from invest_natcap.dbfpy import dbf from invest_natcap.timber import timber_core class TestTimber(unittest.TestCase): def test_timber_summationOne_NotImmedHarv(self): """Test of the first summation in the Net Present V...
from Function import Function from Potentials import GaussianFunction, TableFunction, CategoricalGaussianFunction import numpy as np from numpy.linalg import det, inv class NeuralNetFunction(Function): """ Usage: nn = NeuralNetFunction( (in, inner, RELU), (inner, out, None) ...
from django import forms from .models import * class NoticeBoardForm(forms.ModelForm): class Meta: model = NoticeBoard fields = ['message'] def clean_message(self): message = self.cleaned_data.get('message') if (message == ""): raise forms.ValidationError('Please add a message here') return message cl...
import os import re # Environment variables # DB configuration DB_PORT = os.environ.get('DB_PORT',6379) DB_HOST = os.environ.get('DB_HOST','localhost') # App config MAX_PROCESS = os.cpu_count() MAX_LINES_TO_PARSE = 500 BLOCK_SIZE = 65536 DB_INGEST_INTERVAL = 5 URL_RE = re.compile( r'^(?:http|ftp)s...
#!/usr/bin/python3 """ This script gets the commits (last 10) of a given repository. It doesn't check arguments passed to the script like number or type. You've been warned! """ import requests from sys import argv if __name__ == "__main__": url = "https://api.github.com/repos/" query = "{}/{}/commits...
import logging from collections import OrderedDict from one.alf.files import session_path_parts import warnings from ibllib.pipes.base_tasks import ExperimentDescriptionRegisterRaw from ibllib.pipes import tasks, training_status from ibllib.io import ffmpeg from ibllib.io.extractors.base import get_session_extractor_t...
from itertools import islice, product def parse_file(file): lines = iter(file) next(lines) # Discard the number of test cases T while lines: target = next(lines) food_count = int(next(lines)) foods = islice(lines, food_count) yield format_testcase(target, foods) def format...
#! /bin/python import json import os import subprocess all_traces = [] startup_bbs = [] merged_bbtrace = {} NumKeysAltered = 0 NumEmptyKeys = 0 def get_trace_files(): j_files = [] j_files_startup = [] j_files_trace = [] s = subprocess.check_output(['find', '/tmp/', '-maxdepth', '1', '-name', "rcvry_bbtrace_dump...
# -*- coding: utf-8 -*- import time import sys import RPi.GPIO as GPIO from sklearn.cluster import KMeans import pickle repeat = 150 sleep_sec = 1 exist_list = [] not_exist_list = [] def reading(): GPIO.setwarnings(False) GPIO.setmode(GPIO.BOARD) TRIG = 12 ECHO = 16 ...
from rest_framework.permissions import BasePermission class TempPermission(BasePermission): """docstring for TempPermission""" def has_permission(self,request,view): """该请求是否有对当前视图的权限""" if request.user == "管理员": return True # GenericAPIView中get_object时调用 def has_object_per...
import csv import numpy as np def loadParamter(paramterfile): parafile = file(paramterfile) reader = csv.reader(parafile) paramter = reader.next() lparamter = [0 for i in range(len(paramter)+1)] i = 0 for l in paramter: lparamter[i] = int(l) i = i+1 psum = sum(lparamter) i = 0 for p in lparamter: lparamt...
from ..node_common.queryfunc import * from models import * def setupResults(sql): q = sql2Q(sql) log.debug('Just ran sql2Q(sql); setting up QuerySets now.') transs = Transition.objects.filter(q) ntranss=transs.count() if TRANSLIM < ntranss and (not sql.requestables or 'radiative' in sql.requestable...
import os PATHS = [ "~/.brownie/packages/OpenZeppelin/openzeppelin-contracts@3.2.0/contracts/GSN/Context.sol", "~/.brownie/packages/OpenZeppelin/openzeppelin-contracts@3.2.0/contracts/math/SafeMath.sol", "~/.brownie/packages/OpenZeppelin/openzeppelin-contracts@3.2.0/contracts/token/ERC20/IERC20.sol", ...
from tornado import ioloop, web, httpserver from tornado.options import options import os, sys BASE_DIR = os.path.dirname(os.path.abspath(__file__)) sys.path.append(os.path.dirname(BASE_DIR)) print(sys.path) import django os.environ['DJANGO_SETTINGS_MODULE'] = 'MiracleOps.settings' # 设置项目的配置文件 django.setup() from...
# Generated by Django 3.1.7 on 2021-05-26 11:06 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('sampleapp', '0016_auto_20210526_0548'), ] operations = [ migrations.CreateModel( name='Size', ...
import xlsxwriter import requests from bs4 import BeautifulSoup url = 'http://digidb.io/digimon-list' html = requests.get(url) soup = BeautifulSoup(html.content, "html.parser") #TABEL table_header = soup.find_all("th") table_tbody = soup.find("tbody") table_tr = table_tbody.find_all("tr") #AMBIL HEADER list_hea...
from flask import json from nose.tools import eq_ from server import app client = app.test_client() def test_hello_world(): # When: I access root path resp = client.get('/') # Then: Expected response is returned eq_(resp.status_code, 200) eq_(resp.headers['Content-Type'], 'application/json') ...
import math class Ship: def __init__(self, x_location, y_location, x_spd, y_spd, angle): self.__angle = angle self.__x_params = [x_location, x_spd] self.__y_params = [y_location, y_spd] self.__radius = 1 def get_drawing_param(self): lst = [self.__x_params[...
import sys import os import subprocess import docker import shutil import countconvert datasetpath = "./dataset" saveFilePath = "/cve/saveresult" saveHostPath = "./result" def Select_Algo(list_algo,list_dataset): #Select Algorithm print("#Select Machinelearning Algorithms(Select 0 if you want to add an algori...
import random from ability import Ability class Weapon(Ability): def attack(self): random_value = random.randint(int(self.max_damage)//2, int(self.max_damage)) return random_value
# -*- coding: utf-8 -*- # Ecoation RawProcessor Configuration # # Created by: Farzad Khandan (farzadkhandan@ecoation.com) # from base.cloud_provider import CloudProviderFactory from base.proxy import RecordProcessorProxy from providers.aws import aws # System cloud provider CLOUD_PROVIDER_NAME = 'aws' # Cloud Provi...
# -*- coding: utf-8 -*- from PyQt5.QtCore import QObject from .model import Action class Win32PowerActionManager(QObject): def __init__(self, parent): super().__init__(parent) self.actions = [Action.Null] def act(self, action): raise NotImplementedError("Cannot do {}".format(action))...
""" ObservationInfoモジュール ObservationInfoクラスの基本定義 """ import dataclasses from datetime import datetime @dataclasses.dataclass(frozen=True) class ObservationInfo: observation_ID: str # 観測名 description: str # 観測のターゲット start_time: datetime # 観測開始時刻 end_time: datetime # 観測終了時刻 PI_name: str # PI名...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Devi editare il file di configurazione MyIPCameraBot_config.py Puoi fare riferimento al file di esempio MyIPCameraBot_config.example - You must edit the configuration file MyIPCameraBot_config.py You may refer to the sample files MyIPCameraBot_config.example """ import...
from __future__ import unicode_literals from django.db import models from django.utils.translation import ugettext_lazy as _ # -*- coding: utf-8 -*- class Branch(models.Model): class Meta(object): verbose_name = _('branch') verbose_name_plural = _('branches') app_label = 'library_branch' ...
import cv2 import numpy as np import os import time import argparse import datetime import imutils from PIL import Image ## Init Face detect vars. faceDetector = cv2.CascadeClassifier('haarcascade_frontalface_default.xml'); recognizer = cv2.face.createLBPHFaceRecognizer(); font = cv2.FONT_HERSHEY_SIMPLEX; recognizer.l...
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import numpy as np import tensorflow as tf import time if __name__ != '__main__': from config import cfg else: from easydict import EasyDict as edict cfg = edict() cfg.VOXEL_POINT_COUNT = 50 cfg.POINT_FEATURE_LEN = 6 cfg.GRID_Z_SIZE, cfg....
import sys from PyQt4.QtCore import pyqtSlot from PyQt4 import QtCore, QtGui, uic,QtTest from PyQt4.QtGui import * import subprocess from time import sleep output = subprocess.Popen('xrandr | grep "\*" | cut -d" " -f4',shell=True, stdout=subprocess.PIPE).communicate()[0] resolution = output.split()[0].split(b'x') a =...
from etk.etk import ETK from etk.knowledge_graph import KGSchema from etk.extractors.glossary_extractor import GlossaryExtractor from etk.etk_module import ETKModule from etk.wikidata import * class ExampleETKModule(ETKModule): """ Abstract class for extraction module """ def __init__(self, etk): ...
#!/usr/bin/python # *************************************************************************** # Author: Christian Wolf # christian.wolf@insa-lyon.fr # # Begin: 22.9.2019 # *************************************************************************** import glob import os import numpy as np #from skimage import io from...
import pathlib from os import getenv from logging import INFO # Logging settings LOG_LEVEL = INFO LOGGER_FORMAT = "%(asctime)s %(message)s" # Path refs ROOT = pathlib.Path(__file__).parents[1] DATA_FOLDER = ROOT.joinpath("data") LOG_FOLDER = ROOT.joinpath("log") # Crawler QUERY_RETRY_LIMIT = 3 SEMAPHORE_LIMIT = 10 ...
# fromkeys(seq, value): # crea un nuevo dic dic_1 = { 'Name': 'Pepe', 'Age': 200 } dic_2 = { 'ID': 73783287328732, 'Tel': 1532233 } sequ_1 = ('Name', 'Age', 'ID', 'Tel') #update() dic_1.update(dic_2) print(f'new dic: {str(dic_1)}') #fromkeys(sequ, VALOR) dict_fromkeys = dict.fromkeys(sequ_1, 'pepe...
import json import urllib.request import sqlite3 #pull latest data into file def pullData(): data = urllib.request.urlopen("https://frontlinehelp.api.ushahidi.io/api/v3/posts/geojson").read() serialData = json.loads(data) with open('data.json','w',encoding='utf-8') as file: json.dump(seria...
#!/usr/bin/env python # -*- coding: utf-8 -*- import json from alipay.aop.api.constant.ParamConstants import * class CarRentalMerchantInfo(object): def __init__(self): self._brand_name = None self._merchant_contact = None self._pid = None self._smid = None @property def ...
import numpy as np import tensorflow as tf import argparse import time import os import cPickle from utils import TextLoader from model import Model def main(): parser = argparse.ArgumentParser() parser.add_argument('--data_dir', type=str, default='data/scotus', help='data directory co...
# -*- coding: utf-8 -*- import os import pytest from ymir.schema import validators as v from ymir import schema from ymir import api as yapi import tests.common as test_common Invalid = v.Invalid @test_common.mock_aws def test_derived_schema(**extra_json_fields): with test_common.demo_service() as ctx: c...
import pytest from binary_search_tree.tree import Tree @pytest.fixture() def empty_tree() -> Tree(): return Tree() @pytest.fixture() def tree_with_nodes(empty_tree) -> Tree(): empty_tree.add(5, "Peter") empty_tree.add(3, "Paul") empty_tree.add(1, "Mary") empty_tree.add(10, "Karla") empty_tree...