text stringlengths 38 1.54M |
|---|
from setuptools import setup, find_packages
setup(
name='panoptescli',
version='1.1.3',
url='https://github.com/zooniverse/panoptes-cli',
author='Adam McMaster',
author_email='adam@zooniverse.org',
description=(
'A command-line client for Panoptes, the API behind the Zooniverse'
),
... |
def get_answer(question):
return {
"привет": "И тебе привет!",
"как дела": "Лучше всех", "пока": "Увидимся"
}.get(question, 'я не знаю')
print(get_answer(input()))
|
import sys
import re
import os
# YOU WILL NEED TO RUN 'pip install bitstring' if you don't have the module installed already
from bitstring import Bits
registers32b = {
'R0': '{0:05b}'.format(0),
'R1': '{0:05b}'.format(1),
'R2': '{0:05b}'.format(2),
'R3': '{0:05b}'.format(3),
'R4': '{0:05b}'.format(4),
'R5': '{0... |
print("""
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bo... |
import cherrypy
import json
from sensor import Sensor
class websensor(object):
exposed = True
def __init__(self):
self.sens = Sensor()
def GET (self, *uri, ** params):
if len(uri) == 1:
actions = ["get_temperature_info", "get_humidity_info", "toggle_relay_status", "get_relay_status"]
if uri[0] in action... |
import random
import sqlite3
def enregistrement(voc):
fichier = open("data.txt", "w")
for i in voc:
fichier.write(' '.join(i))
fichier.close()
def quizz():
# list to avoid redundancy in Quizz (2 times the same word)
mdf = []
fichier = open("data.txt", "r")
voc = [i.split(" ")... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Jun 22 00:14:03 2021
@author: salih
"""
import numpy as np
import os
from matplotlib import pyplot as plt
while(os.getcwd().split('/')[-1] != 'star'):
os.chdir("../")
from Calibration.Missions.Mission_8.iterative_packager import map_img_2_img
... |
from zope.viewlet.interfaces import IViewletManager
from plone.app.viewletmanager.manager import OrderedViewletManager
class IHeaderLeft(IViewletManager):
"""a viewlet manager that sits on the header left"""
class IHeaderRight(IViewletManager):
"""a viewlet manager that sits on the header right"""
class I... |
from mgear.maya.synoptic.tabs import MainSynopticTab
from . import widget
##################################################
# SYNOPTIC TAB WIDGET
##################################################
class SynopticTab(MainSynopticTab, widget.Ui_biped_body):
description = "biped body"
name = "biped_body"
... |
import classifyTime as ct
import datetime
import analysis
def computeNow():
# startOfCurrentDay = datetime.datetime.now().replace(hour=8, minute=0, second=0, microsecond=0)
# currentTimePlus = startOfCurrentDay
currentTimePlus = datetime.datetime.now()
data = ct.classifyTime(currentTimePlus, 'random... |
def process_ls(output):
lis = output.split('\n')
newList = []
cp = lis.copy()
for l in cp:
if l[0] != 'd':
newList.append(l.split()[4:])
newList.sort(key=lambda x: x[4])
newList.sort(key=lambda x: int(x[0]), reverse=True)
return [' '.join(el[4:]) for el in newList]
|
def dirige(nome):
print(f'O {nome} pode dirigir')
def carona(nome):
print(f'O {nome} so pode ir de carona')
nome = 'Maykon'
idade = 17
if idade >=18:
dirige(nome)
else:
carona(nome) |
min = int(input("min:"))
max = int(input("max:"))
sushu = []
for i in range(min,max+1):
fg = 0
for j in range(2,i):
if (i % j) == 0:
fg = 1
break
if (fg == 0):
sushu.append(i)
print(sushu)
|
import tensorflow as tf
from tensorflow.keras.layers import Input, Dense, Flatten
from tensorflow.keras.models import Model
from tensorflow.keras import losses
from sklearn.model_selection import train_test_split
class AutoEnconder(object):
def __init__(self, epochs=10, batch_size=32, validation_size=0.2,
... |
import team_solver.utils.subproc
from team_solver.interfaces.interfaces import SolverResult, ISolver, SolverException
class IParser:
def parse(self, out, err):
""" Return: parse_error, is_sat, assignment, stats_data (of StatsData type) """
raise NotImplementedError()
class ProcessSolver(ISolver)... |
# vim: tabstop=8 expandtab shiftwidth=4 softtabstop=4
def recursion(input_li, level):
if level == 0:
return []
output = []
for i in range(len(input_li)-level+1):
rec = recursion(input_li[i+1:], level-1)
c = input_li[i]
if rec == []:
output.append([c])
... |
"""gallium
Frontend-tool for Gallium3D architecture.
"""
#
# Copyright 2008 Tungsten Graphics, Inc., Cedar Park, Texas.
# All Rights Reserved.
#
# 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 Soft... |
from django.utils import unittest
from django.test import TestCase
from django.test import Client
class SimpleTest(unittest.TestCase):
fixtures = ['test_data.json']
def setUp(self):
self.client = Client()
def test_basic_addition(self):
"""
Tests that 1 + 1 always equals 2.
... |
# 5桁の数 16807 = 75は自然数を5乗した数である.
# 同様に9桁の数 134217728 = 89も自然数を9乗した数である.
# 自然数を n 乗して得られる n 桁の正整数は何個あるか?
BORDER = 1000
ans = 0
for num in range(1, 10):
for n in range(1, BORDER):
result = num ** n
# 累乗の結果がn桁よりも大きい場合はそれ以降判定しなくてよい
if(len(str(result)) > n):
break
elif(len... |
###############################################################################
# linkFiles.py
#
# Last update: 6/18/2020 by Isaac Arseneau
#
# Description: Links the necessary files to recreate the wrf runs
# along with the traj files generated on that day
#############################################################... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright 2013 Jingyi Xiao
#
# Encoding: UTF-8
# Author: Jingyi Xiao <kxwarning@126.com>
# Created time: $2015-3-19 21:04:03$
# Note: This source file is NOT a freeware
# Version: Order.py 0.1 jingyi Exp $
__author__="jingyi"
__date__ ="$2015-3-19 21:04:03$"
import os, sys... |
#!/usr/bin/env python
import sys
import os
from djangoconfig import setup_environment
try:
setup_environment(__file__)
except KeyboardInterrupt:
print ""
print "Exiting script."
sys.exit(0)
import settings
from django.core import management
if __name__ == "__main__":
management.execute_manager(s... |
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.pyplot import figure
#target function
def f(X,Y):
return np.cos((X + 6*(0.35*Y))) + 2*(0.35*X*Y)
#10 values from -1 to 1
trX = np.linspace(-1,1,10)
trY = np.linspace(-1,1,10)
trainX, trainY = np.meshgrid(trX, trY) #10 x 1... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"a test hello modle"
__author__="honeybee"
import sys
def test():
args = sys.argv
if len(args) == 1:
print("hello world")
elif len(args) == 2:
print("fuck you, %s!" % args[1])
else:
print("ass ♂ we can ~~")
if __name__ == '__main__':
test() |
import os
from flask import Flask, request, render_template
import sys
sys.path.append("src")
from lime_explainer import explainer, tokenizer, METHODS
import time
app = Flask(__name__)
SECRET_KEY = os.urandom(24)
@app.route('/')
@app.route('/result', methods=['POST'])
def index():
exp = ""
if request.method ==... |
import multiprocessing as mp
from jitcache import Cache
import time
cache = Cache()
@cache.memoize
def slow_fn(input_1, input_2):
print("Slow Function Called")
time.sleep(1)
return input_1 * input_2
def test_process():
kwarg_dict = {"input_1": 10, "input_2": 4}
n_processes = 10
process_l... |
# -*- coding: utf-8 -*-
import datetime as dt
import os
import sys
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
sys.path.inser... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('status', '0004_auto_20150619_1600'),
]
operations = [
migrations.AddField(
model_name='status',
name... |
from NA_Domain.NA_BaseClass import NA_Base
from datetime import datetime
class C_Goods(NA_Base):
def __init__(self,BrandName='',PricePerunit=0,DeprMethod='SL',Unit='Pcs',EconomicLife=5,Placement='Gudang IT1',InActive=0):
NA_Base.__init__()
self.brandName = BrandName
self.pricePerUnit = PricePerunit
self.depr... |
import numpy as np
import pandas as pd
from PIL import Image
import coreglib #from https://github.com/dshean/demcoreg/tree/master/demcoreg
import matplotlib.pyplot as plt
from scipy import stats
'''
Coregister two DEMs using the approach defined by Nuuth and Kääb, 2011.
Do iteratively.
'''
# define current ul and lr c... |
# ###
# Another solution for importing from parent directory:
#
# import sys
# from pathlib import Path # if you haven't already done so
# file = Path(__file__).resolve()
# parent, root = file.parent, file.parents[1]
# sys.path.append(str(root))
#
# # Additionally remove the current file's directory from sys.path
# try... |
import requests
AIRFLOW_URL = "192.168.99.100:30212"
DAG_ID = "Test_Kubernetes_Operator"
docker_image_name = "saivarunr/testpython:test-1"
def initiate_pod(container_name):
r = requests.get(
'http://{AIRFLOW_URL}/admin/rest_api/api/trigger_dag?dag_id={DAG_ID}&run_id=vers7&conf={"docker_image_name": "{CON... |
import time
from selenium.webdriver.support.select import Select
from selenium import webdriver
from selenium.webdriver.common.by import By
class SeleniumDriver():
def getChromeDriver(self):
chrome_driver = webdriver.Chrome(executable_path='C:\\Users\\91897\\workspace_python\\sel_drivers\\chromedriver.ex... |
#! /usr/bin/env python
# -*- coding:utf-8 -*-
__author__ = 'huky'
import sys
digits = set()
def is_slept():
for i in range(10):
if i not in digits:
return False
return True
def get_digits(n):
t = n
d = set()
while t > 0:
d.add(t % 10)
t /= 10
return d
de... |
# -*- coding: utf-8 -*-
import scrapy,re
from scrapydemo.items import Book
class DangdangimgSpider(scrapy.Spider):
name = 'dangdangimg'
allowed_domains = ['http://search.dangdang.com/']
start_urls = ['http://search.dangdang.com/?key=python&act=input']
def parse(self, response):
bookitems = re... |
# -*- coding: utf-8 -*-
b = input(u'Input number: ')
c = input(u'Input number: ')
def square(b, c):
s = c*b
print "Rectangle's square = %.d" % (s)
square(b, c) |
# coding: utf-8
"""Collection of value learning algorithms."""
import abc
import copy
from typing import Optional, Callable, Union, Generic
import attr
import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils.data import DataLoader
from ignite.engine import Events
import irl.utils as utils
fr... |
import picamera
import time
camera = picamera.PiCamera()
#camera.capture('image.jpg')
camera.start_recording("video.h264")
time.sleep(10)
camera.stop_recording()
|
# -*- coding: utf-8 -*-
# Copyright European Organization for Nuclear Research (CERN) since 2012
#
# 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-... |
# -*- coding: utf-8 -*-
"""
Created on Mon Mar 19 07:27:27 2018
@author: am21381
"""
# Classification template
# Importing the libraries
import os
print(os.getcwd())
os.chdir('C:/Vadivel/Analytics/Deep learning/Deeplearning-files-training-Citi')
print(os.getcwd())
import numpy as np
import matplotlib.... |
'''
Read in 10 numbers from the user. Place all 10 numbers into an list in the order they were received.
Print out the second number received, followed by the 4th, then the 6th, then the 8th, then the 10th.
Then print out the 9th, 7th, 5th, 3rd, and 1st.
Example input: 1,2,3,4,5,6,7,8,9,10
Example output: 2,4,6,8,10,... |
#!/usr/bin/env python
"""
If run as a script, crawls the directory tree provided as an argument, and imports all .nxml files in that directory into a Mongo collection.
If imported, provides classes for importing a .nxml file into a Mongo collection.
"""
import os
import pymongo
def mongo_document_from_nxml(file_pat... |
# input
n = int(input())
v = list(map(int, input().split()))
# special case
if len(set(v)) == 1:
print(len(v) // 2)
exit()
d_odds = {}
d_even = {}
for i in range(0, len(v), 2):
if v[i] in d_even:
d_even[v[i]] += 1
else:
d_even[v[i]] = 1
for i in range(1, len(v), 2):
if v[i] i... |
#
# IS-IS transformation module
#
from box import Box
from . import _Module
class EIGRP(_Module):
def node_post_transform(self, node: Box, topology: Box) -> None:
self.set_af_flag(node,node.eigrp)
|
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# Code by: SkyHigh
# Bachelor Thesis written at Gjovik University College
# http://hovedprosjekter.hig.no/v2012/imt/in/skyhighadm/
#
# This sourcecode has been written as an extension of the Horizon module
# in the OpenStack project and is greatly inspired by this.
# http://... |
N, M = 3, 5
pizzas = [7, 2, 6, 5, 3]
oven = []
cnt = 0
for _ in range(N):
oven.append(pizzas.pop(0))
cnt += N
# print(oven)
# print(pizzas)
while pizzas:
for i in range(N):
print(oven)
oven[i] = oven[i]//2
if oven[i] == 0:
if pizzas:
oven[i] = pizzas.pop(0)... |
import re, itertools, hashlib, sys, datetime, time
alphabet = ['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','@','_','#','0','1','2','3','4','5','6','7','8',... |
from __future__ import unicode_literals
from django.conf import settings
from django.utils.html import format_html
def meta_tags(
objects=(),
*,
request,
url_keys=('canonical', 'image', 'url'),
**kwargs):
"""
Return a dictionary containing meta tag information: Keys in... |
import sublime
import sublime_plugin
_ST3 = sublime.version() >= '3000'
if _ST3:
from .getTeXRoot import get_tex_root
from .latextools_utils import analysis, get_setting, quickpanel
else:
from getTeXRoot import get_tex_root
from latextools_utils import analysis, get_setting, quickpanel
def _make_cap... |
################################################################################
# Cristian Alexandrescu #
# 2163013577ba2bc237f22b3f4d006856 #
# 11a4bb2c77aca6a9927b85f259d9af10db791ce5cf884bb31e7f7a889d4fb385 ... |
import os
import face_detect
import face_capturing
import face_update
import face_recogntion
# Title bar
def title_bar():
os.system('cls')
print("\t**********************************************")
print("\t***** Face Recognition Attendance System *****")
print("\t************************... |
from django.test import TestCase
from viridis.models import Test, Question, Choice
class TestListViewTestCase(TestCase):
def test_quiz_index(self):
resp = self.client.get('/')
self.assertEqual(resp.status_code, 200)
def test_add_quiz(self):
resp = self.client.get('/test/new')
s... |
# -*- coding: utf-8 -*-
# Copyright (C) 2011-2016 Martin Glueck All rights reserved
# Langstrasse 4, A--2244 Spannberg, Austria. martin@mangari.org
# #*** <License> ************************************************************#
# This module is part of the package GTW.__test__.
#
# This module is licensed under the term... |
from __future__ import annotations
from collections import defaultdict
from typing import TYPE_CHECKING, Dict, List, NamedTuple, Optional, Set, Tuple
import numpy as np
import tcod
from location import Location
if TYPE_CHECKING:
from actor import Actor
from graphic import Graphic
from items import Item
... |
# Generated by Django 2.1.1 on 2021-01-02 23:09
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('sistema', '0007_auto_20210102_1706'),
]
operations = [
migrations.AlterField(
model_name='curso',
name='id_curso',
... |
# -*- coding: utf-8 -*-
"""
Created on Sat Aug 30 13:07:19 2014
@author: Evan
Goal: Take in a vector Y and a matrix X, calculate the regression
coefficients. Assume there is an intercept calculated as well.
Note: For My_Test_01-My_Test_05, I created the vector of ones for the intercept
in this program. Now I assum... |
################6.1 IS A LIST SORTED IN ASCENDING ORDER?##################
##########################################################################
# def issorted(arr):
# if(len(arr)<=1):
# return True
# else:
# return issorted(arr[:len(arr)//2]) and arr[len(arr)//2-1] <= arr[len(arr)//2] and ... |
import hashlib
#initializing string
print ('='*100)
str = "SHA1 Clear text"
result = hashlib.sha3_256(str.encode())
# printing the equivalent hexadecimal value.
print("The hexadecimal equivalent of SHA1 digest is : ")
print(result.hexdigest())
print ('='*100 )
|
"""
简单排序很简单,它的大致处理流程为:
从待排序序列中,找到关键字最小的元素;
如果最小元素不是待排序序列的第一个元素,将其和第一个元素互换;
从余下的 N - 1 个元素中,找出关键字最小的元素,重复(1)、(2)步,直到排序结束。
"""
def xuzesort(intput_list):
if len(intput_list)<=1:
return intput_list
for i in range(len(intput_list)-1):
print("这是第%d趟" % (i+1))
# minnum... |
from Ref import ref
import os
import json
from DataBase import DataBase
import sqlite3
DATABASE_MAIN_DIRECTORY = r"db/"
def readJson(file):
with open(file) as jsonFile:
data = json.load(jsonFile)
return data
def getDB():
conn = sqlite3.connect('database.db')
conn.execute('CREATE TABLE I... |
import xlrd
import numpy as np
def read_data():
names = ["AI experiments/id3/train_data", "AI experiments/id3/test_data"]
data = []
for i in [0, 1]:
fname = names[i] + ".xlsx"
bk = xlrd.open_workbook(fname)
shxrange = range(bk.nsheets)
try:
sh = bk.sheet_by_name... |
from django.urls import path
from .views import IllnessListView,IllnessDetailView,IllnessSearchDetailView,DrugListView,DrugDetailView,DrugSearchDetailView,PostReplyDetailView,PostListView,PostDetailView,ReplyListView,ReplyDetailView,UserPostsView
from rest_framework.urlpatterns import format_suffix_patterns
urlpatte... |
from torch import nn
from types_ import *
from typing import List
import torch
from itertools import chain
from masked_linear import MaskedLinear
# def zero_grad(self, grad_input, grad_output):
# return grad_input * self.mask
#
# class MaskedLinear(nn.Module):
# def __init__(self, in_features, out_features, nu... |
import datetime
import sys
def get_utc_datetime():
""" Get the current UTC time """
return datetime.datetime.utcnow().replace(tzinfo=datetime.timezone.utc)
def to_utc_datetime(date: datetime.datetime):
""" Sets a datetime's timezone to UTC """
if date.tzinfo is None:
# If there is no timezon... |
from django.conf.urls import url
from django.urls import path
from personnel import views
urlpatterns = [
url(r'^$', views.index, name='index'),
path('employee/', views.employee, name='employee'),
path(
'employee/add_employee/',
views.add_employee,
name='add-employee'
),
p... |
"""
Routes and views for the flask application.
"""
from datetime import datetime
from flask import render_template
from FlaskWebProject import app
from flask_restful import reqparse, abort, Api, Resource
from api import *
from sql import *
@app.after_request
def after_request(response):
get_db().commit()
... |
from models.announcement_manage_model import AnnouncementManageModel
from models.banner_manage_model import BannerManageModel
from models.mine_comments_model import MineCommentsModel
from services.account_service import AccountService
from services.base_service import BaseService
from utils.util import get_offset_by_pa... |
#!/bin/python3
import sys
def convert_2binary_maxlen(n):
max_len = 0
len=0
while( n > 0 ):
temp = n%2
#print(temp)
if(temp == 1):
#print(n)
len = len + 1
if(len > max_len):
max_len = len
#print("current_max_len",m... |
import string
import numpy as np
def ascii_to_string(ascii_array):
tmp_string = ''
for char in ascii_array:
if char != 0:
tmp_string += chr(char)
else:
break
return tmp_string
def string_to_ascii(string, solid_len = np.nan):
num_list = map(ord, list(string))
num_list.append(0)
if not np.isnan(solid_le... |
velocidade = float(input('Informe a velocidade: '))
if velocidade > 80:
diferenca = velocidade - 80
valor = diferenca * 5
print(f'Você foi multado em: R$ {valor:.2f}')
|
from django.contrib.auth.models import AbstractUser, UserManager
from django.db import models
# Create your views here.
class UserProfile(AbstractUser):
objects = UserManager()
class Meta(AbstractUser.Meta):
swappable = 'AUTH_USER_MODEL'
# 重载为了打印自定义的字符串
def __unicode__(self):
return ... |
from PIL import Image
import os
import os.path
from natsort import natsorted
import torch
import torch.utils.data as data
from torchvision.transforms import transforms
import torchvision.transforms.functional as TF
import random
import numpy as np
import cv2
#########################################################... |
"""
Вспомогательные общие функции.
"""
#---------------------------------------------------------------------------------------------------
"""
Проверяем, что модуль переимпортировался в IPython notebook.
"""
print('toy_net.common reload')
#-----------------------------------------------------------------... |
import HtbJsonBase as HJB
import logger as lg
class HtbPlotConfig(HJB.HtbJsonBase):
def __init__(self, _inputF):
lg.logging(
'Start Initialing %s' % (self.__class__.__name__), 'SPECIAL'
)
HJB.HtbJsonBase.__init__(self, _inputF)
self.MAIN = None
self.STACK = []
... |
import sys
import coolfluid as cf
# Some shortcuts
root = cf.Core.root()
env = cf.Core.environment()
# Global confifuration
env.options().set('assertion_throws', False)
env.options().set('assertion_backtrace', False)
env.options().set('exception_backtrace', False)
env.options().set('regist_signal_handlers', False)
en... |
import argparse
import contextlib
import gettext
import importlib
import inspect
import itertools
import json
import logging
import os
import site
from pathlib import Path
import shutil
import signal
import subprocess
import sys
import tempfile
import traceback
import time
import attr
import lib50
import requests
impo... |
import datetime
import glob
import json
import discord
import motor.motor_asyncio
from discord.ext import commands
from helpers import embedHelper
with open("token.json") as json_file:
data = json.load(json_file)
prefixjson = data["default_prefix"]
prefix = prefixjson
intents = discord.Intents(messages=True, gui... |
from openerp.osv import fields, osv
from openerp import tools
class hr_req_job_application_filter(osv.osv):
_name = 'hr.cv.filter'
def _get_image(self, cr, uid, ids, name, args, context=None):
result = dict.fromkeys(ids, False)
for obj in self.browse(cr, uid, ids, context=context):
... |
import Enricher.osscan as osscan
import Enricher.portscan as portscan
import json
def scanHostForInfo(ipAddress:str):
os = ""
ports = []
for func in osscan.os_scans:
try:
os = func(ipAddress)
break
except:
continue
for func in portscan.port_scans:
... |
from companyblog import db,login_manager,app
from werkzeug.security import generate_password_hash,check_password_hash
from flask_login import UserMixin,current_user,LoginManager
from flask_admin import Admin
from flask import session, redirect, url_for, request
from flask_admin.contrib.sqla import ModelView
from dateti... |
from okolje import okolje
class podlaga:
def __init__(self, okolje):
self.dvignjeno = 10
self.leviX = 0
self.leviY = okolje.visina - self.dvignjeno
self.desniX = okolje.sirina
self.desniY = okolje.visina - self.dvignjeno
self.barvaPodlage = (0,0,0)
self.debel... |
"""
This module reads the NetScreen configuration and creates address and policy objects in ZODB which can then be used
by the filtering and conversion scripts.
Author: Fahad Yousuf <fahadysf@gmail.com>
Copyright (c) 2017 Fahad Yousuf <fahadysf@gmail.com>
Permission is hereby granted, free of charge, to any pers... |
import numpy as np
from itertools import product
from .normalizer import Normalizer
class ImageNormalizer(Normalizer):
def __init__(self, data, localStd = False):
self.startAxis = 1 if len(data.shape) > 1 else 0
self.meanFrame = np.ndarray(data.shape[self.startAxis:])
self.stdFrame = np.ndarray(self.meanFrame... |
from thresold_clust import *
from point import *
s = Thresold([
(1,2),
(1,3),
(1,4),
(1,5),
(2,2),
(2,3),
(2,4),
(3,7),
(3,8),
(3,9)
])
s.dump_points()
s.cluster(2)
s.dump_cluster()
s.plot_cluster('k1_1_14');
|
# Illustrative example of Single Neuron Classifier for affine separation
# We work in R^2 with the hyperplane of equation -6+2x+3y = 0
# i.e. y = -(2/3)*x + 2
from numpy import sqrt, array, linspace, zeros, exp
from numpy.random import uniform, randn
import matplotlib.pyplot as plt
# Parameters for proper figure expo... |
import os
import sys
import argparse
import parsl
from parsl import *
from parsl.app.app_factory import AppFactoryFactory, AppFactory
workers = ThreadPoolExecutor(max_workers=4)
@App('bash', workers)
def app_1(stderr='std.err', stdout='std.out'):
cmd_line = "echo 'Hello world'"
return cmd_line
def app_2(st... |
# A program to determine if a number is even or odd
number = int(input("Enter a number: "))
if(number % 2 == 0): # No remainder when number is divided by 0
print(f'{number} is an even number')
else: # Number has a remainder when divided by 0
print(f'{number} is an odd number')
|
7mj
# tuple - azaz nem módosítható adathalmazok
# módosítható adatok []
lista = ['Juli', 'Lili', 'Nani', 'Panni', 'Babi']
# nem mődosítható adatok ()
tup1 = ('Bori', 'Betti', 'Kati', 'Móni', 'Böbe')
print(tup1.index('Kati')) # ez megmondja, hogy a Kati hanyadik indexen található
print(tup1.count('kati')) # ez me... |
#!/usr/bin/python
#coding=utf-8
#使用utf-8在命令行窗口里才能运行
import socket
import time
#getpeername()获得socket对方的地址
server=('10.0.2.15',21345)
msg=['hello','welcome','xiaoming','zhangsan','list','liuliu']
socks=[]
for i in range(10):
sock=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
... |
from django.contrib import admin
from .models import Good, Set, Shop, SuperSet
class BaseAdmin(admin.ModelAdmin):
list_display = ['romanized_name', 'name', 'price', 'available_from', 'available_until', 'event', 'shop', 'online_id']
readonly_fields = ['participating_idols', 'participating_groups']
raw_id... |
# -*- encoding: utf-8 -*-
from django.db import models
from django.contrib.auth.models import User
import datetime
from core.settings_local import TOKEN_IBOARDBOT, DOMOTICZ_LOCALIP, DOMOTICZ_IDX, DOMOTICZ_USUER, DOMOTICZ_PASS
import urllib3
# Create your models here.
class Device(models.Model):
__tablename__ = '... |
#!/usr/bin/python3
import spacy
import math
import MeaningfulWordExtractor
from sentence2vecAna import Word, Sentence, sentence_to_vec
nlp = spacy.load('en_core_web_lg')
# euclidean distance between two vectors
def l2_dist(v1, v2):
sum = 0.0
if len(v1) == len(v2):
for i in range(len(v1)):
... |
import numpy as np
import time
import datetime
import pandas as pd
def getWdata(d, w=1):
# 格式化时间,并计算日期是星期几
x1 = time.mktime(time.strptime(d, "%Y-%m-%d %H:%M:%S"))
week = datetime.datetime.fromtimestamp(x1).weekday()
if week == w:
return 'T'
else:
return 'F'
def Is_seventeen(x):
... |
import pywaves as pw
import datetime
import os
import configparser
import random
from colors import *
class BlackBot:
def __init__(self):
self.log_file = "grid.log"
# main
self.node = "https://nodes.wavesnodes.com"
self.chain = "mainnet"
self.matcher = "https://matcher.wav... |
'''Train'''
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import argparse
import os
import sys
import chainer
import chainer.functions as F
import chainer.training
import chainer.training.extensions as extensions
import numpy as np
import scipy.io.wavfile... |
import sys
import time
import signal
def term_sig_handler(signum, frame):
print('catched singal: %d' % signum)
sys.exit()
if __name__ == '__main__':
# catch term signal
signal.signal(signal.SIGTERM, term_sig_handler)
signal.signal(signal.SIGINT, term_sig_handler)
while True:
print('... |
import cv2
import os
import time
import threading
import numpy as np
from time import sleep
from picamera import PiCamera
class Camera (threading.Thread):
def __init__(self, name, times, path, camera):
threading.Thread.__init__(self)
self.name = name
self.times = times
self.path = p... |
#String Programs
print('Program 1 - accept key from keyborad and print it')
name = input('Enter your name ')
print('entered name in upper case %s '%name)
char = input('enter character')
print('character enetered is ',char)
print(type(char))
num = int(input('enter integer value'))
print('the entered number is ',num)... |
#script
# region headers
# * author: salaheddine.gassim@nutanix.com
# * version: 14082019
# task_name: Authentication
# description: this task is used to authenticate again the Avi controller
# endregion
controller_url = "@@{CONTROLLER_URL}@@"
avi_username = "@@{avi.username}@@"
avi_password = "@@{avi.secret... |
import torch.nn as nn
def femnistmodel():
model = nn.Sequential(
nn.Conv2d(1, 32, 5, padding=(2, 2)),
nn.ReLU(),
nn.MaxPool2d(2, stride=2),
nn.Conv2d(32, 64, 5, padding=(2, 2)),
nn.ReLU(),
nn.MaxPool2d(2, stride=2),
nn.Flatten(),
nn.Linear(7 * 7 * 64,... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.