content
stringlengths
5
1.05M
""" Support for Zwave roller shutter components. For more details about this platform, please refer to the documentation https://home-assistant.io/components/rollershutter.zwave/ """ # Because we do not compile openzwave on CI # pylint: disable=import-error import logging from homeassistant.components.rollershutter im...
import sys import os sys.path.insert(1, os.path.join(sys.path[0], '..')) import numpy as np from base.SO3 import SO3 from base.simple_filter import LowPassFilter, AverageFilter from estimation.magnetometer_calibrator import MagnetometerCalibrator from estimation.kalman_filter import KalmanFilterSO3 class Engine: ...
import matplotlib.pyplot as plt import shapefile import pandas as pd shpFilePath = r"C:\Users\tq220\Documents\Tits things\2018-2019\Data Science\Final-project-data\Data\Utah_FORGE_gravity.shp" line_dict={} df=pd.DataFrame(columns=['x','y']) test = shapefile.Reader(shpFilePath) inds=[] listx=[] listy=[] for ind,sr in...
import os import sys import shutil import asyncio from azure_functions_worker import protos from azure_functions_worker import testutils async def vertify_nested_namespace_import(): test_env = {} request = protos.FunctionEnvironmentReloadRequest( environment_variables=test_env) request_msg = pro...
# --------------------------------------------------------------- # 这个脚本向你展示了如何使用 openvino 对 PPQ 导出的模型进行推理 # 你需要注意,openvino 也可以运行各种各样的量化方案,你甚至可以用 tensorRT 的 policy # 但总的来说,openvino 需要非对称量化的 activation 和对称量化的 weights # --------------------------------------------------------------- # For this onnx inference test, all t...
import pandas as pd import numpy as np import matplotlib.pyplot as plt import argparse import torch import torch.optim as optim import torch.nn as nn from torch.autograd import Variable import os import random import pickle import esm from torch.utils.data import TensorDataset, DataLoader import emb_classifier torc...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Apr 18 11:45:16 2018 @author: nemec """ # ============================================================================= # importing all the packages import numpy as np import glob import re # ============================================================...
""" Scraping Manga from komikid.com Author: Irfan Chahyadi Source: github.com/irfanchahyadi/Scraping-Manga """ # IMPORT REQUIRED PACKAGE import os, requests, bs4 # GET LIST OF ALL CHAPTER def get_all_chapter(): res = requests.get('http://www.komikid.com/manga/one-piece') soup = bs4.BeautifulSoup(res.content,...
n = int(input()) m = int(input()) mat = [[int(j) for j in input().split()] for i in range(n)] def flood_fill(i, j): if i >= n or j >= m or i < 0 or j < 0 or mat[i][j] == 0 or mat[i][j] == -1: return 0 else: mat[i][j] = -1 return 1 + flood_fill(i-1, j-1) + flood_fill(i-1, j) + f...
from . import blocks from . import losses from . import normalization from . import regularizers
""" Launch point """ from components.button import ToggleButton from components.camera import Camera from components.microphone import Microphone button = ToggleButton() camera = Camera() mic = Microphone() def main(): try: while True: if button.is_on(): camera.start_recordi...
import time from model.contact import Contact import re from selenium.webdriver.support.ui import Select import allure class ContactHelper: def __init__(self, app): self.app = app def open_add_contact_page(self): wd = self.app.wd if not wd.current_url.endswith("/edit.php"): ...
from .http import MPXApi from .api_base import get_guid_based_id __version__ = "0.1.16" __title__ = "mpxapi"
# ==================================================================== # CODE AUTHOR: RAUL ESPINOSA # This is the code for the actual cart functionality. A small note: # I can't actually make the cart "work" until the models of the things # that are supposed to go in the cart (i.e. the books) exist and can # be importe...
# -*- coding: utf-8 -*- import urwid __author__ = 'Sumin Byeon' __version__ = '0.1.3' __all__ = ['StackedWidget'] class StackedWidget(urwid.Widget): """A widget container that presents one child widget at a time.""" #: A list containing all widgets widgets = [] #: An index of the current widget ...
#!/usr/bin/env python3 # We are given a list of numbers in a 'short-hand' range notation where only # the significant part of the next number is written because we know the # numbers are always increasing # ex. '1,3,7,2,4,1' represents [1, 3, 7, 12, 14, 21]). # # Some people use different separators for their r...
from HABApp.core.events import ValueChangeEventFilter, ValueUpdateEventFilter from . import ItemStateChangedEvent, ItemStateEvent class ItemStateEventFilter(ValueUpdateEventFilter): _EVENT_TYPE = ItemStateEvent class ItemStateChangedEventFilter(ValueChangeEventFilter): _EVENT_TYPE = ItemStateChangedEvent
#!/bin/python import math import os import random import re import sys if __name__ == '__main__': cases = int(input()) for caseNo in range(cases): s = raw_input() #reverse string rs = s[::-1] n = len(s) #take the difference of ascii values for i in range(1, n): d1 = abs(ord(s[i])...
""" Campaign tools """ import yaml import arcade from .ship import Ship from .utils import Position from .player import Player from .render import RenderEngine class Map(object): """ A single map within a campaign """ def __init__(self): pass # TODO class Campaign(object): """ A cam...
_base_ = [ '../_base_/models/universenet50.py', '../_base_/datasets/waymo_open_2d_detection_f0_mstrain_640_1280.py', '../_base_/schedules/schedule_1x.py', '../_base_/default_runtime.py' ] model = dict(bbox_head=dict(num_classes=3)) data = dict(samples_per_gpu=2) optimizer = dict(type='SGD', lr=0.001, mom...
"""Diagnostics support for Open-Meteo.""" from __future__ import annotations import json from typing import Any from open_meteo import Forecast from homeassistant.components.diagnostics import async_redact_data from homeassistant.config_entries import ConfigEntry from homeassistant.const import CONF_LATITUDE, CONF_L...
from django.contrib import admin from .models import Atracao admin.site.register(Atracao)
from .. import app from .. import queue from .. import hooks from ..models import Post from bs4 import BeautifulSoup import urllib import re import requests def register(): hooks.register('post-saved', send_webmentions) def send_webmentions(post, args): if args.get('action') in ('save_draft', 'publish_quiet...
from nose.tools import eq_ from elasticutils import S, DefaultMappingType, NoModelError, MappingType from elasticutils.tests import ElasticTestCase model_cache = [] def reset_model_cache(): del model_cache[0:] class Meta(object): def __init__(self, db_table): self.db_table = db_table class Mana...
import fractions num = 1 den = 1 count = 0 sum = 0 while den <= 12000: count = 0 min_num = int((den + 0.0) / 3 + 1) max_num = den/2 if den % 2 == 0: max_num -= 1 while min_num <= max_num: if fractions.gcd(min_num, den) == 1: count += 1 min_num += 1 sum += c...
import concurrent.futures as cf import json from datetime import datetime import math import moodle.models as models from frontend.models import Submission, GradingFile, Assignment, Course from moodle.exceptions import AccessDenied, InvalidResponse from persistence.worktree import WorkTree from util import interaction...
from marshmallow import Schema, fields, pprint from flask import Flask from flask_restplus import reqparse from flask_restplus import Resource, Api from scraper import scrape import util def analyze_func(x): return x api = Api() app = Flask(__name__) api.init_app(app) """ Serialization Schemas """ class Su...
from argparse import ArgumentParser from pathlib import Path from pfm import PotentialFieldMethod, Space DIR = Path(__file__).parent def main() -> None: parser = ArgumentParser( prog="python main.py", description="Potential field method runner" ) parser.add_argument( "--space", ...
# -*- coding: utf-8 -*- """INFO Set the package information for `mkstuff' :Author: Martin Kilbinger, <martin.kilbinger@cea.fr> :Date: 18/04/2019 """ # Release version version_info = (1, 2, 2) __version__ = '.'.join(str(c) for c in version_info) # Package details __author__ = 'Martin Kilbinger' __email__ = 'mart...
from db.models import Country, Notice, session from sqlalchemy import desc, func import datetime class Stats: def __init__(self, db_session): self.session = db_session def notice_ordered_per_country(self): all_countries = self.session.query(Country) ordered_list = all_countries.order_...
import numpy as np import matplotlib.pyplot as plt import matplotlib as mpl import matplotlib.colors as colors from scipy.integrate import cumtrapz, quad from scipy.interpolate import interp1d from scipy.stats import chi2 import PlottingTools as PT import argparse import os #--------------- # MATPLOTLIB settings m...
import matplotlib.pyplot as plt import numpy as np import json ''' This script plots multiple frame-by-frame results for PSNR and SSIM for testing video sequences. The raw results files are generated from eval_video.m using MATLAB. ''' ### Three sets of results ### # Loading result text files into JSON format path1 ...
"""Create category table. Revision ID: 0c3924deb2b7 Revises: f68e6dafb977 Create Date: 2020-04-15 17:01:38.788610 """ import sqlalchemy as sa from sqlalchemy.dialects import postgresql from modist.models.common import CategoryType from alembic import op # revision identifiers, used by Alembic. revision = "0c3924deb...
import scrapy from tobber.items import Torrent from tobber.spiders.indexer import Indexer class Rarbg(Indexer): name = "rarbg" def start_requests(self): print 'Rarbg is scrapying...' self.site = "https://rarbg.is" urls = [] search = self.site + "/torrents.php?search=" ...
#!/usr/bin/env python import os import math import numpy as np import cst.sord # FIXME: prestress not correct dx = 100.0 dt = dx / 12500.0 nx = int(16500.0 / dx + 21.5) ny = int(16500.0 / dx + 21.5) nz = int(12000.0 / dx + 120.5) nt = int(8.0 / dt + 1.5) alpha = math.sin(math.pi / 3.0) prm = { 'shape': [nx, ny...
def plug_element_count(plug): lbracket = plug.rfind("[") if lbracket != -1: rbracket = plug.rfind("]") if rbracket != -1 and lbracket < rbracket: slicestr = plug[lbracket + 1:rbracket] bounds = slicestr.split(":") if len(bounds) > 1: return int...
import json import csv import pymysql import re import os.path import cloudscraper import http.client http.client._is_legal_header_name = re.compile(rb'[^\s][^:\r\n]*').fullmatch scraper = cloudscraper.create_scraper() def main(): print("========== Starting ==========") cfg = read_config() db = pymysql...
# Generated by Django 3.0.9 on 2020-10-06 13:24 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('articles', '0003_auto_20201005_1613'), ] operations = [ migrations.AddField( model_name='article', name='image', ...
import pytest from flask import Flask from flask import jsonify from flask_jwt_extended import create_access_token from flask_jwt_extended import create_refresh_token from flask_jwt_extended import jwt_required from flask_jwt_extended import JWTManager from tests.utils import get_jwt_manager from tests.utils import ma...
import xlrd from string import lower ddr_fpga_list = ['FPGA00', 'FPGA01', 'FPGA02', 'FPGA03', 'FPGA30', 'FPGA31', 'FPGA32', 'FPGA33'] class lpfrow(object): def __init__(self, schematic, port, ball, bank): self.schematic = schematic self.port = port self.ball = ball self.bank = ban...
# -*- coding: UTF-8 -*- # Clasificador con Naive Bayes incorporado, archivos usados: stopwords.txt, clasificador.pickle, politicos-historico.txt, medios-historico.txt, politicos-historico-recuperados.json, medios-historico-recuperados.json # Argumento 1 : Lista de usuarios recuperados () # Argumento 2 : Lista de usuari...
# -*- coding: utf-8 -*- # Copyright 2020 The PsiZ Authors. All Rights Reserved. # # 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 r...
import tensorflow as tf from tensorflow import keras from tensorflow.keras import layers, Model def dped_resnet(input_shape, instance_norm = True): inputs = keras.Input(shape=input_shape) conv_0 = layers.Conv2D(64, 9, padding="same", activation=tf.nn.leaky_relu, \ kernel_initializer=tf.keras.i...
from abc import abstractclassmethod import os import datetime import typing import json from ..EnumLogLevel import EnumLogLevel class Converter_prettyJSON_to_raw(object): ################################################################################################################################ ## Cons...
# Generated by Django 2.2.1 on 2019-05-06 10:28 from django.db import migrations, models import Core.models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='ProjectModel', fields=[ ...
import mysql.connector from mysql.connector import errorcode from mysql.connector.connection import MySQLConnection class DatabaseHelper(MySQLConnection): def __init__(self, svr_ctx=None, *args, **kwargs): super(DatabaseHelper, self).__init__(*args, **kwargs) self.svr_ctx = svr_ctx def _c...
import os import torch class CheckPoint(object): def __init__(self, root, save_fn, load_fn, record_filename="checkpoint.txt", num_record=-1, clean=False): self.root = root self.save_fn = save_fn self.load_fn = load_fn self.filename = record_filename self.num_record = num_...
#!/usr/bin/env python import kubeexport import sys from setuptools import setup, find_packages from setuptools.command.test import test as TestCommand requires = ['docopt==0.6.2'] test_requires = ['pytest==3.7.1', 'pytest-cov==2.5.1'] if sys.version_info[0] < 3: test_requires.append('SystemIO>=1.1') class PyTest...
from .domain import Domain, DomainCreate, DomainInDB, DomainUpdate from .msg import Msg from .token import Token, TokenPayload from .user import User, UserCreate, UserInDB, UserUpdate from .event import EventCreate, EventCreated from .billing import StripeLink
import pytest import trio from alexandria.payloads import ( Advertise, Ack, FindNodes, FoundNodes, Locate, Locations, Ping, Pong, Retrieve, Chunk, ) @pytest.mark.trio async def test_client_send_ping(alice_and_bob_clients): alice, bob = alice_and_bob_clients async with bob.message_dispatc...
#!/usr/bin/env python # -*- coding: UTF-8 -*- # Copyright 2014 Konrad Podloucky # # 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 ...
def aumentar(n=0, tx=0, formato=False): aum = n + (n * tx / 100) if formato: return moeda(aum) else: return aum def diminuir(n=0, tx=0, formato=False): dim = n - (n * tx / 100) return dim if formato is False else moeda(dim) def metade(n=0, formato=False): met = n / 2 retu...
"""Canonical ISO date format YYYY-MM-DDTHH:mm:SS+HH:mm This parser is _extremely_ strict, and the dates that match it, though really easy to work with for the computer, are not particularly readable. See the iso_date_loose module for a slightly relaxed definition which allows the "T" character to be replaced by a " "...
import encodedecode as ed import registers as registers import execution as execution import shareddata as globl def jmpf(params): distance = [params[1], params[2], params] distance = ed.decode(distance) if globl.mode == globl.modes.bootloader: globl.bootl += distance elif globl.mode == globl.modes.rom: globl...
############################### # # Created by Patrik Valkovic # 3/9/2021 # ############################### import unittest import ffeat class NormalizedPipeTest(unittest.TestCase): def test_valid(self): n = ffeat.NormalizedPipe() param = (1,3,8), {"something": True} result = n(param) ...
import json from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status from multapp.utility.notification import SendMailNotifications class NotificationServicesRest(APIView): name = 'notification_service' ''' { "mail_list": ["m...
from torch import nn import torchvision.models as models from typeguard import typechecked @typechecked class ResNet(nn.Module): def __init__(self, encoder_name: str, pretrained: bool = False): """ :param encoder_name: :param pretrained: """ super(ResNet, self).__init__() ...
""" Base da API """ from flask import Flask, jsonify from flask_cors import CORS from sqlalchemy import create_engine import pandas as pd app = Flask(__name__) CORS(app) engine = create_engine('postgresql://equipe215:ZXF1aXBlMjE1QHNlcnBybw@bd.inova.serpro.gov.br:5432/equipe215') with engine.connect() as connectio...
import requests SMMS_URL = "https://sm.ms/api/upload" def upload_smms(path, upload_name): smfile = {'smfile': open(path, 'rb')} r = requests.post(SMMS_URL, files=smfile) result = r.json() if result['code'] == 'success': url = result['data']['url'] delete = result['data']['delete'] ...
import numpy as np import pandas as pd from patsy import dmatrices import warnings def sigmoid(x): '''SIGMOID FUNCTION FOR X''' return 1/(1+np.exp(-x)) ## Algorith settings np.random.seed(0) # set the seed tol=1e-8 # convergence tolerance lam = None # l2 - regularization max_iter = 20 # maximum allowed iter...
from typing import Callable, Dict, Optional, List import logging import torch import matplotlib as mpl from .subscriber import LoggerSubscriber def get_type(value): if isinstance(value, torch.nn.Module): return LoggerObserver.TORCH_MODULE if isinstance(value, mpl.figure.Figure): return LoggerOb...
from pathlib import Path import pytest @pytest.fixture() def html_file(): return Path(__file__).parent / "assets" / "index.html"
""" 출처: https://www.hackerrank.com/challenges/coin-change/problem """ def getWay(n, c): n_perms = [1] + [0] * n for coin in c: print("coin", coin) for i in range(coin, n + 1): print("i", i) n_perms[i] += n_perms[i - coin] return n_perms if __name__ == '__main__': ...
import random letter = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'] number = ['0','1','2','3','4','5','6','7','8','9'] symbol = ['!','@','#','$','%','...
from .process_tables import *
from pydantic import BaseModel from typing import List from app.api.schemas.pagination import PaginatedModel class GroupUserBase(BaseModel): group_id: int class GroupUserCreate(GroupUserBase): user_id: int class GroupUserAddOrRemove(BaseModel): user_id: int class GroupUser(GroupUserCreate): id:...
from fabric.api import * from fabric.contrib.files import * # Custom Code Enigma modules import common.ConfigFile import common.Services import common.Utils import common.PHP import AdjustConfiguration import Drupal import DrupalUtils # Override the shell env variable in Fabric, so that we don't see # pesky 'stdin i...
import math import torch import torch.nn as nn from torch.nn.init import _calculate_fan_in_and_fan_out, calculate_gain def MSRInitializer(Alpha=0, WeightScale=1): def Initializer(Tensor): _, fan_out = _calculate_fan_in_and_fan_out(Tensor) gain = calculate_gain('leaky_relu', Alpha) std = gai...
import music21 from mirdata.annotations import KeyData, ChordData from mirdata.datasets import haydn_op20 from tests.test_utils import run_track_tests import numpy as np def test_track(): default_trackid = "0" data_home = "tests/resources/mir_datasets/haydn_op20" dataset = haydn_op20.Dataset(data_home) ...
import json class TestQuestionnaireResourceEndpoints: def test_valid_questionnaire_submision( self, client, logged_in_user_token, setup_plans ): """ Test for questionnaira submission with valid data """ response = client.post( "/api/v1/questionnaire/process", da...
#!/usr/bin/env python import rospy import actionlib from move_base_msgs.msg import MoveBaseAction, MoveBaseGoal from sensor_msgs.msg import Joy from geometry_msgs.msg import Twist from ar_track_alvar_msgs.msg import AlvarMarkers from nav_msgs.msg import Odometry from ros_numpy import numpify from tf.transformations imp...
import matplotlib.pyplot as plt import numpy as np import seaborn as sns # Set random seed for reproducibility np.random.seed(1000) Nsamples = 10000 def X1_sample(): return np.random.normal(0.1, 2.0) def X2_sample(x1): return np.random.normal(x1, 0.5 + np.sqrt(np.abs(x1))) if __name__ == '__main__': ...
""" ## Twitter Celebrity Matcher This is a standalone script that scrapes tweets based on a given Twitter handle Author: [Ahmed Shahriar Sakib](https://www.linkedin.com/in/ahmedshahriar) Source: [Github](https://github.com/ahmedshahriar/TwitterCelebrityMatcher) """ import tweepy import pandas as pd import schedule im...
text = "Lorem ipsum dolor sit amet, calis de tabarnak d'osti de criss de sacréfils de siboire de calaille d'incompétent de calis." saveFile = open("createdFiles/Lorem ipsum 2.0.txt", "w") saveFile.write(text) saveFile.close()
#!/usr/bin/env python import os import sys from optparse import OptionParser INDENTCOUNT = 4 INDENTCHAR = ' ' parser = OptionParser() parser.add_option('-a', '--app', dest='app', help='The app which contains the model.') parser.add_option('-m', '--model', dest='model', help='The model to produce the Form for.') parse...
# -*- coding: utf-8 -*- from .fields import ImportPathField __all__ = ['ImportPathField']
# # This file is part of pysnmp software. # # Copyright (c) 2005-2018, Ilya Etingof <etingof@gmail.com> # License: http://snmplabs.com/pysnmp/license.html # # PySNMP MIB module PYSNMP-MIB (http://snmplabs.com/pysnmp) # ASN.1 source http://mibs.snmplabs.com:80/asn1/PYSNMP-MIB # Produced by pysmi-0.1.3 at Mon Apr 17 11:4...
from typing import Optional from aioros_action import ActionClient from aioros_action import create_client from aioros import NodeHandle from aioros_tf2.abc import BufferInterface from aioros_tf2.exceptions import ConnectivityException from aioros_tf2.exceptions import ExtrapolationException from aioros_tf2.exception...
import logging import numpy as np import matplotlib matplotlib.use('Agg') from matplotlib import pyplot as plt from matplotlib.patches import Rectangle logger = logging.getLogger() from activeClassifier.visualisation.base import Visualiser, visualisation_level from activeClassifier.tools.utility import softmax # ann...
import torch import torch.nn as nn from core.taming.utils import Normalize, nonlinearity class ResnetBlock(nn.Module): def __init__(self, *, in_channels, out_channels=None, conv_shortcut=False, dropout, temb_channels=512): super().__init__() self.in_channels = in_channels ...
import os import git import click import json import string import random import pickle from pathlib import Path import shutil from subprocess import STDOUT, check_call import sys def load_config(): """ Load configuration class. If not configured before create a new one and save as pickle in hom...
from facepy.exceptions import FacepyError from facepy.graph_api import GraphAPI from facepy.signed_request import SignedRequest from facepy.utils import get_application_access_token, get_extended_access_token __all__ = [ 'FacepyError', 'GraphAPI', 'SignedRequest', 'get_application_access_token', 'g...
"""Added RandomTable Revision ID: 183d3f0348eb Revises: 51f5ccfba190 Create Date: 2017-11-28 11:43:16.511000 """ # revision identifiers, used by Alembic. revision = '183d3f0348eb' down_revision = '2356a38169ea' from alembic import op import sqlalchemy as sa def upgrade(): # ### commands auto generated by Alem...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('lexicon', '0109_nexusexport__exportbeauti'), ] operations = [ migrations.AddField( model_name='language', ...
"""Atomic append of gzipped data. The point is - if several gzip streams are concatenated, they are read back as one whole stream. """ import gzip import io __all__ = ('gzip_append',) def gzip_append(filename: str, data: bytes, level: int = 6) -> None: """Append a block of data to file with safety checks.""" ...
""" Copyright (C) 2019 by The Salk Institute for Biological Studies and Pittsburgh Supercomputing Center, Carnegie Mellon University Use of this source code is governed by an MIT-style license that can be found in the LICENSE file or at https://opensource.org/licenses/MIT. """ # NOTE: usage of some a git library was ...
from collections import Counter import numpy as np VOWELS = [ord(c) for c in "AEIOU"] def duplicate_items(l): return [x for x, count in Counter(l).items() if count > 1] def duplicate_items_order(l): total = 0 for i in range(len(l) - 1): if l[i] == l[i + 1]: total += i return to...
# Copyright 2019 The FastEstimator Authors. All Rights Reserved. # # 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 appl...
from django.core.validators import MinLengthValidator from django.db import models class About(models.Model): first_name = models.CharField(max_length=100, validators=[MinLengthValidator(2)]) last_name = models.CharField(max_length=100, validators=[MinLengthValidator(2)]) place = models.CharField(max_len...
import numpy as np import nltk from nltk.tokenize import word_tokenize # using sent_tokenize won't work from nltk.corpus import stopwords from nltk.stem import PorterStemmer def preprocess(file_name): file = open(file_name,"r") if file.mode == 'r': content = file.read() sentences = content.split...
from __future__ import unicode_literals import os import fcntl import select import signal import errno from codecs import getincrementaldecoder from ..terminal.vt100_input import InputStream from .base import BaseEventLoop __all__ = ( 'PosixEventLoop', 'call_on_sigwinch', ) class PosixEventLoop(BaseEventL...
from machine import ADC , Pin from Blocky.Pin import getPin class WaterSensor : def __init__ (self , port , sensitivity = 4): if (getPin(port)[2] == None): from machine import reset reset() self.adc = ADC(getPin[2]) if (sensitivity == 1) self.adc.atten(ADC.ATTN0_DB) elif (sensitivity == 2) self.adc.atte...
import pandas as pd import numpy as np import scipy import scipy.stats as stats import pylab import sklearn.feature_selection as sk from sklearn.linear_model import LogisticRegression, LinearRegression from sklearn.ensemble import RandomForestClassifier from sklearn.ensemble import BaggingClassifier from sklearn.multi...
from marshmallow import Schema, validate, validates_schema, ValidationError from marshmallow.fields import String from app.users.documents import User BaseUserSchema = User.schema.as_marshmallow_schema() class CreateUserSchema(BaseUserSchema): id = String( dump_only=True, description='Unique do...
import numpy as np import pandas as pd import matplotlib.pyplot as plt import math #plt.scatter(x,y,alpha=0.3) #df.drop(df.columns[[0, 2]], axis='columns') def borrar(data): for iterable in range(99,data.shape[0]): data.drop([iterable], inplace=True) class regresion_logistica(): def __init__(self)...
# -*- coding: utf-8 -*- start_time = "2018-06-01 00:00:00" end_time = "2018-07-01 00:00:00" contributors_id = ()
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Common utility functions Created on Sun May 27 16:37:42 2018 @author: chen """ import math import cv2 import os from imutils import paths import numpy as np import scipy.ndimage def rotate_cooridinate(cooridinate_og,rotate_angle,rotate_center): """ calculat...
# CRISP-DM Python template, main #import logging import load #import Model.svm.model as svmimport imp import cDataPreparation.dataCleaning.cleaningFunctions as clean import cDataPreparation.dataConstruction.constructFunctions as construct from sklearn.datasets import fetch_20newsgroups #import DataPreparation.integra...
from .core import Field from .core import FieldDescriptor from .core import FieldGroup from .core import SimpleField from .core.enums import ValueStatus, FieldKind, IsbnType, PublicationType class IsbnField(Field): def __init__(self, document, name): super(IsbnField, self...
from django.contrib.auth import models import factory from faker import Faker fake = Faker() class UserFactory(factory.django.DjangoModelFactory): username = fake.user_name() email = fake.email() first_name = fake.first_name() last_name = fake.last_name() class Meta: model = models.Use...