text
stringlengths
38
1.54M
#!/usr/bin/python3 # -*- coding: utf-8 -*- from flask import g from flask_restful import Api, Resource from flask_restful import abort, reqparse, fields, marshal_with, marshal from models import PersonalUser, EnterpriseUser, UserAuthInfo from models import UserSocialInfo, UserIMConfig, UserPushConfig from models impor...
import torch import torchvision import torch.utils.data as data import os from os.path import join import argparse import logging from tqdm import tqdm #user import from data_generator.DataLoader_Pretrain_Alexnet import CACD from model.faceAlexnet import AgeClassify from utils.io import check_dir,Img_to_zero_center #s...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ FOR PROJECT WRITE-UP ONLY Generating a few illustrative plots of activation functions and what image elements they can produce. Created on Tue Sep 22 20:58:33 2020 @author: riversdale """ import numpy as np import matplotlib.pyplot as plt from src.imaging import Ima...
import timeit setup = ''' import numpy as np # from numba import jit # @jit def bubblesort(X): N = len(X) for end in range(N, 1, -1): for i in range(end - 1): cur = X[i] if cur > X[i + 1]: tmp = X[i] X[i] = X[i + 1] X[i + 1] = tmp...
# -*- coding: utf-8 -*- class Node(object): def __init__(self, data, left=None, right=None): self.data = data self.left = left self.right = right tree = Node(1, Node(3, Node(7, Node(0)), Node(6)), Node(2, Node(5), Node(4))) def lookup(root): """ 层次遍历 """ stack = [root] ...
from kmk.keys import KC from kb import KMKKeyboard from kmk.hid import HIDModes from kmk.modules.layers import Layers from kmk.modules.modtap import ModTap keyboard = KMKKeyboard() modtap = ModTap() layers_ext = Layers() keyboard.modules = [layers_ext, modtap] # Cleaner key names _______ = KC.TRNS CTL_Z = KC.MT(KC...
from InBedManagementTreeView import InBedManagementTreeView from PyQt4.QtCore import * from PyQt4.QtGui import * from Gui.ItemModels.BoundaryTypeInBedItemModel import * class BoundaryTypeInBedItemView(InBedManagementTreeView): def __init__(self, parent): InBedManagementTreeView.__init__(self, parent) ...
from django.apps import AppConfig class IndividualworkappConfig(AppConfig): name = 'individualworkapp'
for x in range(10): print(x+1) print( ) word = input('Введите любое слово: ') for letter in word: print(letter) print( ) rating = [{'shool_class': '4a', 'scores': [2, 3, 3, 5, 4]}, {'shool_class': '4b', 'scores': [2, 4, 5, 5, 4]}, {'shool_class': '4v', 'scores': [2, 2, 3, 5, 3]}] a = 0 for result in rati...
# -*- coding: utf-8 -*- from zope.interface import Interface class IDoormat(Interface): """Marker interface for .Doormat.Doormat """ class IDoormatColumn(Interface): """Marker interface for .DoormatColumn.DoormatColumn """ class IDoormatSection(Interface): """Marker interface for .DoormatSecti...
""" 1.设置日志的收集级别 2.可以将日志输出到文件和控制台 3.一下这些方法: info() debug() error() warning() critical() 额外扩展:单列模式 """ import logging from logging import Logger from day15.myconf import Myconf class MyLogger(Logger): def __init__(self): conf = Myconf("conf.ini") file = co...
class student: def __init__(self, name, grade): self.name = name self.grade = grade # finish the logic in the class def __repr__(self): return self.name def __lt__(self,another_student): return self.grade < another_student.grade AList = [student("Mary", 80),...
from django.urls import path from webapp import views urlpatterns = [ path('', views.hello_world, name='hello_world'), path('savedata', views.savedata, name='savedata'), path('savedata/', views.savedata, name='savedata'), ]
#!/usr/bin/python # -*- coding: utf-8 -*- # this imports verbs for loading by lib/verbs/verbs.py # pylint: disable=unused-import # pylint doesn't know where this file is imported from # pylint: disable=import-error # "verbs" (lowcase) is standard among all files # pylint: disable=invalid-name """ [load_packages.py]...
# -*- coding: utf-8 -*- from hmonitor.autofix.scripts import AutoFixBase class JustShowEventInfo(AutoFixBase): def do_fix(self, trigger_name, hostname, executor, event, *args, **kwargs): raise Exception("ERROR TEST") def get_author(self): return "Qin TianHuan" def get_version(self): ...
flag = True while flag: try: sec = int(input('Input time in seconds:' )) flag = False except: print('Entered time is not a number!!!') print(f'{sec//3600:02}:{(sec//60)%60:02}:{sec%60:02}')
import sys sys.stdin = open('주사위 던지기2.txt') def myprint(q): tmp = 0 t = [] while q != 0: q -= 1 t.append(T[q]) tmp += T[q] if tmp>m: break if tmp==m: result.append(t) def PI(n, r, q): if r == 0: myprint(q) else: for i in range...
import unittest import parseGEDCOM class us07Test(unittest.TestCase): def testUS07(self): self.assertEqual(parseGEDCOM.checkUS07(), "ERROR: INDIVIDUAL: US07: @I20@: More than 150 years old at death - Birth 1800-07-28: Death 1980-10-27\n"+ "ERROR: INDIVIDUAL: US07: @I21@: More than 150 ye...
""" Definition of ListNode class ListNode(object): def __init__(self, val, next=None): self.val = val self.next = next """ class Solution: """ @param head: The first node of the linked list. @return: nothing """ def reorderList(self,head): # basic steps: # step ...
import urllib import requests import pandas as pd import sys # scrape movie posters and corresponding meta data def scrape_meta_posters(mids): ''' Scrape posters and metadata from IMDB using OMDB API Input: IMDB ids Output: meta data and posters ''' meta_info = [] for id_ in mids: ...
""" Project Euler's Problem 014 Sebuah barisan iteratif berikut didefinisikan untuk himpunan bilangan bulat positif dengan aturan: n → n/2 (n ∈ bilangan genap) n → 3n + 1 (n ∈ bilangan ganjil) Menggunakan aturan di atas, dimulai dari 13, maka kita akan mendapatkan barisan: 13 → 40 → 20 → 10 → 5 → 16 → 8 → ...
import requests import brotli from requests.packages.urllib3.exceptions import InsecureRequestWarning requests.packages.urllib3.disable_warnings(InsecureRequestWarning) from bs4 import BeautifulSoup sess = requests.Session() http_proxy = "http://163.172.110.14:1457" proxyDict = { "http": http_proxy, "https":...
import asyncpg import pandas as pd from liualgotrader.common import config from liualgotrader.common.tlog import tlog async def create_db_connection(dsn: str = None) -> None: config.db_conn_pool = await asyncpg.create_pool( dsn=dsn or config.dsn, min_size=2, max_size=40, ) tlog("...
import os from typing import Union, List, Callable, Optional, Tuple import hydra import torch from kornia.losses import BinaryFocalLossWithLogits import yaml with open(os.path.join( '/home/rishabh/Thesis/TrajectoryPredictionMastersThesis/src/position_maps/', 'config/model/model.yaml'), 'r') as f: ...
totalMarks = 0 numberOfStudents = 0 marks = int(input("Enter the marks of students or a negative value to quit: ")) while marks >=0: totalMarks += marks numberOfStudents += 1 marks = int(input()) print("The total number of students is: {}".format(numberOfStudents)) print("The total marks of studen...
import sys nome = "Bruno Wayne" idade = 30 peso = 92.3 list = ["youngling", "padawan", "knight", "master"] categorias = ("youngling", "padawan", "knight", "master") print("a var nome é do tipo {} e tem {} bytes".format(type(nome), sys.getsizeof(nome))) print("a var idade é do tipo {} e tem {} bytes".format(type(idade...
# Generated by Django 3.1.7 on 2021-03-04 06:44 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ("committees", "0008_auto_20210112_1221"), ] operations = [ migrations.AlterField( model_name="committee", name="date_...
# -*- coding: utf-8 -*- import socket # Nécessaire pour ouvrir une connexion import PoolAdresse #On fait appel aux fonctions présentes dans PoolAdresse.py import csv #Nécessaire pour manipuler facilement les fichiers CSV import smtplib import datetime import requests from email.mime.multipart import MIMEMultipart from...
# -*- coding: utf-8 -*- import theano theano.config.floatX= 'float64' #out_sc_x is the Parsey McParseface parsing result of original sentence #out_sc_y is the Parsey McParseface parsing result of summary ############################################################################### f=open("./out_sc_x.txt",mode="r") ...
#Escriba un programa en Python donde el usuario introduce un número n #y el programa imprime los primeros n números triangulares, junto con #su índice. Los números triangulares se originan de la suma de los números #naturales desde 1 hasta n.Ejemplo: Si se piden los primeros 3 números #triangulares, la salida es: 1 -...
# Postorder Traversal # Problem Description # Given a binary tree, return the Postorder traversal of its nodes values. # NOTE: Using recursion is not allowed. # Problem Constraints # 1 <= number of nodes <= 10^5 # Input Format # First and only argument is root node of the binary tree, A. # Output Format # Return an...
# 20 choose 3 with reps counter = 10 for i in range(1, 16): for j in range(i, 16): for k in range(j, 16): print(i, j, k) counter += 1 print(counter)
import os,sys import ROOT from array import array import argparse from datetime import datetime import pandas as pd import numpy as np import pdb sys.path.append(os.getcwd()) print(os.getcwd()) os.sys.path.append(os.path.expandvars('$CMSSW_BASE/src/ZCounting/')) from ZUtils.python.utils import to_RootTime ROOT.gROO...
import gzip import cv2 import _pickle import tensorflow as tf import numpy as np # Translate a list of labels into an array of 0's and one 1. # i.e.: 4 -> [0,0,0,0,1,0,0,0,0,0] def one_hot(x, n): """ :param x: label (int) :param n: number of bits :return: one hot code """ if type(x) == list: ...
#!/usr/bin/env python # -*- coding:utf-8 -*- # date :2018/1/ # discriptions : # vision : # copyright :All copyright reserved by FMSH company __author__ = 'zuodengbo' def TAC_enc(keys, datas): assert len(keys) == 32 assert len(datas) == 48 length = len(keys) / 2 first_half_key = keys[:l...
class UCDay_Hourly: def __init__(self, ucday): self.date = ucday.date self.hourly_map = {} for i in range(0, 24): self.hourly_map['hr'+str(i)] = ucday.hours[i]
import openpyxl as xl import csv import numpy as np ## flags { TOP3 = False TOP2 = True TOP1 = True ## flags } def main(dargs): input_excel_name = dargs["INPUT_EXCEL_NAME"] output_excel_name = dargs["OUTPUT_EXCEL_NAME"] input_csv_name = dargs["INPUT_CSV_NAME"] ## READ Excel file wb...
""" This code represents a set of functions to implement the toy problem for the Xor gate, it uses an Artificial Neural Network in which the parameters are set by a Genetic Algorithm, in this case, the weights are being set. This must be used with the interface, as it does not print any result on the screen and works ...
# Capture mouse clicks and draw a dot on the image import numpy as np import argparse import cv2 file_name = '..\image4\parking.jpg' points = [] def onMouseClick (event, x, y, flags, param): global points # grab references to the global variable if event == cv2.EVENT_LBUTTONUP: points.append((x, ...
#!C:\Users\Vaibhavi Raut\AppData\Local\Programs\Python\Python37 ''' WAP to accept a string from user and convert it to lowercase and uppercase. ''' word = input("Enter a word: ") print(type(word)) if word.islower(): print("UpperCase is ",word.upper()) elif word.isupper(): print("LowerCase is ",...
import re def remove_comments(filename): with open(filename, 'r') as f: data = f.read() # remove all occurance streamed comments (/*COMMENT */) from string data = re.sub(re.compile("/\*.*?\*/", re.DOTALL) , "", data) # remove all occurance singleline comments (//COMMENT\n ) from str...
import setuptools with open('VERSION', 'r') as verfile: version = verfile.read() with open("README.md", 'r') as fh: long_description = fh.read() setuptools.setup( name="gqla", version=version, author="Alexey Kuzin", author_email="alenstoir@yandex.ru", description="A module used to generat...
# Generated by Django 3.0 on 2020-09-12 01:51 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('coffee', '0002_coffeepod'), ] operations = [ migrations.AlterField( model_name='coffeepod', name='product_type', ...
import tensorflow as tf import numpy as np num_units = 256 # num_units = 200 attention_len = 512 def matU(shape=[num_units,attention_len], stddev=0.1, mean=0): initial = tf.truncated_normal(shape=shape, mean=mean, stddev=stddev) with tf.variable_scope('attention', reuse=tf.AUTO_REUSE): return tf.get_...
# draw circles on a canvas import numpy as np import cv2 canvas = np.zeros((300, 300, 3), dtype = "uint8") # (y,x,3) cx, cy = canvas.shape[1]/2, canvas.shape[0]/2 blue = [250,0,0] for rad in range(0,150,20): cv2.circle(canvas, (cx,cy), rad, blue) cv2.imshow("My Art", canvas) # reuse the same w...
import cv2 import glob import random import numpy as np emotions = ["neutral", "anger", "contempt", "disgust", "fear", "happy", "sadness", "surprise"] #Emotion list #fishface = cv2.face.FisherFaceRecognizer_create() #Initialize fisher face classifier fishface = cv2.createLBPHFaceRecognizer() faceCascade = cv2.CascadeC...
# -*- coding:utf-8 -*- # ------------------------------- # ProjectName : autoDemo # Author : zhangjk # CreateTime : 2020/10/3 16:08 # FileName : wjx # Description : # -------------------------------- import turtle import time turtle.pensize(5) turtle.pencolor("yellow") turtle.fillcolor("red") turtle.begin_fill() fo...
# -*- coding: utf-8 -*- import numpy as np import scipy import astropy.units as u def deltaMag(p, Rp, d, Phi): """Calculates delta magnitudes for a set of planets, based on their albedo, radius, and position with respect to host star. Args: p (ndarray): Planet albedo ...
# model form : model, form(parent) from django.contrib.auth.models import User from django import forms class SignUpForm(forms.ModelForm): # additional field password -> 우선순위가 더 높다 password = forms.CharField(label='Password', widget=forms.PasswordInput) password2 = forms.CharField(label='Repeat Password',...
#!/usr/bin/python from api.utils.test_base import BaseTestCase class TestEmployees(BaseTestCase): def setUp(self): super(TestEmployees, self).setUp() def test_get_employees(self): self.assertEqual(True, True)
import numpy as np import cv2 from glob import glob input_path = './data/video/mica-cam-output.mp4' video_cap = cv2.VideoCapture(input_path) while(video_cap.isOpened()): ret, frame = video_cap.read() if not ret: break cv2.imshow('img', frame) cv2.waitKey() video_cap.release() cv2.destroyAllW...
import scipy.io import numpy as np class KittiDatasetReader: """ base class for Kitti DataReader provides common function for kitti data readers """ @staticmethod def get_file_content(file_path): """ function read content of file in file_path """ with open(file_path, 'r'...
from typing import List from itertools import permutations def gen_primes(limit=10000): """Generates all primes up to a given limit.""" candidates = set(range(2, limit)) primes = [] while len(candidates) > 0: prime = min(candidates) primes.append(prime) for number in range(pr...
#_*_encoding:cp936_*_ import random l = ['项','万','福','侠','心','海','康','宁','冲','元','云','飞','风','峰','贵','国','雪','夏','霞'] def choice(lists,num): i = 1 while i<=num and num<=len(l): print random.choice(lists) i = i + 1 n = input('请输入要选择的人数:') choice(l,n)
#!/usr/bin/env python """ Provides useful physical constants. """ from math import pi __author__ = "Sean Hooten" __license__ = "BSD-2-Clause" __version__ = "0.2" __maintainer__ = "Sean Hooten" __status__ = "development" h = 6.62607e-34 hbar = h / (2*pi) c = 299792458.0 q = 1.60218e-19 eps0 = 8.85419e-12 m0 = 9.10938...
from enum import Enum class SIZE(Enum): # The integer values define their order in a tensor SMALL = 0 MEDIUM = 1 LARGE = 2 def main(state, event): del event # unused print("size :", state["size"].name) print("sizerequired:", state["sizerequired"].name) print("sizelist:", str(" ".joi...
from urllib.request import urlopen, Request from BeautifulSoup import BeautifulSoup import pickle mistakes = {} ##for i in string.ascii_uppercase: ## url = "http://en.wikipedia.org/wiki/Wikipedia:Lists_of_common_misspellings/"+i ## req = Request(url, headers={'User-Agent':"Magic Browser"}) ## print url ## page = B...
import pandas as pd from tkinter import filedialog load_features_file = filedialog.askopenfilename() df = pd.read_excel(load_features_file) df = pd.DataFrame(df) total_cols = len(df.columns) print(total_cols)
# # Copyright (c) 2013 Juniper Networks, Inc. All rights reserved. # import re from setuptools import setup, find_packages def requirements(filename): with open(filename) as f: lines = f.read().splitlines() c = re.compile(r'\s*#.*') return list(filter(bool, map(lambda y: c.sub('', y).strip(), lin...
class Solution: def getPermutation(self, n, k): """ :type n: int :type k: int :rtype: str """ if n == 1: return "1" nums = list(range(1, n+1)) i = 1 while i < k: self.permutation_sequence(nums, n) i += 1 ...
import requests import os, sys import json from multiprocessing.dummy import Pool as ThreadPool from datetime import datetime import logging def worker(i): currentFile = "files\\{}.json".format(i) if os.path.isfile(currentFile): logging.info("{} - File exists".format(i)) return 1 url = "h...
import pandas as pd import numpy as np from sklearn.gaussian_process import GaussianProcessClassifier, GaussianProcessRegressor from sklearn.gaussian_process.kernels import RBF, WhiteKernel from tqdm.notebook import tqdm import scipy.optimize as op def LineageCounts(df_data, dict_lineages, t_ranges): ''' Funct...
# Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 """Utilities for testing the logging system (metrics, common logs).""" import fcntl import os class Fifo: """Facility for creating and working with named pipes (FIFOs).""" path = None fifo = N...
# -*- coding: utf-8 -*- from __future__ import absolute_import, unicode_literals from base64 import b64encode from .base import logger, Base # # Abstract # class AbstractKey(Base): def __init__(self, size=None, key=None, **kwargs): self.size = size self.key = key super(AbstractKey, self)...
from flask import jsonify, Response, url_for from estimator import db from database.models import Group, User from flask import Blueprint api = Blueprint('api', __name__) @api.route('/rest/v1/group/<groupname>', methods = ['POST']) def create_group(groupname): user = User.query.filter_by(nickname='default').first() ...
#!/usr/bin/env python3.7 import click import tempfile import subprocess import tqdm import json import inspect import array import math import os import functools def helper_for(other): def decorator(f): @functools.wraps(f) def helper(*args, **kwargs): self = f.__name__ hel...
import sys import os num_walks = [10,30,100,300] dimension = [32,64,128,256] walk_len = [5,15,50,100] window = [5,10,20] iteration = [1,5,10,50,100] p_list = [0.1,0.5,1,2,10] q_list = [0.1,0.5,1,2,10] input_file = "loc-brightkite_edges.txt" for n_walk in num_walks: dim = 128 w_len = 80 win = 10 ite =...
from os import name from flask_admin import model from pymongo import MongoClient from bson.objectid import ObjectId import flask_admin as admin from wtforms import form, fields from flask_admin.form import Select2Widget from flask_admin.contrib.pymongo import ModelView, filters, view from bson.json_util import dumps ...
import cv2 # Reading video cap = cv2.VideoCapture('../data/seniorita.mp4') # loop while(cap.isOpened()): ret, frame = cap.read() if ret: gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) cv2.imshow('frame', gray) if cv2.waitKey(1) & 0xFF == ord('q'): break else: p...
from django.test import TestCase from rest_framework.response import Response from django.contrib.auth import get_user_model from rest_framework import request, status from rest_framework.test import APIClient User = get_user_model() # Create your tests here. class JwtAuthTest(TestCase): def setUp(self) -> None:...
#import win32com.client import os import skimage import skimage.viewer import sys import cv2 import csv from matplotlib import pyplot as plt import numpy as np import glob editFiles = glob.glob("D:/FOOTFALL_IMAGES/CMT_*.jpeg") for i, fname in enumerate(editFiles): name=fname[19:30] img = cv2.imread(editFiles...
# ---------------------------------------------------------------------- # NWQBench: Northwest Quantum Proxy Application Suite # ---------------------------------------------------------------------- # Ang Li, Samuel Stein, James Ang. # Pacific Northwest National Laboratory(PNNL), U.S. # BSD Lincese. # Created 05/21/2...
import sys from maraboupy import Marabou, MarabouUtils, MarabouCore import numpy as np from eval_network import evaluateNetwork from tensorflow.python.saved_model import tag_constants ## SD QUERY : the situation is great and we were expected bitrate to be HD, but actual bitrate is SD def create_network(filename,k): ...
from heapq import heappop, heappush class Solution: def shortestDistance(self, maze, start, destination): start, destination = tuple(start), tuple(destination) queue = [((0,) + start)] visited = { start:0 } m, n = len(maze), len(maze[0]) while queue: dis, r, c = h...
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Date : 2020-03-15 21:19:23 # @Author : mutudeh (josephmathone@gmail.com) # @Link : ${link} # @Version : $Id$ import os class Solution(object): def generateAbbreviations(self, word): """ :type word: str :rtype: List[str] """ ...
#!/usr/bin/env python3 import os import pprint import fnmatch from PhysicsTools.HeppyCore.utils.dataset import createDataset if __name__ == '__main__': import sys from optparse import OptionParser import pprint parser = OptionParser() parser.usage = "%prog [options] <dataset>\nPrints informa...
# -*- coding: utf-8 -*- # See LICENSE file for full copyright and licensing details. from odoo import api, fields, models class ProductProduct(models.Model): _inherit = 'product.product' @api.model def get_products_by_pricelist(self, product_ids = None, pricelist_ids = None,): """ It will...
import os import sys import django os.environ.setdefault("DJANGO_SETTINGS_MODULE", "AthleteAPI.settings") django.setup() from Athlete.importAthleteCSV import * if len(sys.argv) >= 3: pathNOC = sys.argv[1] pathAthlete = sys.argv[2] if validateNOCCSV(pathNOC): importNOCCSV(pathNOC) pass ...
# 编写一个 SQL 查询,来删除 Person 表中所有重复的电子邮箱,重复的邮箱里只保留 Id 最小 的那个。 # # +----+------------------+ # | Id | Email | # +----+------------------+ # | 1 | john@example.com | # | 2 | bob@example.com | # | 3 | john@example.com | # +----+------------------+ # Id 是这个表的主键。 # # # 例如,在运行你的查询语句之后,上面的 Person 表应返回以下几行: ...
""" You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list. You may assume the two numbers do not contain any leading zero, except the number 0 itself. ...
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.4' # jupytext_version: 1.2.4 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- # # MID-2017 POPULATION ESTIMATES: Net migration by age...
#A Denoising Sparse Autoencoder class using THEANO #Class also has the encoder, decoder and getUpdate function to use for training #The decoding weights are NOT transposed versions of the encoding weights from theano.tensor.shared_randomstreams import RandomStreams from theano import tensor as T import numpy as np i...
# Copyright (c) 2016 John Gateley # 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, modify, merge, publish, distribut...
from sqlAlchemy.models.utils.base_db import db from sqlAlchemy.models.utils.database_session import Persistance from sqlAlchemy.models.schema.movies import Movies from sqlalchemy import text class MovieDbOperations: @staticmethod def create(dict_args): #print(dict_args) movies_model_i...
# -*- coding:utf-8 -*- class Solution: def FirstNotRepeatingChar(self, s): # write code here if None == s or 0 == len(s): return -1 occurence = {} keys = [] for i,c in enumerate(s): if c in occurence: occurence[c] += 1 else:...
"""Write GNSS position results Description: ------------ """ # Standard library imports from collections import namedtuple # External library imports import numpy as np # Midgard imports from midgard.data import position from midgard.dev import plugins from midgard.writers._writers import get_field, get_header # ...
#! /usr/bin/env python # usage: python convert_indicators_to_cvs_single <indicator_type> <input_file> <output_file> #indicator type can be: "GO", "EC" (without quotation marks) # converts the indicators to a .cvs file, on a network by network basis import os import sys import csv import networkx as nx #from ..edgeLis...
""" Copyright (c) 2021 ARM Limited SPDX-License-Identifier: Apache-2.0 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 ...
import torch import torch.nn as nn import cv2 import numpy as np # class stepPool(nn.Module): # # def __init__(self,): # # super(stepPool, self).__init__() # # self.set_pool = nn.AvgPool2d(kernel_size=) img = cv2.imread('cat.jpg') img = torch.Tensor(img) img = np.int32(img) cv2.imshow('1',img) cv2...
#indexing assistance name = 0 colour = 1 price = 2 rent = 3 onehouse = 4 twohouse = 5 threehouse = 6 fourhouse = 7 hotel = 8 buildprice = 9 owner = 10 #library a = ['Go'] b = ["Old Kent Rd", "brown", "60", "2", "10", "30", "90", "160", "250", "50", ''] c = ['Community Chest'] d = ['Whitechapel Rd', 'brown', '60', '4',...
# -*- coding=utf-8 -*- # Created Time: 2015年06月26日 星期五 15时03分54秒 # File Name: __init__.py
#1 - Decision Tree on Guiding Question 1 import pandas as pd from sklearn.model_selection import KFold import numpy as np from sklearn.preprocessing import OneHotEncoder from sklearn.preprocessing import scale from sklearn.tree import DecisionTreeRegressor from sklearn.metrics import mean_absolute_error fro...
def main(): a = [] b = [] n = int(input("Informe a quantidade de elementos do vetor: ")) for i in range(n): elemento = input(f"Qual o valor do {i} elemento: ") a.append(elemento) b = a[::-1] print(f"Vetor A = {a}") print(f"Vetor B = {b}") main()
# Generated by Django 2.2.7 on 2019-11-29 22:02 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('sightings', '0004_auto_20191129_2200'), ] operations = [ migrations.AlterField( model_name='squirrel', name='unique_...
import tensorflow as tf from utils import normal_initializer, zero_initializer from layers import ConvLayer, ConvPoolLayer, DeconvLayer import numpy as np flags = tf.app.flags FLAGS = flags.FLAGS class AutoEncoder(object): def __init__(self): # placeholder for storing rotated input images self.in...
# -*- coding: utf8 - *- """Exceptions for tmuxp. tmuxp.exc ~~~~~~~~~ :copyright: Copyright 2013 Tony Narlock. :license: BSD, see LICENSE for details """ class TmuxSessionExists(Exception): """Session does not exist in the server.""" pass class ConfigError(Exception): """Error parsing tmuxp configur...
# -*- coding: utf-8 -*- import json from cgbeacon2.constants import ( BUILD_MISMATCH, INVALID_COORDINATES, NO_MANDATORY_PARAMS, NO_POSITION_PARAMS, NO_SECONDARY_PARAMS, UNKNOWN_DATASETS, ) HEADERS = {"Content-type": "application/json", "Accept": "application/json"} BASE_ARGS = "query?assemblyI...
from django.contrib import admin from game.models import Territory, Lobby, Session, TerritorySession, UserProfile admin.site.register(Territory) admin.site.register(Lobby) admin.site.register(Session) admin.site.register(TerritorySession) admin.site.register(UserProfile)
# -*- coding:utf-8 -*- __author__ = 'gusevsergey' from pytils import dt from coffin import template register = template.Library() @register.filter() def date_inflected(d, date_format): return dt.ru_strftime(unicode(date_format), d, inflected=True)
# Minimize Cost a = [int(x) for x in input().split()] if a[0] < 1 or a[1] < 1 or a[0] > 10e5 or a[1] > 10e5: sys.exit() b = [int(x) for x in input().split()] for i in range(0, len(b)): if b[i] > 10e9 or b[i] < -10e9: sys.exit()