text
stringlengths
38
1.54M
from django.contrib import admin from apps.quiz.models import Quiz, Question, Objective, PlayQuiz class QuestionAdmin(admin.ModelAdmin): list_display = ('question_text', 'is_subjective', 'get_objective') def get_objective(self, obj): return [i['objective_text'] for i in obj.objectives.values('object...
from abc import abstractmethod from pacman import exceptions from pacman.executor.algorithm_classes.abstract_algorithm \ import AbstractAlgorithm from pacman.model.decorators.overrides import overrides class AbstractPythonAlgorithm(AbstractAlgorithm): """ An algorithm written in Python """ __slots__...
"""Helper functions used in multiple places throughout the module.""" import numpy as _np import xarray as _xr def rss(array, dim): """Calculate root-sum-square of array along dim.""" return _np.sqrt(_np.square(array).sum(dim=dim)) def cyclic_extension(array, dim, coord_val=0, add=True): """Cyclicly ex...
# John Rearden 2020 ''' An abstraction to store information on the virtual disks available to a VM. VMWare MOB: Data Object Type: Virtual Hardware Property Path : config.hardware ''' import json import yaml from pyVmomi import vim from utilities import quantize_storage_size class Virt...
from sys import stdin input = stdin.readline def musical_scale(m): if music == sorted(music): return 'ascending' elif music == sorted(music, reverse=True): return 'descending' else: return 'mixed' if __name__ == "__main__": music = list(map(int, input().split())) res = m...
import numpy as np import pandas as pd from sqlalchemy import * from datetime import datetime from sqlhelper import batch from ipdb import set_trace ##连接到现在的数据库 #db = database.connection('wind_sync') #metadata = sql.MetaData(bind=db) #t = sql.Table('caihui_exchange_rate', metadata, autoload=True) #columns = [ # t.c...
############################################################################## # # Copyright (c) 2009 Zope Foundation and Contributors. # All Rights Reserved. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. # THIS SOF...
# Copyright 2020,2021 Sony Corporation. # Copyright 2021 Sony Group Corporation. # # 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 ...
import sys import argparse import structures.src.util.sort_util as util import structures.src.util.timing as timing import structures.src.util.constants as const import structures.src.sorts.bubble as bubble_sort import structures.src.sorts.insertion as insertion_sort import structures.src.sorts.selection as selection...
import numpy as np import scipy as sp import scipy.io as io import pandas as pd from scipy.optimize import minimize class BLP(): def __init__(self): # Use the two files ps2.mat and iv.mat # ps2.mat contains the matrices v, demogr, x1, x2, s_jt, id_demo ps2 = io.loadmat('p...
class JRecRequest: def __init__(self, article): self.article = article # ID used for articles, paragraphs or sentences # Example: 'k10010731741000_para3' self.doc_id = article.doc_id # ID used for url # Example: 'k10010731741000' self.id = self.doc_id[:15] ...
from models.Model_Base import Base from sqlalchemy import Column, Integer, String, DATETIME, func class Device(Base): __tablename__ = 'devices' device_id = Column(Integer, primary_key=True) device_name = Column(String(100)) device_ip = Column(String(500)) created_on = Column(DATETIME(timezone=Tru...
# Generated by Django 3.1.1 on 2020-11-02 09:48 from django.db import migrations, models import phonenumber_field.modelfields class Migration(migrations.Migration): dependencies = [ ('grant_applications', '0010_auto_20201030_1553'), ] operations = [ migrations.RenameField( m...
class Song: name = None next = None # link to next song start = None # empty linked list n = 0 fin = open("songs.txt") for lineFromFile in fin: # EOF loop aSong = lineFromFile.strip() x = Song() x.name = aSong x.next = start # put here to match below start = x n += 1 fin.close() ...
# Figure # Running times of computation tasks import numpy as np import matplotlib.pyplot as plt x = np.linspace(1000, 10000, 10) y1 = [68.514,137.098,204.863,273.898,341.774,408.749,476.726,543.549,611.941,680.712] # Enclave version. Hyperthreading enabled. y2 = [23.036,46.634,69.956,94.085,114.878,138.770,160.354,1...
#实例002:“个税计算” #企业发放的奖金根据利润提成。 # 利润(I)低于或等于10万元时,奖金可提10%; # 利润高于10万元,低于20万元时,低于10万元的部分按10%提成,高于10万元的部分,可提成7.5%; # 20万到40万之间时,高于20万元的部分,可提成5%;40万到60万之间时高于40万元的部分,可提成3%; # 60万到100万之间时,高于60万元的部分,可提成1.5%, # 高于100万元时,超过100万元的部分按1%提成,从键盘输入当月利润I,求应发放奖金总数? profit=int(input('show me the money: '))#控制台输入 bonus=0 thresholds=[1000...
from flask import Flask, request, render_template, redirect, url_for, session import os import pypyodbc from CountryModel import CountryModel from RoleModel import RoleModel from UserModel import UserModel from Constants import connString from StorageUnitModel import StorageUnitModel from FoodManufactureModel import F...
from django.shortcuts import render from django.conf import settings from rest_framework.views import APIView from rest_framework import viewsets from rest_framework.response import Response from rest_framework import status from keras.preprocessing import sequence import tensorflow as tf from keras.models import load_...
import ctypes #import struct import zlib import os.path import getopt import sys import math import time import serial # python3 pip install --user pyserial opts, args = getopt.getopt(sys.argv[1:],'h', ['help']) #print(opts) #print(args) #exit(0) fname = "~/Downloads/" fname = args[0] #fname += "pg2243.txt" #fname +...
import pandas as pd import numpy as np import seaborn as sns import pandas as pd import matplotlib.pyplot as plt import numpy as np from PIL import Image import os from random import choice, sample import cv2 from imageio import imread from keras.preprocessing.text import Tokenizer, one_hot from keras.preprocessing.seq...
#! /usr/bin/env python import rospy from geometry_msgs.msg import Twist from sensor_msgs.msg import LaserScan from std_msgs.msg import Float64 #def processSonarData (): #Method for sennding data def sonarcallback ( sensor_data ): t = sensor_data.data v = 343.0 d = t*v/2 data = d #s...
import pyvital.arr as arr import numpy as np cfg = { 'name': 'PLETH - Pulse Transit Time', 'group': 'Medical algorithms', 'desc': 'Calculate pulse transit time.', 'reference': '', 'overlap': 5, 'interval': 30, 'inputs': [{'name': 'ECG', 'type': 'wav'}, {'name': 'PLETH', 'type': 'wav'}], ...
# -*- coding: utf-8 -*- # @Author: 1000787 # @Date: 2017-06-03 16:16:38 # @Last Modified by: 1000787 # @Last Modified time: 2018-03-07 17:23:53 from .DTensor import DTensor, contract, directSum, deparallelisationCompress, \ diag, fusion, svdCompress class MPO(list): """docstring for MPO""" def __init__(self, *a...
# -*-coding: utf-8 -*- """ 文件处理 """ import os #写入数据 def write_data(file, content_list, model): with open(file, mode=model) as f: #参见Python学习笔记-P1 ,以指定模式(model)打开文件(file),同时创建了"文件对象"(file),并将file简记作"f" #这也意味着,file如果之前有数据,将会被擦除并被改写 for line in content_list: #for-in 遍历...
from keras.layers import Input, Dense, Dropout, BatchNormalization, Conv1D, Flatten, GlobalMaxPooling1D, MaxPooling1D from keras.models import Model import tensorflow as tf from keras.layers import Lambda, concatenate def exp_dim(global_feature, num_points): return tf.tile(global_feature, [1, num_points, 1]) ...
import tensorflow as tf import numpy as np from numpy import * def consine_distance(a,b): # a.shape = N x D # b.shape = M x D a_normalized = tf.nn.l2_normalize(a, dim=1) # 0 is colum, 1 is row b_normalized = tf.nn.l2_normalize(b, dim=1) product = tf.matmul(a_normalized, b_normalized, adjoint_b=Tru...
try: from source.MANTIS_Assembler import * from source.MANTIS_Processor import MANTIS_Processor from source.MANTIS_Interpreter import MANTIS_Interpreter from source.MANTIS_Consensus import MANTIS_Consensus except: from MANTIS_Assembler import * from MANTIS_Processor import MANTIS_Processor f...
# Generated by Django 3.1.4 on 2021-03-15 13:54 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='FreeUser', fields=[ ...
# Generated by Django 2.2.4 on 2019-09-12 08:41 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [('applications', '0005_applicationtemplate_spawner_time')] operations = [ migrations.AddField( model_name='applicationinstance', na...
import pytest import magma as m import magma.testing from magma.inline_verilog import InlineVerilogError def test_inline_verilog(): FF = m.define_from_verilog(""" module FF(input I, output reg O, input CLK); always @(posedge CLK) begin O <= I; end endmodule """, type_map={"CLK": m.In(m.Clock)})[0] class M...
import discord from discord.ext import commands import json, random, praw, datetime, time start_time = time.time() invlink = 'https://discordapp.com/oauth2/authorize?client_id=400501965383139328&scope=bot&permissions=8' guildlink = 'https://discord.gg/Y4uXWKB' votelink = 'https://discordbots.org/bot/40050196538313932...
import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from tensorboardX import SummaryWriter class Net(nn.Module): same = False initial_state = None @staticmethod def same_initial_point(same): Net.same = False if same: net = Net(...
import os import requests from flask import Flask, session, request, redirect, flash, jsonify from flask_socketio import SocketIO, emit from flask import render_template from dotenv import load_dotenv from flask_session import Session app = Flask(__name__) socketio = SocketIO(app) SESSION_TYPE = 'redis' app.secret_ke...
# Generated by Django 2.2.6 on 2019-11-01 00:03 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('mobile', '0005_auto_20191031_1756'), ] operations = [ migrations.AlterField( model_name='mobil', name='defect_tel', ...
import matplotlib.pyplot as plt import csv import datetime, time import numpy as np import matplotlib.gridspec as gridspec from scipy.signal import find_peaks from matplotlib.widgets import Button def nadjiMax(niz, vrijeme, par): tacke = [] poX = [] max = par index = -1. ovdje = 0 for i in ran...
import tensorflow as tf import numpy as np from tabulate import tabulate from tensorflow.python.ops.rnn_cell import LSTMCell, GRUCell from PhasedLSTMCell import PhasedLSTMCell, multiPLSTM from data_generation import create_batch_dataset from tqdm import tqdm import pandas as pd flags = tf.flags flags.DEFINE_string("uni...
import numpy as np import tensorflow as tf import pymongo import tweepy import json import requests from credentials import * from nltk import TweetTokenizer from keras.models import load_model from train import clean_tweet, pad_tweet, vectorize_tweet from gensim.models import Word2Vec import os.path # Vectorizes a tw...
import pytest import tensorflow as tf import numpy as np from numpy.testing import assert_array_equal from model.graph_embedder import GraphEmbedder, GraphEmbedderConfig class TestGraphEmbedder(object): num_nodes = 5 def test_update_utterance(self, graph_embedder): config = graph_embedder.config ...
from datetime import date from django.utils.datastructures import SortedDict from .models import ( Laureate, LaureateOlympiad, LaureateCompetition, Competition, ) def find_beginners(laureates): BEGINNERS_POSITIONS = [0, 6] for laureate in laureates: for competition in laureate.laureatec...
#!/usr/bin/python import secrets from session import IComfort3Session from lcc_zone import IComfort3Zone s = IComfort3Session() s.login(secrets.icomfort_username, secrets.icomfort_password) homes = s.fetch_home_zones() for home in homes: lcc_zones = homes[home] for (lcc, zone) in lcc_zones: s.set_con...
""" Tellor Oracle Reporter Workflow Overview: - Checks the price on coingecko - Submits the price to Tellor Mesosphere - Waits to see 1 block confirmations on the transaction Pre-requisites: - set `reporter-address` in Airflow's Variables for an approved reporter - set `tellor-address` in Airflow's Variables to the M...
#-*- coding:utf-8 -*- import random import cv2,os,time import numpy as np from PIL import Image from utils.image import transform_preds from utils.patch import patchmaker from utils.post_process import ctdet_decode, _nms, _topk from recognition.model import databaseMat from recognition.recog import img2vec from net...
from torchvision import models import torch def get_pre_model(fc_out_features: int, only_train_fc=True): ''' :param fc_out_features: 分类树木,即为全连接层的输出单元数 :param only_train_fc: 是否只训练全连接层 :return: ''' model = models.resnet152(pretrained=True) # 使用预训练 # 先将所有的参数设置为不进行梯度下降 if only_train_fc: ...
#!/usr/bin/env python # -*- coding: utf-8 -*- import logging import re import copy from pycoshark.mongomodels import Issue, Event from core import LabelSHARK, BaseLabelApproach def remove_index(cls): tmp = copy.deepcopy(cls._meta) if 'indexes' in tmp.keys(): del tmp['indexes'] del tmp['index_sp...
import os from flask import Flask from flask_sqlalchemy import SQLAlchemy from flask_marshmallow import Marshmallow from instance.config import app_config app = Flask(__name__, instance_relative_config=True) app.config.from_object(app_config[os.getenv('APP_SETTINGS')]) app.config.from_pyfile('config.py') db = SQLAlche...
import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) FILES_DIR = os.path.join(BASE_DIR, 'files/') # user credentials USER = os.getenv('IUSER') # please, set a user login, with email won't work PASSWORD = os.getenv('IPASSWORD') # Config for like bot ACCOUNTS = os.getenv('ACCOUNTS', '').sp...
#!/usr/local/bin/python import xmlrpclib, sys, networkx as nx, threading # Acts as a client that can call methods on the master node class clientnode(threading.Thread): def _init_(self,ip,port):...
# Generated by Django 3.1.1 on 2020-09-26 03:15 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='data', fields=[ ...
# Based on anime_scrapers by jQwotos import os import re import requests import subprocess import json import logging import argparse from progress.bar import Bar LINK_PAT = re.compile('(https://)(.*)\n') logger = logging.getLogger() logger.setLevel("INFO") logger.addHandler(logging.StreamHandler()) def parseLinks(...
from django.urls import path from . import views urlpatterns = [ path('create_po/', views.po_index, name='po_index'), path('singlepo_create/', views.singlepo_create, name='single_create'), path('create_bill/', views.bill_index, name='bill_index'), path('bill_create/', views.bill_create, name='bill_crea...
import numpy as np ## BLOSUM 62 BLO = {} with open("D:/OneDrive - zju.edu.cn/PTA/BLOSUM62.txt",mode='r') as f: head = f.readline().strip('\n').split() num = [] for line in f.readlines(): num.append(line.strip('\n').split()[1:]) for i in range(len(head)): for j in range(len(head)): ...
# pylint: disable=invalid-name, too-many-locals, too-many-arguments, line-too-long """Functions for learning rules' weights""" from typing import TYPE_CHECKING, Tuple, Optional from copy import deepcopy from joblib import Parallel, delayed, parallel_backend from .utils.logger import Logger if TYPE_CHECKING: # pyl...
# Generated by Django 3.2.3 on 2021-05-20 07:51 from django.db import migrations import home.RichTextBleachField class Migration(migrations.Migration): dependencies = [ ('home', '0018_add_tags_test_data'), ] operations = [ migrations.AlterField( model_name='question', ...
""" 用于对mysql数据库进行备份(已在linux环境中测试没问题) """ import os import time import smtplib from django.conf import settings from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart from email.header import Header class AutoDumpMysqlData: HOST = settings.DATABASES['default']['HOST'] PORT ...
import random l = list(range(100)) random.shuffle(l) print(l) def bubble_sort(lst): """冒泡排序""" for i in range(len(lst) - 1): # 需要排序的列表长度(几趟), 跟j + 1比较 所以len-1, 最底下那个数已经在本来位置 exchange = 0 for j in range(len(lst) - 1 - i): # 每趟的长度(发生几次比较) if lst[j] > lst[j + 1]: # 比较前后二个值的大小 ...
from bs4 import BeautifulSoup import requests from time import sleep from selenium import webdriver from selenium.webdriver.common.desired_capabilities import DesiredCapabilities from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC # A SIMPLE SPIDER F...
#!/usr/bin/python from __future__ import division import matplotlib.pyplot as plt #TBD for doc retrieve N = 9952 nums = [5, 10, 20, 30, 40, 50, 60, 70, 80] cover = [6763, 7847, 8765, 9237, 9367, 9405, 9429, 9445, 9447] ratio = [x / N for x in cover] plt.figure(1) plt.plot(nums, ratio) plt.title("Answer hit(%) in ...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ @File : organization_code_check.py @Author: rebecca @Date : 2020/4/24 13:47 @Desc : """ import string # 用数字与大写字母拼接成code_map,每个字符的index就是代表该字符的值 code_map = string.digits + string.ascii_uppercase # 加权因子列表 WMap = [3, 7, 9, 10, 5, 8, 4, 2] def get_c9(bref): # C9=11...
from db_credentials import db_engine engine = db_engine() engine.execute(""" CREATE TABLE IF NOT EXISTS daily_summary ( country VARCHAR(128), countrycode VARCHAR(2), slug VARCHAR(128), new_confirmed INTEGER, total_confirmed INTEGER, new_deaths INTEGER, tot...
""" Base renderer class """ import html import itertools import re from .helpers import camel_to_snake_case, is_type_check if is_type_check(): from typing import Any, Union from .inline import InlineElement from .block import BlockElement from .parser import ElementType Element = Union[BlockEleme...
def print_welcome_message(): print('Welcome to Split-it') def print_menu_options(): menu_dict = {'About\t\t': '(A)', 'CreateProject\t': '(C)', 'Enter Votes\t': '(V)', 'Show Project\t': '(S)', 'Quit\t\t': '(Q)'} for k, v in menu_dict.items(): print(f'{k} {v}') # not 100% w...
import requests from itsDemoTest.comm.ReadConfig import config from itsDemoTest.comm.md5_password import psd import unittest from itsDemoTest.comm.apiutils import API_Info from itsDemoTest.comm.log_utils import logger class Login_InfoCase(unittest.TestCase): def setUp(self) -> None: self.session = requests...
__author__ = 'Steeven Villa' import cv2 as v import os import numpy as np from corte import dividir from Caracteristicas import eolaplace, eogradient, smlaplacian from Others import GetImagenes from easygui import * numero =1 files = GetImagenes("dataset_gray") salida = "OUTq" img = numero*2 print files[img] A = v....
__author__ = 'mh' from network_elements.addresses import IPv6Address, MacAddress import world class BasedMessage(object): def __init__(self, env): self.env = env #self.payload = None def __str__(self): return self.msg #.print_payload(self) def print_payload(self, msg): i...
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes ...
from django.urls import path from api.collaboration.views import BarrierTeamMemberDetail, BarrierTeamMembersView urlpatterns = [ path( "barriers/<uuid:pk>/members", BarrierTeamMembersView.as_view(), name="list-members", ), path( "barriers/members/<int:pk>", BarrierT...
from hopf.simulation import Simulation s = Simulation() s.load_initial_conditions('random40.mat') s.sigma = 0.10 s.run_simulation(h = 0.1, tmax=2000, numpoints=1000, sim='sphere-midpoint') s.post_process() s.save_results('data/generic40_T200_sphere.mat') s = Simulation() s.load_initial_conditions('random40.mat') s.si...
"""Use case for loading a metric entry.""" from dataclasses import dataclass from typing import Iterable from jupiter.core.domain.features import Feature from jupiter.core.domain.metrics.metric_entry import MetricEntry from jupiter.core.framework.base.entity_id import EntityId from jupiter.core.framework.use_case impo...
df = pd.read_csv('../data/letter-recognition.csv', header=None) df['TARGET'] = df[0] df = df.drop([0], axis=1) def sample_df(df, num_letters=6): letters = [chr(x+65) for x in np.random.choice(26, num_letters, replace=False)] rows = np.any([df.TARGET == l for l in letters], axis=0) df = df[rows].apply(lamb...
import os import random import sys def makeData(index): os.system("rename zuma" + str(index) + ".in number" + str(index) + ".in") os.system("rename zuma" + str(index) + ".out number" + str(index) + ".out") for i in range(20): makeData(i)
from django.forms import ModelForm from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User,BaseUserManager #User1=User.objects.get(username='username') #User1.is_admin= True #User1.is_superuser = True #User1.is_staff= True #User1.save() from django import forms from ....
from django.shortcuts import render from . import models from . import serializers from django.http import Http404 from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status, generics from .models import commands # Create your views here. commands_obj = co...
from google.appengine.ext import db class User(db.Model): UserName = db.StringProperty() Password = db.StringProperty() RegistedDate = db.DateTimeProperty(auto_now_add=True) class Wiki(db.Model): title = db.StringProperty() content = db.TextProperty() created = db.DateTimeProperty(auto_now_add=True) author = d...
""" Created by Andrew Silva on 10/26/20 """ import torch import torch.nn as nn import typing as t import numpy as np def weight_init(m): if isinstance(m, nn.Linear): torch.nn.init.xavier_uniform_(m.weight, gain=1) torch.nn.init.constant_(m.bias, 0) class MLP(nn.Module): def __init__(self, ...
#!/usr/bin/env python # encoding: utf-8 """ Created by Preston Holmes on 2010-01-13. preston@ptone.com Copyright (c) 2010 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, incl...
import json def parse_location(location): return { "type": "Feature", "geometry": { "type": "Point", "coordinates": [location["longitude"], location["latitude"]] }, "properties": { "name": location["city"] } } def main(): with o...
from django.shortcuts import render from django.http import JsonResponse from django.conf import settings from .apps import DigitrecappConfig from rest_framework.decorators import api_view import cv2 from PIL import Image, ImageGrab, ImageDraw import os import time import requests import json import io import numpy as...
import cv2 as cv import numpy as np from matplotlib import pyplot as plt image = cv.imread('coins.jpg') src = cv.imread('coins.jpg') gray = cv.cvtColor(image, cv.COLOR_BGR2GRAY) ret, thresh = cv.threshold(gray, 0, 255, cv.THRESH_BINARY_INV + cv.THRESH_OTSU) # noise removal kernel = np.ones((3, 3), np.uint8) opening =...
#! /usr/bin/env python '''storage.py - Spambayes database management framework. Classes: PickledClassifier - Classifier that uses a pickle db DBDictClassifier - Classifier that uses a shelve db PGClassifier - Classifier that uses postgres mySQLClassifier - Classifier that uses mySQL Trainer - Clas...
source_strs_sub_results = [ '.new-game-accept-customization {\n' ' position: absolute;\n' ' z-index: 2;\n' ' width: 180px; \n' ' height: 80px; \n' ' left: 2360px; \n' ' top: 2360px; \n' ' font-size: 36px;\n' ' color: #b6b6b6;\n' ' background-color: #6c6c6c;\n' ' border: 2px soli...
""" #ITERACION DE STRINGS --------------------------------------------------------------------- Funciona de la misma forma que cualquier otra iteracion de una lista de objetos """ # EJEMPLO 1 s = "Iterando strings" # Recorrer el string con for for l in s: print(l) # EJEMPLO 2 s = "Iterando strings" indice = 0; whil...
# Forward stepwise selection for best predictor subset selection import numpy as np import matplotlib.pyplot as plt from sklearn.model_selection import train_test_split class ForwardSelection: '''Class for selecting the best predictor subset to train a linear model such and LinearRegression or LogisticRegres...
#!/usr/bin/env python import rospy from geometry_msgs.msg import PoseStamped, TwistStamped from styx_msgs.msg import Lane, Waypoint from std_msgs.msg import Int32 import math import tf ''' This node will publish waypoints from the car's current position to some `x` distance ahead. As mentioned in the doc, you shoul...
import tweepy import re import urllib import os import codecs import time consumer_key = "" consumer_secret = "" access_key = "" access_secret = "" auth = tweepy.OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(access_key, access_secret) api = tweepy.API(auth) path = "./img/" def Downloadimg(tweet_...
from django.shortcuts import render, render_to_response from django.http import HttpResponse, JsonResponse import sys, cgi, os, json, gzip import numpy as np import pickle as pkl def main(request): return render(request, "index.html") def recommend(request): handler = dummyHandler() sname = int(request.PO...
#coding=utf-8 ''' Created on 2018.12.17 @author: gaowei ''' import unittest import time from utils.common.common import getNextTime from utils.login.search_login import logIns, logout from utils.volumeControl.volumeControl_Auto import setVolume_Auto from utils.volumeControl.getVolumeInfo import getVolumeInfo, assertVo...
import numpy as np class sidak_proc: def __init__(self, alpha0, numhpy, gamma_vec_exponent, markov_lag=0): self.alpha0 = alpha0 #FWER level self.alpha = np.zeros(numhpy) # alpha vec # Cmopute the discount gamma sequence and make it sum to one tmp = range(1, 10000) self.gamma_vec = np.true_divide(np.ones(l...
#!/usr/bin/env python # Written by Dong Yuan Yang (dyan263) import os import sys import shutil def main(): path = os.getcwd() + "/.versiondir" shutil.rmtree(path) print ".versiondir deleted" os.system('fusermount -u mount') print "Unmounted directory" if __name__ == '__main__': main()
import json import os import uuid from datetime import datetime from flask import current_app from flask_restplus import Namespace, Resource # from celery import group from flaskapi.core.worker import celery from celery.exceptions import TimeoutError, CeleryError from celery import group, chain # from flaskapi.api i...
import os import sys import numpy as np import tensorflow as tf from datetime import datetime from math import ceil from sklearn.metrics.pairwise import cosine_similarity # Custom libraries sys.path.append('../Util') from loader import get_book_dataframe, get_book_features from cross_validation import ColumnwiseKFold ...
## This program is free software; you can redistribute it ## and/or modify it under the same terms as Perl itself. ## Please see the Perl Artistic License 2.0. ## ## Copyright (C) 2004-2016 Megan Squire <msquire@elon.edu> ## Major Contributions from Evan Ashwell (converted from perl to python) ## ## We're working on t...
''' def add(x,y): z = x + y print(z) ''' def add(x = 0, y = 0): z = x + y print(z) def sub(x,y): #z = x - y z = x - y if x > y else y - x print(z) #add(2,2) add(y=2,x=5) sub(3,7)
from ConfigParser import ConfigParser from functools import wraps from flask import Flask, render_template, request, redirect, session, url_for from flask.ext.assets import Environment, Bundle from flask_googlelogin import GoogleLogin from os import mkdir import os.path from StyleGrader import StyleRubric from werkzeug...
### Right now we only suppost csv. import io import os import glob import numpy as np import pandas as pd import json import model from flask import Flask, request, jsonify, render_template, send_file, Response,session import flask import csv import json from flask_session import Session app = Flask(__...
# this is to cater for Python 2, is it really needed? try: from inspect import getfullargspec except ImportError: from inspect import getargspec as getfullargspec # Auto pack or grid position the element # INTERNAL ONLY def auto_pack(widget, master, grid, align): # If the master widget specifies grid, do...
<<<<<<< HEAD from torch.autograd import Variable import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from extract_data import GetDataFromCSV import torch import numpy as np class Net(nn.Module): def __init__(self): super(Net, self).__init__() # 1 input image channel(g...
import zmq import time #Set database to use database = "sqlite3" #####OPTIONS############ module_in = "ipc://module_i2c" db_name = "rLoop" db_user = "rloop" #rloop - DY ######################## ##### #Sensor Identity SensorName='TestSens' #CONCEPT: Store attribute listing and handle all the info on python prior to...
__version__ = '0.1' __date__ = '28-11-2019' __author__ = 'Shervin Azadi & Pirouz Nourian' import numpy as np node = hou.pwd() #function to put the attributes of the houdini geometry into a numpy array def attrib_to_nparray(input_index, attributeList): #loading the geometry of the corresponding input geo...
from sys import maxint from functools import wraps def memo(fn): cache = {} miss = object() @wraps(fn) def wrapper(*args): result = cache.get(args, miss) if result is miss: result = fn(*args) cache[args] = result return result return ...
lb = float(input('digite o peso em libras desejado: ')) kg = lb * 0.45 print(f'{lb} libras equivalem a {kg} quilos')