text
stringlengths
38
1.54M
from crispy_forms.helper import FormHelper from allauth.account.forms import LoginForm, ChangePasswordForm, ResetPasswordForm, ResetPasswordKeyForm class LoginForm(LoginForm): def __init__(self, *args, **kwargs): super(LoginForm, self).__init__(*args, **kwargs) self.helper = FormHelper() s...
# PATH 'C:\Users\Administrator\Desktop\energies ¶þÉó·µÐÞ\Ò»ÉóÐÞ¶© 项目生成文件位置 # OUTSTR 10 计算开始时间 # ENDT 100 计算结束时间 # US0Z0 1.5 surface velocity # MUCS 2.967057 surface velocity degree流场角度,弧度 # TIDE 0 相对海平面位置 # TP 3.83 Peak spectral period波浪周期 # HS .33 wave height波高 # GAMMA 3.33 Peakedness # ...
import random import string def gFIO(): min_char = 4 max_char = 10 allchar = string.ascii_letters return str("".join(random.choice(allchar) for x in range(random.randint(min_char,max_char)))) f = open('listec.txt','w+') for i in range(1000): s= str(gFIO())+' '+str(gFIO())+' '+str(gFIO())+','+st...
from nave import Nave from pygame import mixer class Inimigo(Nave): def __init__(self, imagem): super().__init__(imagem) self.__efeito = mixer.Sound("audios\\colisao.ogg") def destruir(self): self.__efeito.play()
import pandas as pd import argparse import logging from pathlib import Path import os from simpletransformers.classification import ClassificationModel import torch import numpy as np import re import json from scipy.special import softmax import scipy import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as...
""" iframe-eventsource transport """ from aiohttp import web, hdrs from sockjs.protocol import ENCODING from .base import StreamingTransport from .utils import CACHE_CONTROL, session_cookie class EventsourceTransport(StreamingTransport): async def send(self, text): blob = "".join(("data: ", text, "\r\n\r...
import json from bs4 import BeautifulSoup, ResultSet, element as Element import boto3 import bson s3 = boto3.resource('s3') def convetToJson(el=None, newjson={}): if type(el) == Element.Tag: newId = str(bson.objectid.ObjectId()) newjson = { '_id': newId, 'name': el.name, 'attributes': el.attrs, 'chi...
from django.contrib.auth.models import User from django.db import models # Create your models here. from django.utils.safestring import mark_safe class UserProfile(models.Model): MISSION = ( ('PAIE', 'Responsable_paiement'), ('CDE', 'Responsable_commande'), ('DEUX', 'Les_deux'), ) ...
# Copyright (c) 2013, Sebastien Mirolo # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # * Redistributions of source code must retain the above copyright notice, # this list of condition...
# # Create by Hua on 4/5/22. # """ Given a string path, where path[i] = 'N', 'S', 'E' or 'W', each representing moving one unit north, south, east, or west, respectively. You start at the origin (0, 0) on a 2D plane and walk on the path specified by path. Return true if the path crosses itself at any point, that is, ...
#!/usr/bin/env python ''' Example Usage of ISAM2 Fixed-Lag Smoother Class ''' # Author: Nick R. Rypkema (rypkema@mit.edu) # License: MIT import time import math import numpy as np import matplotlib.pyplot as plt from isam_fixed_lag_smoother import Noise1D, Noise2D, Noise3D from isam_fixed_lag_smoother import priorFa...
#!/usr/bin/env python import rospy from std_msgs.msg import String from geometry_msgs.msg import Twist from geometry_msgs.msg import Vector3 from gazebo_msgs.msg import ModelStates def Vector3subs(Vector2, Vector1): Vectorp=Vector3() Vectorp.x=Vector2.x-Vector1.x Vectorp.y=Vector2.y-Vector1.y Vectorp.z=Vector2.z-...
from setuptools import setup, find_packages setup( name='smartweb_service', version='1.0.0', description='RESTful API for the Elastos NET', url='https://github.com/cyber-republic/elastos-smartweb-service', keywords='rest restful api flask swagger openapi flask-restplus', packages=find_packag...
from django.urls import path from .views import InstrumentListView, InstrumentDetailView urlpatterns = [ path('',InstrumentListView.as_view()), path('<int:pk>/',InstrumentDetailView.as_view()), ]
#!/usr/bin/python import fileinput def frametext(s): """This function takes a string and frames it with a star border the re is 1 line of vertical space and 2 characters of horizontal space around the string. """ sl = len(s) allstarline = "*" * ( sl + 6 ) endstarline = "*" + ...
# -*- coding: utf-8 -*- # @Author: Ben # @Date: 2017-03-03 22:23:44 # @Last Modified by: Ben # @Last Modified time: 2018-05-18 22:55:27 # /Library/Frameworks/Python.framework/Versions/3.6/bin/python3.6 PATMAN.py import os import pygame from multiprocessing.connection import Client import select import time import ...
from hwt.hdlObjects.value import Value from hwt.hdlObjects.types.integer import Integer from hwt.hdlObjects.types.bits import Bits from hwt.hdlObjects.types.hdlType import HdlType from hwt.hdlObjects.operator import Operator from hwt.hdlObjects.operatorDefs import AllOps from hwt.hdlObjects.types.defs import BOOL from ...
import copy import json import tempfile import unittest import responses from zato_connection_registry.registry import Registry SINGLE_CHANNEL_DATA = { 'sec_tls_ca_cert_id': None, 'sec_type': None, 'cache_type': None, 'service_name': 'account-service.account-sync-service', 'is_internal': False, ...
#!/usr/bin/env python # -*- coding: utf-8 -*- # # Copyright 2017, Data61 # Commonwealth Scientific and Industrial Research Organisation (CSIRO) # ABN 41 687 119 230. # # This software may be distributed and modified according to the terms of # the BSD 2-Clause license. Note that NO WARRANTY is provided. # See "LICENSE...
# -*- coding: utf-8 -*- """ Created on Tue Aug 10 04:39:16 2021 @author: Prakhar Sharma """ import meshio import matplotlib.pyplot as plt import numpy as np import sklearn.metrics as metrics # for r squared from scipy.interpolate import Rbf mesh = meshio.read("circle-2d-drag_1000.vtu") cells=mesh.cells_dict pointDat...
# Generated by Django 2.0.7 on 2018-08-22 05:51 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ('members', '0004_remove_member_house_pin'), ('chit', '0002_chit'), ] operations = [ ...
#!/usr/bin/env python import os import sys SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__)) sys.path.append(os.path.dirname(SCRIPT_DIR)) def main(): from unittest import TestLoader, TestSuite from xmlrunner import XMLTestRunner import db_checks suites = [ TestLoader().loadTestsFromTe...
import redis import time import datetime redis_host = "localhost" redis_port = 6379 #HASHMAP def hello_redis(): redisClient = redis.Redis(host=redis_host, port=redis_port , db=0) #get len of set print(redisClient.scard("hello")) # NOTICE: set cannot have duplicates value hello_redis()
import re from draw import BOX_UNIT from math import floor ONE_DECIMAL_TOL = 0.5 TWO_DECIMAL_TOL = 0.15 THREE_DECIMAL_TOL = 0.05 LTCURVE_LIMIT = 400 class Dimension: def __init__(self, figure_type, page, string, label, x1, y1, x2, y2, nom, tol, copy=1): self.type = figure_type self.page_number = p...
topfile="rubberbands_all_PRO.top" outfile="dihedrals_rubberbands_all_PRO.top" nr_domains = 2 start_stop_atoms = [23, 207, 244, 425] assert len(start_stop_atoms) == 2*nr_domains with open(topfile, 'r') as f: toplines = f.readlines() def dihedrals_to_keep_domain(atom_start, atom_stop, toplines, start_line, end_lin...
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys import socket import argparse import threading clients = {} def client_serve(client): try: print 'Enter a command to execute: ' command = sys.stdin.read() client.send(command) while True: # Wait for data from ...
from flask import Blueprint,render_template, url_for, flash, redirect, request from .models import Company from extensions import db from flask import jsonify,request from flask_restful import Resource, Api from user.models import User from decorator import token_required # Get all job class Allcompany(Resource): ...
from flask import flash, Blueprint, g, redirect, render_template, request, session, url_for, jsonify, abort from checkit.db import get_db from checkit.apiUtils import * import psycopg2 as pg from checkit.db import get_db bp = Blueprint('apisession', __name__, url_prefix='/api/v1.0/sessions') session_fields = ["id","...
from hcsr04 import HCSR04 import time # GPIOs for NodeMCU ESP8266 D5 and D6 sensor = HCSR04(trigger_pin=14, echo_pin=12) while True: distance = sensor.distance_cm() print('Distance:', distance, 'cm') time.sleep(1)
from datetime import datetime import logging logger = logging.getLogger(__name__) console = logging.StreamHandler() logger.setLevel(logging.DEBUG) console.setLevel(logging.DEBUG) formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') console.setFormatter(formatter) logger.addHandler(con...
#! /usr/bin/env python3 ## # GPL license # Code based on MATE-HUD. # URL: https://bitbucket.org/ubuntu-mate/mate-hud/ # Modifications made by Dave Davenport <qball@gmpclient.org> ## import gi gi.require_version("Gtk", "3.0") from gi.repository import Gio, GLib, Gtk def rgba_to_hex(color): return "#{0:02x}{1...
import os import requests from flask import Flask, request, render_template, jsonify from flask_session import Session from sqlalchemy import create_engine from sqlalchemy.orm import scoped_session, sessionmaker from imports import main app = Flask(__name__) # Check for environment variable if not os.getenv("DATABAS...
from django import template from django.db.models import Count from django.db.models import F from news.models import Category register = template.Library() # Реализация вывода sidebar через simple_tag @register.simple_tag() def get_categories(): # Возвращаем только непустые категории (те категории, которые опу...
#replace segments of string by patterns def regex_replace_all(text, dict): for i, j in dict.items(): text = re.sub(i, j, text) return text parse_dict = {'_out':''} parse_dict2 = {'\.\w+':''} temp = regex_replace_all(line['name'], parse_dict) #pandas dataframe: drop columns df.drop(['id','desc'], axis...
import random import sf class Tile(object): # The width/height in pixels of one tile. Must be powers of 2. SIZE = 64 ID = 0 def __init__(self, xtile, ytile): # Position of the tile within the level. # may want to just pass these as parameters. self._xtile = xtile...
# Generated by Django 3.1.1 on 2020-11-30 19:24 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('ubserv', '0002_post_author'), ] operations = [ migrations.RenameField( model_name='news', old_name='userNameSub', ...
""" Test bandwidth of 915 MHz telemetry radios to explore streaming real-time data from the rocket, in-flight. """ from sys import path path.insert(0, "../../lib") from telemetry import Telemetry from time import sleep, time from argparse import ArgumentParser MESSAGE_RATE = 5 # default message interval in Hertz N...
import numpy as np import cv2 import subprocess from PIL import ImageTk import PIL.Image import Tkinter as tkinter import tkFileDialog as filedialog window = tkinter.Tk() global filename def dec2bin(num): y=[0,0,0] if(num==1): y[0]=0 y[1]=0 y[2]=1 elif(num==2): y[0]=0 ...
#label: array difficulty: easy """ 思路一: 遍历数组,判断每一个元素和它右下方元素(行数和列数均加一)是否相等,注意每一行最后一个元素以及最后一行元素无需比较(已经比较过了), 所以遍历时,行数和列数都要减1. """ class Solution: def isToeplitzMatrix(self, matrix: List[List[int]]) -> bool: for i in range(len(matrix)-1): for j in range(len(matrix[0])-1): if ma...
from collections import namedtuple from functools import lru_cache from django.conf import settings from elasticsearch import Elasticsearch RAW_INDEX = "test" if settings.TESTING else "raw" DERIVED_INDEX = "test" if settings.TESTING else "derived" @lru_cache() def connect(): "A cached reference to the connectio...
import numpy as np import scipy as sc def target_mean(ap, ext_band, inp_spectrum, inp_wvls): """ Radiance in mean wvl :param inp_spectrum: (n_realizations, n_wvls) :param inp_wvlens: (n_wvls,) :param ap: :param band: :return: """ # cut input to band support band = ap.shift_ban...
# -*- coding: utf-8 -*- # # Copyright (c) 2021, CloudBlue # All rights reserved. # from connect.client import R from reports.utils import get_basic_value, get_value def generate(client, parameters, progress_callback): query = R() if parameters.get('date') and parameters['date']['after'] != '': query...
import urllib import yaml import os from PIL import Image with open('config.yaml', 'r') as ymlfile: cfg = yaml.load(ymlfile) save_dir = os.path.join(os.getcwd(), cfg['output']['save_dir']) if not os.path.exists(save_dir): os.mkdir(save_dir) def retrieve_des_dr1_image(filename, ra, dec): filename = '{}/im...
import numpy as np import math from sfml import sf import inspect import os import signal from read_only_properties import * G = 6.67e-11 PLANET_RADIUS = 6371e3 PLANET_MASS = 5.9742e24 g_max = 9.8 k = 1.38e-21 T_max = 300 ATM_HEIGHT = 1e4 METERS_PER_PIXEL = 1e5 PLANET_COORD = (1920. / 2, 720.) AIR_MASS = 5e-26 GAME_SP...
from flask import Blueprint, render_template, request, url_for import web_app.adapters.repository as repo import web_app.home.services as services home_blueprint = Blueprint('home_bp', __name__) @home_blueprint.route('/', methods=['GET']) def home(): movies_per_page = 5 cursor = request.args.get('cursor') ...
from connect_four_game import ConnectFour def main(): ConnectFour().run() if __name__ == '__main__': main()
# -*- coding: utf-8 -*- """ Created on Sat Dec 12 21:00:34 2015 @author: Gaurav """ import math def isPrimes(number): if number == 2: return True elif number%2 == 0: return False else: for x in range(3,int(math.sqrt(number))+1,2): if number%x == 0: retur...
from django.contrib import admin from apps.users import models # Register your models here. @admin.register(models.EmailVerifyRecord) class EmailVerifyRecordAdmin(admin.ModelAdmin): # 显示的列 list_display = ['code', 'email', 'send_type', 'send_time'] # 搜索的字段,不要添加时间搜索 search_fields = ['code', 'email', 'sen...
import threading def asynchronously(callback): def _wrapped(*args, **kwargs): thread = threading.Thread(target=callback, args=args, kwargs=kwargs, daemon=True) thread.start() return {} return _wrapped
from django.contrib import admin from import_export.admin import ImportExportModelAdmin from .models import Player, Franchise, Team, \ Ballpark, Payroll, Contract, Arbitration, \ DraftPick, Trades, TradePlayer, TradePick, TradeMoney, \ AvailableDraftPick, AvailableFreeAgent, FreeAgentBid, \ HitterCardS...
from mra.helpers.util import UpdatableDict from typing import List class TaskMeta(UpdatableDict): title = UpdatableDict._variable_property('title', '') completed = UpdatableDict._variable_property('completed', False) still_running = UpdatableDict._variable_property('still_running', True) result = Upda...
from .utils import is_django_2, is_string class DatabaseSchemaEditorMixin(object): def _constraint_names(self, model, column_names=None, unique=None, primary_key=None, index=None, foreign_key=None, check=None, type_=None): """Return all constraint names ...
import sys lines = "" with open(sys.argv[1], "r") as read_file: lines = read_file.readlines() lines.replace("-", ", ") with open(sys.argv[1], "w") as write_file: write_file.write(map(lambda x: x.replace("-", ", "), lines))
#Forward kinematics #calculate the x and y coordinates of a single jointed arm given theta1, theta2, L1, and L2 from math import cos, sin, pi L1 = 2.5 #length in meters theta1 = 1.2 #angle from horizontal in radians L2 = 0.5 theta2 = 3 #angle from the line of action of the previous arm L = [0,0] #L is a vector with ...
while True: n = input("Please enter your name : ") if n.isalpha(): break else: print("Your name can't have numbers or special characters")
""" Also posted on https://stackoverflow.com/questions/57596431/python-dict-like-interface-to-glom. See there for possible comments. """ from py2store.base import KvReader from py2store.utils.glom import glom, Path # TODO: Handle names_of_literals concern better. Here affects all keys with that name (regardless of pa...
# Face detector(HOG) and draws landmark on faces detected in video feed from webcam. # https://towardsdatascience.com/facial-mapping-landmarks-with-dlib-python-160abcf7d672 # The mouth can be accessed through points [48, 68]. # The right eyebrow through points [17, 22]. # The left eyebrow through points [22, 27]. # The...
class EnergyAnalysisOpening(Element,IDisposable): """ Analytical opening. """ def Dispose(self): """ Dispose(self: Element,A_0: bool) """ pass def GetAnalyticalSurface(self): """ GetAnalyticalSurface(self: EnergyAnalysisOpening) -> EnergyAnalysisSurface Gets the associative analytical pare...
#!/usr/bin/python3 # -*- coding: utf-8 -*- import logging from library.Persistence import Persistence import requests import json def handle(text, slots, scheduler): logger = logging.getLogger('NewsModule') logger.info("... executing News module") tagesschau = Persistence.read("tagesschau") requests....
#!/usr/bin/python import sys, commands combined_energy = float(commands.getoutput('grep "Convergence criterion met" ../output.out | tail -1 ').split()[1]) iso_counter = int(commands.getoutput('grep "Convergence criterion met" output.out | wc -l ')) iso_energy_line = commands.getoutput('grep "Convergence criterion me...
#!/usr/bin/env python from TOSSIM import Tossim from random import * from TestNetworkMsg import * import sys import socket import os import time enable_main=0; if enable_main: def main(): rssi_level=sys.argv[1] return {'y0':rssi_level} rssi_level=int(main()['y0']) else: noise_offset = 7 #80 #noise_offset ...
import datetime import objc import CoreFoundation from PyObjCTools.TestSupport import TestCase, min_os_level class TestCFCalendarVariadic(TestCase): def testTypes(self): cls = None try: cls = objc.lookUpClass("NSCFCalendar") except objc.error: cls = objc.lookUpClas...
import urllib.request import urllib.parse from bs4 import BeautifulSoup baseurl = 'https://search.naver.com/search.naver?where=post&sm=tab_jum&query=' lusurl = input("검색어를 입력하세요") url = baseurl+urllib.parse.quote_plus(plusurl) html = urllib.request.urlopen(url).read() soup = BeautifulSoup(html, 'html.parser') title =...
#!/usr/bin/env python """ The Tornado server used to receive operation requests and deliver results to the user. """ import json import os, sys, psutil from sys import stderr from linguine.transaction import Transaction from concurrent.futures import ThreadPoolExecutor from linguine.transaction_exception import Transa...
#Bryan Ventura Ortiz Using Python Text print("*\n**\n***\n****") #christmas Tree print("n\*n\n**\n***\n***\n***")
#!/usr/bin/python3 """Unittest for max_integer([..]) """ import unittest max_integer = __import__('6-max_integer').max_integer class TestMaxInteger(unittest.TestCase): def test_file_doc(self): docs = __import__('6-max_integer').__doc__ self.assertTrue(len(docs) > 1) def test_func_doc(self): ...
import tensorflow as tf #定义变量 w=tf.Variable([[2.0,1.0]]) x=tf.Variable([[0.5],[1.0]]) y=tf.matmul(w,x) #生成零矩阵和全1矩阵 tf.zeros([3,4],tf.float32) tensor=[[1,2,3],[1,2,3]] tf.zeros_like(tensor,tf.float32) tf.ones([3,4],tf.float32) tf.ones_like(tensor,tf.float32) #定义常量 tensor=tf.constant([1,2,3,4,5,6]) tensor=tf.constant(...
import requests import json import os search_name = "BellingcatRaqqah" southwest_corner = "35.92865398664048,38.96073818206787" northeast_corner = "35.97895687940326,39.06510829925537" # we use the coordinates lat_min,long_min = southwest_corner.split(",") lat_max,long_max = northeast_corner.split(",") # # Func...
import numpy as np class TTT: def __init__(self, game_id, n=3, rows=3, cols=3): self.max_moves = rows * cols self.rows = rows self.cols = cols self.reset() self.length = n self.actions = rows*cols def reset(self, turn=1): self.count = 0 self.game_over = False self.turn = turn self.board = [0 fo...
# Find eularian path in a graph import unittest from graph import Graph from collections import deque class EulerianPath: def __init__(self, g): self.g = g self.done = [False]*self.g.V self.odd_degree_nodes = [] self.path = [] self.find_path() def dfs(self, v):...
import networkx as nx import matplotlib.pyplot as plt from cuckoopy import CuckooFilter as CF # 测试图,此处可以根据自己的需要生成原图 G = nx.Graph() #G.add_nodes_from([1,2,3,4,5,6,7,8]) #G.add_edges_from([(1,4),(2,4),(3,4),(4,5),(4,6),(4,7),(4,8),(5,6),(7,8)]) G.add_nodes_from([1,2,3,4,5,6,7,8,9,10]) G.add_edges_from([(1,5),(...
# -*- coding: utf-8 -*- # # Copyright 2014 Bernard Yue # # 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...
# upper, lower, title methods convert the string parameter into upper case, lower case and title case respectively. name = "jack" print(name.upper()) print(name.lower()) print(name.title())
# -*- coding: utf-8 -*- # Copyright (c) 2019, 9T9IT and contributors # For license information, please see license.txt from __future__ import unicode_literals import frappe def execute(): if not frappe.db.exists("Custom Field", "Stock Entry-os_reference_stock_transfer"): frappe.get_doc( { ...
# this is mean median file students = [] fees = [] def enrollment_status(universities): for u in universities: students.append(u[1]) fees.append(u[2]) return students,fees def mean(total_list): mean_value = 0 length_list = len(total_list) for t in total_list: ...
from datetime import datetime from decimal import Decimal from receipt_tracker.lib.qr_code import decode def test_decode(): result = decode('t=20170615T1411&s=67.20&fn=8710000100036875&i=78337&fp=255743793&n=1') assert result.fiscal_drive_number == '8710000100036875' assert result.fiscal_document_number ...
import torch from torch import Tensor def accuracy(output: Tensor, target: Tensor) -> float: with torch.no_grad(): pred = torch.argmax(output, dim=1) assert pred.shape[0] == len(target) correct = 0 correct += torch.sum(pred == target).item() return correct / len(target) def t...
# -*- coding: utf-8 -*- from __future__ import print_function import sys import os from distutils.spawn import find_executable def check_packages(): pkg_config = find_executable("pkg-config") print("Found pkg-config : {0}".format(pkg_config)) if pkg_config: from . import pkgconfig packa...
# Definition for a binary tree node. # class TreeNode: # https://www.jiuzhang.com/problem/recover-binary-search-tree/ # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def recoverTree(self, root: Optional[TreeNode...
from typing import Dict, List, Tuple, Set, Optional class F1_triplet(object): def __init__(self): self.A = 1e-10 self.B = 1e-10 self.C = 1e-10 def reset(self) -> None: self.A = 1e-10 self.B = 1e-10 self.C = 1e-10 def get_metric(self, reset: bool = False): ...
from selenium import webdriver from time import sleep driver = webdriver.Chrome() #Open the url driver.get("http://www.baidu.com") # max in windows operator driver.maximize_window() #Get Title baiduTitle = driver.title print(baiduTitle) # Get Current URL currentUrl = driver.current_url print(currentUrl) # Browser ...
# -*- coding: utf-8 -*- import pytest import ros_pytest def test_output_file_is_correctly_extracted_from_argv(): output = ros_pytest.get_output_file(['runner.py', '--gtest_output=xml:~/junit_output.xml']) assert output == '~/junit_output.xml' def test_not_passing_output_file_throws_runtime_error(): wi...
from setting import * from helper import * import torch import numpy as np import pandas as pd import plotly.offline as pyo import plotly.graph_objects as go import plotly.express as px import dash import dash_core_components as dcc import dash_html_components as html from dash.dependencies import Input, Output, Sta...
from pymongo import Connection from pymongo.errors import ConnectionFailure from bson.objectid import ObjectId from bs4 import BeautifulSoup from urlparse import urljoin import hashlib import datetime import requests import sys class Crawler: #init func def __init__(self): self.c = Connection(host='lo...
import numpy as np import matplotlib.pyplot as plt data = [[1,4],[2,8],[3,12],[4,16],[5,20]] data = np.array(data) print(data) X = data[:,0] Y = data[:,1] X = X.reshape((-1,1)) Y = Y.reshape((-1,1)) print(np.shape(X)) print(np.shape(Y)) plt.scatter(X,Y) # plt.show() theta = np.array([0.5,0.5]) theta = theta.resha...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Nov 27 09:19:33 2019 @author: MrMndFkr """ import numpy as np #from dtreeviz.trees import * #from lolviz import * from scipy.stats import mode from sklearn.metrics import accuracy_score from sklearn.metrics import r2_score import math def gini(y): ...
import hashlib import os from os.path import abspath, dirname, realpath from pathlib import Path import requests _this_dir = Path(abspath(dirname(realpath(__file__)))) _root_dir = _this_dir.parent.parent def test_specifiers_up_to_date(): original = requests.get( "https://raw.githubusercontent.com/batfis...
# Write the function fun_isfactorish(n) that takes a value int n, # and returns True if n is a (possibly-negative) integer with exactly 3 unique digits # (so no two digits are the same), where each of the digits is a factor of the number # n itself. In all other cases, the function returns False (without crashing). ...
#This code has to be added ... import pygame import time import random pygame.init() display_width = 1280 display_height = 720 black = (0,0,0) white = (255,255,255) red = (255,0,0) navy = (0,150,200) gray = (100,100,100) dark_gray = (80,80,80) gameDisplay = pygame.display.set_mode((display_width,display_heigh...
# -*- coding: utf-8 -*- # Generated by Django 1.11.6 on 2018-12-01 14:17 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('dataentry', '0074_questionlayout_form_config'), ] operations = [ migrations...
#!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright (c) 2012 Rodolphe Quiédeville <rodolphe@quiedeville.org> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of...
from logging import getLogger import numpy as np import gokart import luigi from sklearn.model_selection import train_test_split import swifter # noqa from dajare_detector.utils.base_task import DajareTask logger = getLogger(__name__) class TrainTestValSplit(DajareTask): target = gokart.TaskInstanceParameter(...
from django.contrib import admin from django.urls import path,include from .import views urlpatterns = [ path(r'', views.FronView.as_view(), name='FrontView'), path(r'<int:pk>/', views.DetailViewView.as_view(), name='DetailView'), path(r'listview/', views.ListViewView.as_view(), name='ListViewView'), p...
from effortless_config import Config class config(Config): # lowercase "c" optional SOME_INTEGER_SETTING = 10 FLOAT_SETTING = 0.5 A_BOOLEAN = False MY_STRING_SETTING = 'foo' def main(): print(f'SOME_INTEGER_SETTING is {config.SOME_INTEGER_SETTING}') print(f'FLOAT_SETTING is {config.FLOAT_S...
s = 'cAt' l = list(s) l_new = [] s_new = "" i_new = "" print l for i in l: print type(i) if i.islower() ==True: print ("Original", i) i_new = i.upper() l_new.append(i_new) print ("ToUpper", i_new) else: print ("Original", i) i_new = i.lower() l_new.append(i_new) print ("ToLower", i_new) s_new = str(l...
from collective.cart.shipping.interfaces import ICountries from zope.component import getUtility from zope.interface import directlyProvides from zope.schema.interfaces import IVocabularyFactory from zope.schema.vocabulary import SimpleTerm, SimpleVocabulary def CountryVocabularyFactory(context): items = [SimpleT...
#!/usr/bin/env python3 import sys, getopt, boto3, yaml, base64, re, time, string from os import listdir from os.path import isfile from botocore.exceptions import ClientError completed_states = [ 'CREATE_FAILED', 'CREATE_COMPLETE', 'ROLLBACK_FAILED', 'ROLLBACK_COMPLETE', 'DELETE_FAILED', 'DELETE_CO...
# -*- encoding: utf-8 -*- from flask_app import app from werkzeug.contrib.profiler import ProfilerMiddleware if __name__ == '__main__': from werkzeug.serving import run_simple app = ProfilerMiddleware( app, # profile_dir='.' ) run_simple('127.0.0.1', 5000, app, use_debugger=True)
#Lesson 51 #Merge Intervals def merge(intervals): results = [] for start, end in sorted(intervals, key=lambda x:x[0]): #print(start) if results and start <= results[-1][1]: prev_start, prev_end = results[-1] results[-1] = (prev_start, max(prev_end, end)) else: ...
''' Module to handle the motorised focuser via an Arduino ''' from tkinter import N, S, E, W, HORIZONTAL, StringVar, Tk import tkinter.ttk import tkinter.messagebox import arduino import skyx import configparser from os import path, makedirs appdatadir = path.expandvars(r'%LOCALAPPDATA%\AutoSkyX') if not path.exis...