text
stringlengths
8
6.05M
from ephemeral.build_api.lib_function import LibFunction from ephemeral.build_api.job_builder import JobBuilder class LibBuilder(object): def __init__(self): self.functions = [] self.jobs = [] def add_function(self, name, method): t = LibFunction(name, method) self.functions....
#!usr/bin/python # -*- coding: utf-8 -*- import torch import torch.nn as nn class sphere20(nn.Module): def __init__(self): super(sphere20, self).__init__() # input: batch_size, channel_num, pic_width, pic_height (B, 3, 112, 112) self.conv1_1 = nn.Conv2d(in_channels=3, out_channels=64, k...
# Python Imports import wx.lib.agw.floatspin as FS from datetime import datetime import re import time from threading import Thread # Local Imports import globals from yamaha import * from helpers import * class SmartVolumeFinished(eg.ActionBase): def __call__(self): self.plugin.smart_vol_up_start = None ...
# -*- coding: utf-8 -*- # 卷积神经网络训练mnist # 训练20000次后,再进行测试,测试精度可以达到99%。 import tensorflow as tf import tensorflow.examples.tutorials.mnist.input_data as input_data # mnist = input_data.read_data_sets("MNIST_data/", one_hot=True) def read_data(file_queue): reader = tf.TextLineReader(skip_header_lines=1) key, va...
from model_file import Model from abc import ABC, abstractmethod import datetime class Login_Controller: def __init__(self): pass def show_login_menu(self): x = True while x == True: print("""SELAMAT DATANG DI APLIKASI GERAI 1. Login (Admin) 2. Login (Cashier)""") ...
from dataclasses import dataclass, field from datetime import datetime from typing import List from rubicon_ml.domain.mixin import TagMixin from rubicon_ml.domain.utils import uuid DIRECTIONALITY_VALUES = ["score", "loss"] @dataclass class Metric(TagMixin): name: str value: float id: str = field(defaul...
import Day11 #Test Common to Q1 & Q2 def test_find_number_occupied_seats_1(): assert 6 == Day11.find_number_occupied_seats([['#', '#', '#'], ['#', '.', '.'], ['#', '.', '#']]) def test_find_number_occupied_seats_2(): assert 0 == Day11.find_number_occupied_seats([[], [], []]) #Test Specific to Q1 def test_nex...
#park sensor without buzzer import RPi.GPIO as GPIO import time trigger_pin = 23 echo_pin = 24 red_pin = 22 yellow_pin = 27 green_pin = 17 def setup(): #method to set...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ GNU AFFERO GENERAL PUBLIC LICENSE Version 3, 19 November 2007 """ import wikipedia FRENCH = "fr" ENGLISH = "en" def get_resum(word_to_search, language): """ Fonction qui renvoie le résumé du wikipedia du mot cherché :param word_to_search: Mot à cherc...
r""" Meshless Methods for Computational Mechanics (:mod:`meshless`) ============================================================== .. currentmodule:: meshless This repository has been created to organize the code developed during studies with novel meshless methods. Available modules - ES-PIM: static and linear buc...
#----------------URL and imports-------------------------- import requests #Should be install requests libary URL = 'http://localhost:8088/services/users/' #---------------REQUESTS----------------------------------- def delete_user_by_id(id): response = requests.delete(URL + str(id)) print('DELETE ...
from classifier_utils import * def write_dmc_csv(folder): dmct = pd.read_csv(os.path.join(folder, "dmct.csv"), index_col=0) dmct = dmct[dmct["DMC"] != 0] dmct = dmct.drop(columns="DMC") dmct.to_csv(os.path.join(folder, "dmct_small.csv")) if __name__ == "__main__": folders = ["../analysis/martino2015/Mvalu...
#!/usr/bin/env python3 from __future__ import print_function import sys import os import subprocess import time fullScript = os.path.abspath(sys.argv[0]) scriptName = os.path.basename(sys.argv[0]) scriptName = os.path.splitext(scriptName)[0] jarName = scriptName + '.jar' toolsFolder = os.path.dirname(fullScript) ...
import configparser import telegram import sys class TelegramWriter: def __init__(self, token, chat_id): self.token = token self.chat_id = chat_id self.bot = telegram.Bot(token=self.token) def write(self, msg): self.bot.sendMessage(chat_id=self.chat_id, text=msg) if __name__ == '__main__': ...
from ..util import file_handling as fh import html import output_labels import output_label_index import output_responses import output_response_index import output_words import output_word_index def make_masthead(active_index): names = ['Responses', 'Labels', 'Words'] targets = ['index_responses.html', 'inde...
from espeak_bot.main import main main()
# coding=utf-8 # Copyright 2016 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import (absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement) import logging impor...
import numpy as np import math import matplotlib.pyplot as plt def load_pts_features(path): """ Load interest points and SIFT features. Args: path: path to the file pts_feats.npz Returns: pts: coordinate points for two images; an array (2,) of numpy arrays (N1, 2), (N2, ...
class PropertyManager: def __init__(self, person_list): self.person_list = person_list self.keyword_list = self.get_keyword_list() def get_keyword_list(self): keyword_list = [] for person in self.person_list: for prop in person.property_list: if pr...
import unittest from katas.kyu_6.wordify import wordify class WordifyTestCase(unittest.TestCase): def test_equals(self): self.assertEqual(wordify(1), 'one') def test_equals_2(self): self.assertEqual(wordify(10), 'ten') def test_equals_3(self): self.assertEqual(wordify(12), 'twel...
P1_WINS = {'scissorspaper', 'paperrock', 'rockscissors'} def rps(p1, p2): if p1 == p2: return 'Draw!' return 'Player {} won!'.format(1 if p1 + p2 in P1_WINS else 2)
# Selection Sort # Given an array of integers, sort the elements in the array in ascending order def swap(nums, a, b): temp = nums[a] nums[a] = nums[b] nums[b] = temp return def selectSort(nums): if nums is None or len(nums) <= 1: return nums min_idx = 0 while min_idx <= len(nums)...
# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! import grpc import chat_pb2 as chat__pb2 class ChatStub(object): # missing associated documentation comment in .proto file pass def __init__(self, channel): """Constructor. Args: channel: A grpc.Channel. """ self.real...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Aug 11 23:29:27 2018 @author: ck807 """ import numpy as np import matplotlib.pyplot as plt import tensorflow as tf import keras from keras.models import Model from keras.layers.core import Dense, Lambda from keras.layers.advanced_activations import L...
import pandas as pd from sklearn.model_selection import train_test_split from sklearn.preprocessing import Imputer from sklearn.model_selection import cross_val_score from sklearn.ensemble import RandomForestRegressor def get_mae(X, y): # multiple by -1 to make positive MAE score instead of neg value returned as...
# -*- coding: utf-8 -*- from datetime import datetime from lxml import etree from optparse import OptionParser from zeit.care import add_file_logging from zeit.connector.resource import Resource import StringIO import httplib import logging import os import zeit.connector.connector logger = logging.getLogger(__name__...
import torch from argparse import ArgumentParser from unet.utils import * from unet.unet import UNet parser = ArgumentParser() parser.add_argument("--images_path", type=str, required=True) parser.add_argument("--model", type=str, required=True) parser.add_argument("--result_folder", type=str, required=True) parser.a...
import unittest from Pyskell.Language.Syntax import * from Pyskell.Language.TypeClasses import * from Pyskell.Language.EnumList import L, Enum from Pyskell.Language.Syntax.QuickLambda import __ class ADTTest(unittest.TestCase): def test_adt(self): Unit, V1, V2, V3 = data.Unit == d.V1 | d.V2 | d.V3 \ ...
# -*- coding: utf-8 -*- """ sphinx.domains.swift ~~~~~~~~~~~~~~~~~~~ The Swift domain. :copyright: Copyright 2016 by Johannes Schriewer :license: BSD, see LICENSE for details. """ import re from docutils import nodes from docutils.parsers.rst import directives from sphinx import addnodes from s...
""" Created by hzwangjian1 on 2017-08-04 """ import hashlib def test(): start = 0 end = 33 step = int(end/10) aa = [i * 10 for i in range(step)] for i in aa: print(i) for j in range(0, 368, 10): print(j) def test_split(): category = '游戏/直播' root_category = category.spl...
# Defination for a binary tree node class TreeNode(object): def __init__(self,x): self.val = x self.left = None self.right = None ######################################################## def findSecondMinimumValue(root): row = [root] minlist = [root.val,-1] while row: for...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- __version__ = '1.0.1' from web_backend.nvlserver.module import nvl_meta from sqlalchemy import BigInteger, String, Column, Boolean, Table, ForeignKey, DateTime, func console = Table( 'console', nvl_meta, Column('id', BigInteger, primary_key=True), Column...
# -*- coding: utf-8 -*- # Generated by Django 1.11.2 on 2017-10-10 14:25 from __future__ import unicode_literals from django.db import migrations, models import user_input.models class Migration(migrations.Migration): dependencies = [ ('user_input', '0019_auto_20171009_2052'), ] operations = [ ...
from aiogram import types from aiogram.dispatcher.filters import Command from keyboards.default import locations_for_button from loader import dp from utils.misc.calc_for_distance import choose_nearest @dp.message_handler(Command("show_attractions")) async def show_on_map(message: types.Message): await message.an...
""" Tests if the MPR121 touch sensor is set up correctly. See readme for set up instructions. """ from piripherals import MPR121 mpr = MPR121(bus=4, irq=0) def _onTouch(isPressed, pinNumber): pressedMessage = "pressed" if isPressed else "released" print('pin %d is %s' % (pinNumber, pressedMessage)) for i in range...
#Define a SOLVABLE sudoku board board = [ [0,0,0,0,0,0,0,0,0], [0,1,5,3,0,9,7,8,0], [0,4,0,2,0,1,0,6,0], [0,6,4,7,0,8,1,2,0], [0,0,0,0,0,0,0,0,0], [0,3,7,5,0,6,8,4,0], [0,8,0,4,0,5,0,9,0], [0,7,9,8,0,2,4,3,0], [0,0,0,0,0,0,0,0,0] ] #Sudoku solving function def sudoku_sol...
import math from unittest import TestCase import simplejson as S class TestFloat(TestCase): def test_floats(self): for num in [1617161771.7650001, math.pi, math.pi**100, math.pi**-100, 3.1]: self.assertEquals(float(S.dumps(num)), num) self.assertEquals(S.loads(S.dumps(num)), num) ...
""" 18. Plus One Question: Given a number represented as an array of digits, plus one to the number. Example Questions Candidate Might Ask: Q: Could the number be negative? A: No. Assume it is a non-negative number. Q: How are the digits ordered in the list? For example, is the number 12 represented by [1,2] or [2,1]?...
print("LETTER U HAS BEEN SUCCESSFULLY EXECUTED")
from validators import domain class Scrub(object): """ Core data handler to clean, and post results in proper DataSerialization format for SimplyDomain. Attributes: subdomain: subdomain to parse """ def __init__(self, subdomain=""): """ Init class struc. Used as a ob...
from random import randint from django.core.management.base import BaseCommand from faker import Faker from homepage.models import Student, Subject, Book class Command(BaseCommand): books = ['Zach0tka', 'za4etko', 'zachechotko', 'zaCHETKO', 'zacheton'] """ Help command that generate books for each...
import sys import numpy as np import lib1743734 as lib def create_matrix(bags, N): """ Method that creates the matrix of distances given the Jaccard similarity. :param bags: Array of bags. :param N: Size of the matrix. :return: The distance Jaccard similarity matrix J. """ D = np.ones([N, ...
from django.shortcuts import render from django.views.generic.base import TemplateView from sample1.models import Article class HomePageView(TemplateView): template_name = 'home.html' def get_context_data(self, *args, **kwargs): context = super().get_context_data(*args, **kwargs) context['lat...
str = input() vowel = ['A','E','I','O','U'] substr_list1 = [] substr_list2 = [] for i in range(1,len(str)+1): for j in range(0,len(str)-i+1): sub_str = "" ans = 0 for k in range(j,j+i): sub_str +=str[k] for q in vowel: if sub_str[0]==q: ...
# -*- coding: utf-8 -*- #Reading Oauth file from the ../auth/in_auth file from linkedin import linkedin import json credentials='../auth/In_auth'#add your authentication data f=open(credentials,'r') keys=f.readlines() f.close() #Read credentials keys CONSUMER_KEY=keys[0].strip() CONSUMER_SECRET=keys[1].strip() USER...
from tweets import * import os import unittest class Tests(unittest.TestCase): def test_not_a_file(self): self.assertRaises(AssertionError, tweets_analysis, '') self.assertRaises(AssertionError, tweets_analysis, 999) self.assertRaises(AssertionError, tweets_analysis, 'aaa') ...
# https://www.youtube.com/watch?v=uWvb3QzA48c&list=PLsk-HSGFjnaH5yghzu7PcOzm9NhsW0Urw&index=18 import pygame import random import os #CONSTANTS - GAME WIDTH = 600 HEIGHT = 300 FPS = 30 GROUND = HEIGHT - 30 SLOW = 3 FAST = 8 #CONSTANTS - PHYSICS PLAYER_ACC = 0.9 PLAYER_FRICTION = -0.12 PLAYER_GRAV = 0....
import sys from awsglue.transforms import * from awsglue.utils import getResolvedOptions from pyspark.context import SparkContext from awsglue.context import GlueContext from awsglue.job import Job ## @params: [JOB_NAME] args = getResolvedOptions(sys.argv, ['JOB_NAME']) print "*"*20 print args print "*"*20 sc = Spark...
def find(a, b): for x in a: if x == b: return a.index(x) #インデックス番号 return -1 i = input() values = eval(i) index = find(values, 100) if index == -1: print("100は一つも含まれない") else: print(f"100は{index}番目に含まれる") #
# Copyright 2016 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). from __future__ import annotations import dataclasses import logging from dataclasses import dataclass, field from enum import Enum from typing import Iterable, Mapping from pants.engine...
# # 1. 数据类型 (类型转换 .每个类型常用方法, ) # #python的数据类型有1、字符串 2、布尔类型 3、整数 4、浮点数 # # 5、 数字 6、列表 7、元组 8、字典 9、日期 # # #控制字符串循环(* 在数字中表示乘号,在字符串中表示重复多少次) # e = '我爱中国 ,'*8 # print(e) # # #拆分字符串 # for g in 'I love china': # print(g) # # #字符串---用单引号或双引号括起来 # str = 'who are you ?' # str2 = 'i am String' # print(str+' '+str2) # # #还有一...
""" hardwire.server Copyright (C) 2014 Joseph P. Crabtree Hardwire._site_init based on wsgi_echo example https://github.com/tavendo/AutobahnPython/blob/master/examples/twisted/websocket/echo_wsgi/server.py Copyright (C) 2012-2013 Tavendo GmbH This module implements the Hardwire Web Interface Server. """ ...
import discord from discord.ext import commands # Inicializaciones bot=commands.Bot(command_prefix="-") bot.remove_command("help") @bot.event async def on_ready(): await bot.change_presence(activity=discord.Game(name="¡Computación! | -help")) @bot.event async def on_command_error(ctx, error): ...
a = input() b = input() c = input() d = { 'a':a, 'b':b, 'c':c } n = 'a' while(True): if d[n] == '': break nx = d[n][0] d[n] = d[n][1:] n = nx print(n.upper())
def pattern(n): return '\n'.join(str(x) * x for x in range(2, n + 1, 2)) ''' ##Task: You have to write a function pattern which creates the following pattern upto n number of rows. If the Argument is 0 or a Negative Integer then it should return "" i.e. empty string. If any odd number is passed as...
""" The implementation of hidden markov model using tensorflow for a sequence of discrete observations. This implementation is simpler than the original version. The tutorial of the original version can be found here: https://web.stanford.edu/~jurafsky/slp3/A.pdf """ import numpy as np import tensorflow as tf from g...
# -*- coding: utf-8 -*- import os os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'my_library.settings') import django django.setup() from django.utils import timezone from books.models import Category, Book, Tag def populate(): programming_books = [ {"title": "Official Python Tutorial", "autho...
from control_panel.util import coin_data_formatter, create_timestamp from control_panel.cryptography_func import coin_data_hasher, validate_coin_data_hash, generate_random_id, generate_block_hash class BlockWeb: def __init__(self): pass class BlockChain: def __init__(self, ): pass """...
# -*- coding: utf-8 -*- # Generated by Django 1.10.4 on 2017-01-07 01:37 from __future__ import unicode_literals import django.utils.timezone from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('yyfeed', '0002_auto_20170106_1714'), ] operations = [ ...
# Copyright (c) 2009 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. { 'targets': [ { 'target_name': 'program', 'type': 'executable', 'msvs_cygwin_shell': 0, 'sources': [ 'program.c', ], ...
from reference.models import Province, District from .resources import ProvinceResource, DistrictResource from import_export.formats import base_formats from django.urls import reverse_lazy from giz.import_export_views import ImportView class ProvinceImportView(ImportView): model = Province template_name = 'da...
# This script finds the optimal classifier (PCA+KNN vs. Linear SVM) and # justifies the use of the threshold for calling an unknown cell S or R. %reset import numpy as np import pandas as pd import os import scanpy as sc import seaborn as sns from mpl_toolkits.mplot3d import Axes3D from matplotlib.pyplot import plo...
import Game from Menu.HeadMenu import HeadMenu from Menu.PlayerMenu.PlayerSelectionMenuItems import * from Vector2 import Vector2 class PlayerSelection(HeadMenu): def __init__(self, resolution, background=None, logo=None, playerMenuItems=None): super().__init__(resolution, background, logo) self...
import shutil import tempfile import unittest from persistqueue import pdict class PDictTest(unittest.TestCase): def setUp(self): self.path = tempfile.mkdtemp(suffix='pdict') def tearDown(self): shutil.rmtree(self.path, ignore_errors=True) def test_unsupported(self): pd = pdict...
import pandas as pd import statistics as st import plotly.figure_factory as ff import plotly.graph_objects as go df = pd.read_csv("StudentsPerformance.csv") data = df["reading score"].tolist() mean = st.mean(data) median = st.median(data) mode = st.mode(data) std_deviation = st.stdev(data) first_std_dev...
import dash_bootstrap_components as dbc from dash import html card = dbc.Card( [ dbc.CardImg(src="/static/images/placeholder286x180.png", top=True), dbc.CardBody( [ html.H4("Card title", className="card-title"), html.P( "Some quick exa...
#!bin/python3 def findInstanceCount(arr, element): sum = 0 for t in arr: if (t == element): sum += 1 return sum def main(): n = int(input()) arr = [] search = [] for i in range(n): arr.append(input()) q = int(input()) for i in range(q): search....
prices = { 'banana': 4, 'apple': 2, 'orange': 1.5, 'pear': 3 } stock = { 'banana': 4, 'apple': 5, 'orange': 6, 'pear': 7 } for price in prices: print(f'{price}') print(f'Price: {prices[price]}') print(f'Stock: {stock}') total = 0 for price in prices: inventory = prices[price] * stock[price] ...
# -*- coding: utf-8 -*- """ Created on Thu Sep 7 16:50:35 2017 @author: zx621293 """ #Cumulative Variance explains var= pca.explained_variance_ratio_ var1=np.cumsum(np.round(pca.explained_variance_ratio_, decimals=4)*100) fig = plt.figure(figsize=(20, 10)) plt.suptitle('Cumulative Variance contribution ...
import types import time from django.shortcuts import render_to_response, get_object_or_404 from django.http import HttpResponseRedirect, Http404 from django.core.urlresolvers import reverse from django.template import RequestContext from django.contrib.auth import authenticate, login, logout from django.db.models imp...
# this is a psuedo code for the coloring project import tensorflow as tf import numpy as np from glob import glob import math import sys import random #import the necessary packages above I think should be useful ''' To present the nueral network, I want to create an object with methods and attributes. ...
def fib(n): resultado=[] a, b = 0,1 while b<n: resultado.append(b) a, b = b, a+b return resultado print(fib(5))
import connexion from connexion.resolver import RestyResolver from flask_sqlalchemy import SQLAlchemy # Uncomment to see import-time debug logging: #import logging #logging.basicConfig(level=logging.DEBUG) api = connexion.FlaskApp(__name__, specification_dir='specs/') api.app.config['SQLALCHEMY_DATABASE_URI'] = 'sqli...
from time import sleep from serial import Serial import serial.tools.list_ports import helpers import dds_data ad9910_address = 'COM10' # addresses = [cp[0] for cp in serial.tools.list_ports.comports()] # for port in addresses: # print port # if 'COM4' in addresses: # ser = Serial('COM4', 4800, timeout=2) # se...
from django.db import models from django.conf import settings from mainapp.models import Product from datetime import timedelta #for sitemap from django.urls import reverse from django.contrib.sitemaps import ping_google class Review(models.Model): review_id = models.AutoField(primary_key=True) use...
""" author songjie """ from flask_login import current_user from tool.lib.function import get_date_time class TradeInfo(object): def __init__(self, goods): self.total = 0 self.trades = [] self.__parse(goods) def __parse(self, goods): self.total = len(goods) self.trade...
import csv import os import re from datetime import date import plotly.graph_objects as go import questionary from pytrends.request import TrendReq from tabulate import tabulate from setup import setup class Student: """ Class for Student Mode. Used as base class for `Teacher` Class """ def __...
# Copyright 2021 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 agreed to in writing, ...
import pandas as pd import gc from joblib import dump, load import numpy as np import shap import torch import torch.nn as nn import torch.nn.functional as F from sklearn import preprocessing from torch.nn.utils.weight_norm import weight_norm from train_config import * import matplotlib.pyplot as plt import numpy a...
''' Topic signature data: Each file is named according to the following pattern: measure.BNCfilt.target_word.PoS.sense.txt.bz2 for instance: tf_idf.BNCfilt.church.n.1.txt.bz2, which corresponds to the topic signature of the first sense of church built using the tf.idf measure. - Each file is compresed with bzip2 (http:...
# This file is part of beets. # Copyright 2016, Thomas Scholtes. # # Permission is hereby granted, free of charge, to any person obtaining # a copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy,...
""" File to put some utils functions """ import random import conf def to_bin(number): return list(bin(number))[2:] def to_int(binary): signal = -1 if binary[0] == '1' else 1 number = int(''.join(binary[1:]), 2) return signal*number def similarity_of_individuals(ind1, ind2): if len(ind1) != len...
""" Given an array A of integers and integer K, return the maximum S such that there exists i < j with A[i] + A[j] = S and S < K. If no i, j exist satisfying this equation, return -1. Input: A = [34,23,1,24,75,33,54,8], K = 60 Output: 58 Explanation: We can use 34 and 24 to sum 58 which is less than 60. """ class So...
# -*- coding: utf-8 -*- # import ngram sentence = "I am an NLPer" words = sentence.split(' ') for i in range(len(words)): print(''.join(words[i]) + ' ' , end ="") if(i+1 == len(words)): break else: print(''.join(words[i+1])) # print(''.join(words[3]))
from enum import Enum from itertools import permutations from collections import defaultdict class Opcodes(Enum): ADD = 1 MULTIPLY = 2 INPUT = 3 OUTPUT = 4 JTRUE = 5 JFALSE = 6 LESSTHAN = 7 EQUALS = 8 HALT = 99 with open("input1.txt","r") as f: data = f.readlines()[0].replace("\...
#!usr/bin/python def penis(): filename = raw_input("file name?: ") with open(filename) as f: for line in f: for word in line.split(): print line.replace(str(word), "penis") penis()
import heapq as h import math import random import time from collections import defaultdict, deque import numpy as np from matplotlib import pyplot as plt from occupancyGrid import OccupancyGrid from utils import raytrace class CCRA: def __init__(self, occ_grid, block_size_x, block_size_y): # Change obstacle...
from PIL import Image, ImageChops import numpy as np import os from scipy.spatial import ConvexHull from math import sqrt from skimage.feature import blob_log, blob_dog, blob_doh import rawpy path_to_images = '' faint_green_image_path = '' laser_area = 0.17 * 0.17 # m^2 def iter_through_folder_for_images(folder_pat...
import pandas as pd import numpy as np from sklearn.model_selection import train_test_split from sklearn.neural_network import MLPClassifier from sklearn import preprocessing import tensorflow.keras as keras def custom_activation(x): return 2 / keras.activations.sigmoid(x) #keras.utils.generic_utils.get_cust...
from django.contrib import admin from .models import * admin.site.register(AcademicYear) admin.site.register(Department) admin.site.register(Course) admin.site.register(Semester) admin.site.register(Teacher)
#!/usr/bin/python3.6 from __future__ import division import numpy as np import pandas as pd import sys from sklearn import svm from sklearn.ensemble import RandomForestClassifier import csv from sklearn.metrics import matthews_corrcoef from sklearn.metrics import classification_report #train_file = sys.argv[1] #train_f...
from flask import json from datamanager import * class User(): #__slots__ = ('wxid', 'name') def __init__(self, wxid='', name='', head_url=''): self.wxid = wxid self.name = name self.head_url = head_url
# imports import os import csv import locale # set locale settings to US locale.setlocale( locale.LC_ALL, 'en_US.UTF-8' ) # set csv path path = os.path.join('Financial_Records', 'budget_data_1.csv') with open(path, newline = '') as file: # create reader reader = csv.reader(file, delimiter = ',') # sets...
planed_gifts = input() list_planed_gifts = planed_gifts.split() command = input() while command != "No Money": list_command = command.split(" ") gift = list_command[1] if "OutOfStock" in command: for index, element in enumerate(list_planed_gifts): if gift in element: li...
#!/usr/bin/env python3 # -*- encoding: utf-8 -*- # File: osc4py3/tests/dispatching.py # <pep8 compliant> import sys from os.path import abspath, dirname # Make osc4py3 available. PACKAGE_PATH = dirname(dirname(dirname(abspath(__file__)))) if PACKAGE_PATH not in sys.path: sys.path.insert(0, PACKAGE_PATH) import ti...
import sys global p p = float(sys.argv[1]) class State: def __init__(self, Psum, Dsum, Naces, isTwoCards, isBlackJack, pair, turn): self.Psum = Psum self.Dsum = Dsum self.Naces = Naces self.isTwoCards = isTwoCards self.isBlackJack = isBlackJack self.pair = pair ...
from flask import Flask, request, jsonify # custom modules from helpers import get_stock_all, get_stock_one, is_valid app = Flask(__name__) @app.route("/") def index(): return jsonify("hello") @app.route("/stocks") def stocks(): try: stocks = get_stock_all() return jsonify(stocks) ex...
#!/usr/bin/python import time import sys import select print "Start loop, type 'exit' to exit" while True: print "Reading..." i,o,e = select.select([sys.stdin],[],[],0.0001) for s in i: if s == sys.stdin: input = sys.stdin.readline().strip() if (input == "exit"): ...
# -*- coding: utf-8 -*- """Tests for Time zone information files (TZif).""" import unittest from dtformats import tzif from tests import test_lib class TimeZoneInformationFileTest(test_lib.BaseTestCase): """Time zone information file (TZif) tests.""" # pylint: disable=protected-access def testDebugPrintFil...
__author__ = 'bhathiyap' class Foo(tuple): def __new__(cls, _, *args): return super(Foo, cls).__new__(cls, tuple(args)) def __init__(self, label_string, *_): self.label = label_string if __name__ == '__main__': foo = Foo("add", 2, "+", 3) print foo print foo.label