content
stringlengths
5
1.05M
from django.db.models.base import Model from django.db.models.deletion import CASCADE from django.db.models.fields import BooleanField from django.db.models.fields.related import ForeignKey from django.utils.translation import ugettext_lazy as _ from django.db import models from django.utils import timezone from numpy ...
# https://pymotw.com/3/socket/udp.html#echo-server # socket_echo_server_dgram.py import socket import sys # Create a UDP socket sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # Bind the socket to the port server_address = ('localhost', 10000) print('starting up on {} port {}'.format(*server_address)) sock.b...
# Copyright 2020 - 2021 MONAI Consortium # 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 wri...
# -*- coding: utf-8 -*- """ Azure Functions Queue Trigger Python Sample - Get RSS feed URL from Queue and dump all items that obtained from RSS feed """ import os import sys sys.path.append("site-packages") import feedparser # Read the queue message rss_feed_url = open(os.environ['inputMessage']).read() print "Pyt...
print('-=' * 20) print('CADASTRE UMA PESSOA') print('-=' * 20) c_idade = 0 c_homem = 0 c_mulher = 0 c_mulher_20 =0 while True: idade = int(input('Idade: ')) sexo = str(input('Sexo [M/F]: ')).strip().upper() print('Quer continuar ? [S/N]') opcao = str(input('>>> ')).strip().upper() # if opcao == 'S...
import time def profile(epsilon1, epsilon2, epsilon3, x): y = -1 epsilon4 = epsilon3 + (epsilon2 - epsilon1) if epsilon1 <= x < epsilon2: y = (x - epsilon1) / (epsilon2 - epsilon1) elif epsilon2 <= x <= epsilon3: y = 1 elif epsilon3 < x <= epsilon4: y = (epsilon4 - x) / (ep...
# Copyright (C) 2020, 2021 Satoru SATOH <satoru.satoh@gmail.com> # SPDX-License-Identifier: MIT # # pylint: disable=invalid-name """Common utility classes for test cases. """ import pathlib import typing import unittest from . import base class RuleTestCase(unittest.TestCase): """Base class to test rules. ""...
# -*- coding: utf-8 -*- """ Lacework Agent Access Tokens API wrapper. """ import logging logger = logging.getLogger(__name__) class AgentAccessTokensAPI(object): """ Lacework Agent Access Tokens API. """ def __init__(self, session): """ Initializes the AgentAccessTokensAPI object. ...
""" Background Image ================ This is the Background Image Class used to generate a back ground image like a bias image acquired by the SPARC4 cameras. """ import sys import numpy as np from astropy.table import Table from photutils.datasets import make_noise_image class Background_Image: """Background...
from marshmallow import Schema, fields from .fields import Fields class TaskSchema(Schema): id = fields.String(dump_only=True) user = fields.Nested('UserSchema', only=Fields.User.compact) growthbook = fields.Nested('GrowthbookSchema', only=Fields.Growthbook.compact) scheduling = fields.Nested('Schedu...
import tensorflow as tf import numpy as np import os import workIds as wi import prepWorks as pw ##Variables #File location of the loaded text converted to absolute path prepWork = os.path.abspath(pw.textOut) #Train model variables training = False numGenerate = 2000 epochs = 25 startString = 'The ' #Training consta...
#!/usr/bin/env python3 # Stdlib import pathlib import unittest # 3rd party import numpy as np # Our own imports from deep_hipsc_tracking.utils import image_utils from .. import helpers # Tests class TestFixContrast(unittest.TestCase): def test_fixes_flat_image(self): img = np.zeros((64, 64)) ...
import nep import time node = nep.node("surveyor_test") resp = node.new_respondent('surveyor_sample'); i=0 while True: x = {"node":"sucess"} s, msg = resp.listen_json(block_mode=False) if s: i = i + 1 if i%2 == 0: print i resp.send_json(x)
from pywebpush import webpush, WebPushException import json from flask import current_app def trigger_push_notification(push_subscription, title, body): try: response = webpush( subscription_info=json.loads(push_subscription.subscription_json), data=json.dumps({"title": title, "bod...
FLOATING_POINT_ACCURACY = 3 ENCODING = "utf-8"
from model.states_map import StateMap class Policy: def __init__(self, state_actions_map): """ :param state_actions_map: is dictionary where key is the state and the value is list of best possible actions """ self.__state_action_map = state_actions_map def get_actions_map(sel...
import socket clientSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) serverAddr = input("Server address: ") port = int(input("port number: ")) filename = input("file name: ") clientSocket.connect((serverAddr, port)) filename = "/"+filename request = b'GET %s HTTP/1.1\r\nHost: %s:%s\r\n'%(filename.enc...
#!/usr/bin/env python3 import copy import curses import curses.ascii from enum import Enum import locale import math import sys import signal class Direction(Enum): north, east, south, west = range(4) def is_opp(self, other): return ((self == Direction.north and other == Direction.south) or ...
# -*- coding:utf-8 -*- # Author: hankcs # Date: 2020-05-08 16:34 from hanlp_common.structure import SerializableDict from elit.datasets.glue import STANFORD_SENTIMENT_TREEBANK_2_TRAIN, MICROSOFT_RESEARCH_PARAPHRASE_CORPUS_DEV from elit.transform.table import TableTransform class StanfordSentimentTreebank2Transorm(Tab...
# # PySNMP MIB module EATON-PDU-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/EATON-PDU-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 18:44:29 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 201...
from unittest import TestCase from CombinationSum import CombinationSum class TestCombinationSum(TestCase): def test_combinationSum(self): cs = CombinationSum() list0 = cs.combinationSum([2, 3, 6, 7], 7) self.assertTrue(len(list0) == 2) self.assertTrue(list0.__contains__([7])) ...
# Copyright 2012 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. from telemetry.internal.app import possible_app class PossibleBrowser(possible_app.PossibleApp): """A browser that can be controlled. Call Create() to...
#! /usr/bin/python """ Phase recovery from two meausured intensity distributions using Gerchberg Saxton. .. :copyright: (c) 2017 by Fred van Goor. :license: MIT, see License for more details. """ import matplotlib.pyplot as plt import numpy as np import LightPipes from LightPipes import cm, m, mm, nm, um #P...
import dill import matplotlib.pyplot as plt from scipy.stats import gaussian_kde import numpy as np for target in ["low", "high"]: # Load saved stuff if target == "low": s1, s2, m1, m2 = dill.load(open("saved/example_tcl_sim_low.p", "r")) else: s1, s2, m1, m2 = dill.load(open("saved/examp...
import os import sys import time import shutil import traceback import os.path import argh import carcade from carcade import server from carcade.conf import settings from carcade.i18n import extract_translations from carcade.environments import create_jinja2_env from carcade.core import build as _build from carcade....
""" Test applying a Stratification to a CompartmentalModel via stratify_with updates compartments correctly. """ import numpy as np from numpy.testing import assert_allclose, assert_array_equal from summer import Compartment, CompartmentalModel, Stratification def test_stratify__single__validate_compartments(): ...
# Python - 3.6.0 Test.assert_equals(total_goals, 58, 'total goals should equal to 58')
import datetime import uuid from datetime import timezone from app.main import db from app.main.model.channel import Channel norilsk_time = timezone(datetime.timedelta(0, 25200), 'Asia/Krasnoyarsk') def add_channel(data): channel = None if data.get('public_id'): channel = Channel.query.filter_by(pub...
''' Created on Oct 18, 2015 @author: nyga ''' import base64 import datetime import mimetypes import os from _pyio import BytesIO from colorsys import hsv_to_rgb, rgb_to_hsv import xml.etree.ElementTree as ET from xml.dom import minidom from PIL import Image as PILImage from dnutils import Condition, ifnone from pyr...
import sys sys.path.append('/usr/local/lib') import pyrealsense2 as rs import numpy as np import cv2 import operator import math import time from statistics import mean class Viewer: """Class for the Realsense Viewer""" def __init__(self): """Contructor Function.""" ## PyRealsense Object Ini...
from .swaggerdoc import Preprocessor
from turterra import app_callbacks, app_layout from turterra.utils.compound_utility import Compound __all__ = ["app_callbacks", "app_layout", "Compound"]
PLAYLIST_ID = """3865036 15163713 44227904 47190423 48428043 55489311 60530487 63097780 74104913 117286958 156934569 312734124 401702326 427495738 436692330 473759386 481244653 491658341 533896713 547236299 549579429 551095546 598105571 613527455 614159955 637947405 749564716 924680166 984196486 1992428073 2075961982 2...
import unittest import json from pathlib import Path import pandas as pd import lusid from lusidtools import logger from lusidtools.cocoon.cocoon import load_from_data_frame from lusidtools.cocoon.cocoon_printer import format_portfolios_response from lusidfeature import lusid_feature class CocoonPrinterIntegrationTes...
"""thairod URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/2.2/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based...
from PolynomialMultiType import Atom #from NumberTheory.Rationals import Rational def atom_tests(): print("Begin Atom Tests") a = Atom("a") b = Atom("b") val = [a,-a,a**3,a*a,a*b,1-a,a-1,a+a] cor = ["a","-a","a^3","a^2","ab","-a + 1","a - 1","2a"] ctr = 0 for test_val,correct_val in zip(...
""" *One-Down-Half* A half note on the downbeat of one. """ from dataclasses import dataclass __all__ = ["OneDownHalf"] @dataclass class OneDownHalf( OneDown, HalfNote, ): pass
''' O programa pede um número qualquer e, logo após isso, imprime o valor na tela! ''' valor = float(input("Digite um valor numérico: ")); print("O numero digitado foi : {}".format(valor));
# -*- coding:utf-8 -*- import numpy as np import random import matplotlib.pyplot as plt class Arm: def __init__(self, id, real_p): self.id = id self.real_p = real_p self.estimate_p = 0.0 self.n = 0 self.gba = 0.0 def get_used_count(self): retur...
#!/usr/bin/env python import execo import execo_g5k import argparse parser = argparse.ArgumentParser( description='Run the spawn-node/volunteer test on Grid5000') parser.add_argument( 'volunteers', metavar='N', type=int, help='number of volunteer nodes to use (8 cores per node)'...
# Generated by Django 2.2 on 2021-10-20 22:02 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('researchhub_document', '0025_auto_20211007_0017'), ] operations = [ migrations.RemoveField( model_name='researchhubunifieddocument', ...
a = 'パタトクカシーー' print(a[0] + a[2] + a[4] + a[6])
##!/usr/bin/env python import argparse import requests from oauth2client.service_account import ServiceAccountCredentials from firecloud import api as fapi def main(args): # set up scopes and credentials scopes = ['https://www.googleapis.com/auth/userinfo.profile', 'https://www.googleapis.com/auth/userinfo....
from fastapi import FastAPI from routes import login, logout, register, get_user from core.events import startup_connection, shutdown_connection app = FastAPI() app.add_event_handler('startup', startup_connection) app.add_event_handler('shutdown', shutdown_connection) app.include_router(get_user.router, prefix='/a...
from .driver import MacrobaseDriver
"""empty message Revision ID: 8b3f167d0418 Revises: Create Date: 2017-05-11 12:03:37.001446 """ from alembic import op import sqlalchemy as sa from sqlalchemy.dialects import postgresql # revision identifiers, used by Alembic. revision = "8b3f167d0418" down_revision = None branch_labels = None depends_on = None de...
import json import os import subprocess import shutil import pytest from ramp_engine.local import CondaEnvWorker def _is_conda_env_installed(): # we required a "ramp-iris" conda environment to run the test. Check if it # is available. Otherwise skip all tests. try: proc = subprocess.Popen( ...
from django.contrib import admin from stew.models import * admin.site.register(Work) admin.site.register(Stewdent) admin.site.register(Skill)
import models import yaml import torch import torch.nn as nn import torch.nn.functional as F import torchvision import matplotlib.pyplot as plt import numpy as np def set_seed(seed): torch.manual_seed(seed) torch.backends.cudnn.deterministic = True torch.backends.cudnn.benchmark = False np.random.seed...
""" Django settings for resources project. Generated by 'django-admin startproject' using Django 3.0.7. For more information on this file, see https://docs.djangoproject.com/en/3.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.0/ref/settings/ """ import os ...
def reverse(sentence): answer = '' temp = '' for char in sentence: if char != ' ': temp += char else: answer = temp + ' ' + answer temp = '' answer = temp + ' ' + answer print(answer) sentence = 'This is a string to try' reverse(sentence)
# -*- coding: utf-8 -*- """ Created on 2017-4-28 @author: cheng.li """ import unittest import numpy as np import pandas as pd from alphamind.settlement.simplesettle import simple_settle class TestSimpleSettle(unittest.TestCase): def setUp(self): self.n_samples = 3000 self.n...
# -*- coding: utf-8 -*- """ Pymongo ORM Base Example: User(Collection): # Collection name in mongodb _ORM_collection_name = 'user' uid = Field(time.time, is_unique=True) name = Field() age = Field(18) created = Field(datetime.utcnow) user = User(name='Bob') # Create a user with default age 18...
from PyQt5 import QtWidgets, uic import os def get_dir(): return str(os.path.abspath(os.path.dirname(__file__))) def load_keys_file(window): result = QtWidgets.QFileDialog.getOpenFileName(window) filepath = result[0] if filepath != '': window.keys_file = filepath def gui_main(): ...
#!/usr/bin/env python3 # -*- encoding=utf8 -*- # Author : Mohammed Ouassou # Date : October 11, 2018 # Organization : NMA, Geodetic Institute prolog = """ **PROGRAM** klobuchar_model.py **PURPOSE** compute the ionospheric time-delay correction for the single-frequency by broadcast m...
from rest_framework import serializers from ..models import Attribute class AttributeSerializer(serializers.ModelSerializer): parent = serializers.HyperlinkedRelatedField(view_name='api-v1-domain:attribute-detail', read_only=True) children = serializers.SerializerMethodField() class Meta: model...
from django.db import models from django.db.models import Q from django.urls import reverse from django.utils.safestring import mark_safe from django_extensions.db.models import TimeStampedModel def capitalize_phrase(string): phrase = "" for word in string.split(): phrase = f"{phrase} {word[0].upper()...
""" Contains APIService class """ from typing import Optional from avionix.kube.base_objects import ApiRegistration from avionix.kube.meta import ObjectMeta from avionix.yaml.yaml_handling import HelmYaml class ServiceReference(HelmYaml): """ :param name: Name is the name of the service :param namespace...
lista = [] while True: n = lista.append(int(input('Digite um número: '))) o = str(input('Deseja continuar? [S/N]: ')).upper()[0] if o not in 'SN': o = str(input('Deseja continuar? [S/N]: ')).upper()[0] if o == 'N': break print(f'A lista é {lista}') print(f'Você digitou {len(lista)} númer...
from collections import OrderedDict from flask import render_template from app import current_service, service_api_client from app.main import main from app.models.spreadsheet import Spreadsheet from app.utils.user import user_has_permissions @main.route("/services/<uuid:service_id>/returned-letters") @user_has_per...
from sqlalchemy import Column, String, Enum from sqlalchemy.ext.associationproxy import association_proxy from sqlalchemy.orm import relationship from .base import Base class Repository(Base): uuid = Column(String(36), primary_key=True) name = Column(String(256), unique=True, nullable=False) raw_storage_t...
""" To check if peak of DANO map is due to model bias or not. Pass output mtz file of phenix.refine to this script. And then run FFT. Can you still see peak of anomalous scatterers? """ import sys import iotbx.mtz from cctbx.array_family import flex import numpy def get_cc(a1, a2, title): a1, a2 = a1.common_sets...
# -*- coding: utf-8 -*- # ********************************** # Author: Lizi # Contact: alisonbrielee@gmail.com # ********************************** import torch.nn as nn from layers import * class MPRNet(nn.Module): def __init__(self): super(MPRNet, self).__init__() dim = 3 ...
from collections import defaultdict from django.db.models import Sum from ..models import Media from ..search import TatorSearch from ..schema import MediaStatsSchema from ._base_views import BaseDetailView from ._media_query import get_media_es_query from ._permissions import ProjectViewOnlyPermission class MediaS...
from manimlib.imports import * class WhatDoesItReallyMean(TeacherStudentsScene): CONFIG = { "default_pi_creature_kwargs": { "color": MAROON_E, "flip_at_start": True, }, } def construct(self): student_q = TextMobject("What does", "``probability''\\\\", ...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.contrib import admin from .models import City # Register your models here. @admin.register(City) class CityAdmin(admin.ModelAdmin): list_display=('name','created','updated',)
#!/usr/bin/python # coding=utf-8 # # Unit test of the suffix summary module including hyperloglog import sys import suffixes import nameparse import compare_file_test import traceback import time import os # Test of the summarization of detail result files. # # The following tests are expected to work: # # py .\suffi...
from django.contrib.auth.models import User from django_rest_urltoken_auth.models import URLToken from rest_framework import authentication from rest_framework import exceptions class URLTokenAuthentication(authentication.BaseAuthentication): def authenticate(self, request): if not "token" in reque...
pkgname = "bsdutils" _commit="d7050267fbc655a8b1a01bae58f23b304e0daf32" pkgver = "0.0.1" pkgrel = 0 build_style = "meson" hostmakedepends = ["flex", "byacc", "meson", "pkgconf"] makedepends = [ "acl-devel", "ncurses-devel", "libedit-devel", "openssl-devel", "musl-fts-devel", "musl-rpmatch-devel", "libxo-devel" ...
class ValidWordAbbr(object): def __init__(self, dictionary): """ :type dictionary: List[str] """ self.word_map = {} for word in dictionary: abbr = self.abbreviate(word) if abbr in self.word_map: self.word_map[abbr].add(word) ...
from flask import jsonify, Blueprint from caringapp.core import errors from caringapp.endpoints.error.schemas import ERROR_SCHEMA blueprint = Blueprint('errors', __name__) @blueprint.app_errorhandler(errors.HttpError) def handle_error(error): return jsonify(ERROR_SCHEMA.dump(error).data), error.status_code @bl...
# Число инверсий # Про инверсии: https://ru.stackoverflow.com/questions/375825/%D0%A0%D0%B0%D0%B7%D0%B4%D0%B5%D0%BB%D1%8F%D0%B9-%D0%B8-%D0%B2%D0%BB%D0%B0%D1%81%D1%82%D0%B2%D1%83%D0%B9-%D0%BF%D0%BE%D0%B4%D1%81%D1%87%D0%B5%D1%82-%D0%BA%D0%BE%D0%BB%D0%B8%D1%87%D0%B5%D1%81%D1%82%D0%B2%D0%B0-%D0%B8%D0%BD%D0%B2%D0%B5%D1%80%D...
from django.conf.urls import url from .views import NotifySofortView urlpatterns = [ url(r'^notify/$', NotifySofortView.as_view(), name='notifiy'), ]
from keras.models import Sequential from keras.layers import Convolution2D from keras.layers import MaxPooling2D from keras.layers import Flatten from keras.layers import Dense classifier = Sequential() classifier.add(Convolution2D(32, 3, 3, input_shape = (64, 64, 3), activation = 'relu')) classifier.add(Max...
#!/usr/bin/env python # -*- coding: utf-8 -*- import requests r = requests.get('http://cuiqingcai.com') print type(r) # http 状态码 print r.status_code # 页面编码 print r.encoding # 页面响应 -- 内容较多,占时隐藏掉 # print r.text # cookies的信息 print r.cookies
# -*- coding: utf-8 -*- # Copyright 2020 Google 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...
import sys import json jsonFN = sys.argv[1] jsonPath = sys.argv[2] with open(jsonFN, 'r') as inputFile: jsonFile = json.load(inputFile) inputFile.close() print(jsonFile[jsonPath])
from ...error import GraphQLError from .base import ValidationRule class UniqueVariableNames(ValidationRule): __slots__ = 'known_variable_names', def __init__(self, context): super(UniqueVariableNames, self).__init__(context) self.known_variable_names = {} def enter_OperationDefinition(s...
#!/usr/bin/env python2.5 # # Copyright 2009 the Melange authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applic...
# -*- coding: utf-8 -*- import logging import functools from django.contrib.gis.db import models from django.conf import settings from django.utils.translation import ugettext_lazy as _ from django.contrib.gis.geos import fromstr, LineString from mapentity.models import MapEntityMixin from geotrek.authent.models imp...
"""mpc controller""" from Controllers.template_controller import template_controller from CartPole.cartpole_model import TrackHalfLength, s0, Q2u, cartpole_ode from others.p_globals import v_max from CartPole.state_utilities import create_cartpole_state, \ ANGLE_IDX, ANGLED_IDX, POSITION_IDX, POSITIOND_IDX import...
# Generated by the protocol buffer compiler. DO NOT EDIT! # source: RpcSub.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 as _reflec...
import socketserver from http.server import HTTPServer, BaseHTTPRequestHandler from typing import Tuple, Callable class Server(HTTPServer): def __init__(self, server_address: Tuple[str, int], RequestHandlerClass: Callable[..., BaseHTTPRequestHandler]): super().__init__(server_address, RequestHandlerClass...
#!/usr/bin/env python # coding: utf-8 # # Crossentropy method # # This notebook will teach you to solve reinforcement learning problems with crossentropy method. We'll follow-up by scaling everything up and using neural network policy. # In[1]: import sys, os if 'google.colab' in sys.modules and not os.path.exists...
# coding: utf-8 """ CLOUD API IONOS Enterprise-grade Infrastructure as a Service (IaaS) solutions can be managed through the Cloud API, in addition or as an alternative to the \"Data Center Designer\" (DCD) browser-based tool. Both methods employ consistent concepts and features, deliver similar power and ...
from .._qt.qt_main_window import Window from .._qt.qt_viewer import QtViewer from .._qt.qt_viewer_buttons import QtNDisplayButton, QtViewerButtons from .threading import create_worker, thread_worker __all__ = ( 'create_worker', 'QtNDisplayButton', 'QtViewer', 'QtViewerButtons', 'thread_worker', ...
# -*- coding: utf-8 -*- from numpy import array, double def fread(filename): '''This function read data from Irtac .dat files''' fp = open(filename, 'r') fstr = fp.readline() #read first row while not fstr.strip() == 'Series: IAC': fstr = fp.readline() fstr = fp.readline() #read title datay = [] fstr =...
""" Created on Thursday May 14nd, 2019 This script explores the ratio of ethane to methane, as well as acetylene to methane. It plots the ratio along all of the years where the data is present, and then performs harmonic fitting on the plots. """ def ratioCalc(): import numpy as np from fileInput import f...
import datetime def handle_response(root): """ :param root: Root element of XML payload. :return: XML payload for Openpay API. """ final_response = {} for value in root: if value.text is not None: final_response[value.tag] = value.text return final_response def check_...
#!/usr/bin/env python def get_map(func, start, end): map_ = dict() for i in range(start, end+1): p = func(i) div_, mod_ = divmod(p, 100) if mod_ < 10: continue if mod_ in map_: map_[mod_].append(div_) else: map_[mod_] = [div_] retu...
## Count token with their number of occurances in positive and negative ## tweets to help identify non-discriminatory stop words specific for the given ## data. import os # Must import before sklearn or else ImportError. from comet_ml import Experiment import pandas as pd from operator import itemgetter # Custom fun...
import numpy as np import matplotlib.pyplot as plt y = 1 z = np.arange(0.005, 0.995, .005) gini = 2*z*(1-z) entropy = -z*np.log2(z)-(1-z)*np.log2(1-z) fig = plt.figure() ax = fig.add_subplot(111) ax.plot(z, gini, label='gini') ax.plot(z, entropy, label='entropy') ax.set_ylim([0,1]) ax.set_xlim([0,1]) ax.set_xlabel('p...
# coding: utf-8 import datetime from sqlalchemy import Column, Numeric, String, Integer, Boolean, DateTime, Time, ForeignKey, MetaData from geoalchemy2 import Geometry from sqlalchemy.orm import relationship from sqlalchemy.ext.declarative import declarative_base Base = declarative_base(MetaData(schema="wawamgr")) m...
# Untitled - By: Cameron - Mon Jan 14 2019 import sensor, image, pyb, os, time, math, mjpeg from pyb import LED blue_led = LED(3) TRIGGER_THRESHOLD = 5 BG_UPDATE_FRAMES = 1 # How many frames before blending. thresholds=[69,255] knownHeight = 150.5 #focal_mm = 2.8 #image_width_in_pixels=160 #sensor_width_mm=3.9...
# -*- coding: utf-8 -*- # Generated by Django 1.10 on 2016-08-24 06:19 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('web', '0024_auto_20160821_1451'), ] operations = [ migrations.CreateModel( ...
import os import unittest from os.path import ( abspath, dirname, join, ) from hammett import main, g class SuitesTests(unittest.TestCase): def test_suites(self): base = dirname(dirname(abspath(__file__))) suites_base = abspath(join(base, 'tests', 'suites')) for d in os.listdi...
from datetime import datetime from pylsner.plugin import Metric class Plugin(Metric): def __init__(self, unit='seconds', refresh_rate=1, **kwargs): super().__init__(unit, refresh_rate) self._set_value = getattr(self, '_set_{}'.format(unit)) self._min = 0 if self.unit in ['secon...
# -*- coding: utf-8 -*- from setuptools import setup, find_packages with open('README.md', 'r') as fh: long_description = fh.read() packages = [p for p in find_packages() if "third_party" not in p] print(packages) setup( name='pose_format', packages=packages, version='0.0.3', description='Library for view...
#!/usr/bin/env python3 import hashlib inp = "cxdnnyjw" pass_vals = [None] * 8 charsfound = 0 index = 0 m = hashlib.md5() m.update((inp + str(index)).encode()) hexdigest = m.hexdigest() while charsfound != 8: m = hashlib.md5() m.update((inp + str(index)).encode()) hexdigest = m.hexdigest() if hex...
class Message(object): def __init__(self, first_name, last_name): self._first_name = first_name self._last_name = last_name @property def message(self): return f'Hello-World! Nice to meet you {self._first_name} {self._last_name}!'