text
stringlengths
38
1.54M
import numpy as np import Memory import DDPG_Agent import utils import gym import torch def main(): env = gym.make('MountainCarContinuous-v0') ram = Memory.MemoryBuffer(1000) agent = DDPG_Agent.DDPGAgent(env.observation_space, env.action_space, ram) steps_done = 0 episode_reward = [] for epoch in range(1...
# -*- coding: utf-8 -*- __author__ = 'jayin' def is_markdown_file(filename=''): """ 判断给定的文件名是否是markdown文件 """ if filename.endswith('.md') or filename.endswith('.markdown'): return True return False def read_file(file_path): """ 读取文件 :param file_path: 文件路径 :return: string ...
def main(): #minvals = [10000 for i in range(99)] #with open("output.txt") as out: # lines = out.readlines() # for linen in lines: # line = linen.split(",") # if len(line) >= 2: # if (len(line[0].split(":")) == 2 and len(line[1].split(":")) ==2 ): # ...
import threading import functools """本地异步任务装饰器, 用Thread类进行简单封装,执行中等耗时CPU任务,不带线程列队,执行完毕自动回收, 由于没有线程管理,短时间创建大量线程会增加进程管理负担,影响执行效率,所以不可频繁调用""" def runTask(func): @functools.wraps(func) def wrapper(*args, **kwargs): thread = threading.Thread(target=func, args=args, kwargs=kwargs) thread.start() ...
from rolepermissions.roles import AbstractUserRole class AddUsers(AbstractUserRole): available_permissions = { 'create_new_user': True, } class Loans(AbstractUserRole): available_permissions = { 'approve_loan_application': True, }
from django.contrib import admin from django import forms from django.contrib.auth.models import User from core.models import DashboardUser class DashboardUserForm(forms.ModelForm): first_name = forms.CharField(max_length=200) last_name = forms.CharField(max_length=200) username = forms.CharField(max_leng...
def whichwayold(): # In a real system we would have a linked table containing exits # For this flat file demo, we have a kludge to work out if there # is a valid exit for the adventurer to go chosenExit = ["", None] response = input("Which way ? ") response = response[:1].capitalize() if res...
import math as mt micro_0 = 4*mt.pi*pow(10,-7) t1 = 42 micro = 1*pow(10,-6) rho_0 = 4.9 phi = 12*mt.pi/180 l = 2.9 electric_flow2 = 3*micro/micro_0 * mt.tan(phi)*l*rho_0 print(f"I = {electric_flow2} A") a = 0.03 b = 0.06 c = 0.15 magnetic_flow_2 = (micro_0*t1/(3*a))*(pow(a,3) - pow(c,3) + pow(b,3))*((pow(b,4) - po...
import tempfile import isi.hw.check.lib.log as loglib import isi.hw.check.lib.misc as misc import isi.hw.check.lib.net as netlib import isi.hw.check.lib.nettest as nettestlib # jcc start import sys import signal import time import isi.hw.check.mfg.consts as consts start_time = time.time() abs_starttime = start_time c...
from typing import List class Solution: def sortedSquares(self, A: List[int]) -> List[int]: B = sorted(A, key = abs) # sort by absolute values res = list() for elem in B: res.append(elem*elem) return res # below is testing sol = Solution() print(sol.sortedSquare...
# -*- coding: utf-8 -*- # Generated by Django 1.11.7 on 2018-12-20 12:29 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('hostmanager', '0021_auto_20181220_1149'), ] operat...
# Steve Ivy <steveivy@gmail.com> # http://monkinetic.com from random import random from socket import socket, AF_INET, SOCK_DGRAM class StatsdClient(object): SC_TIMING = "ms" SC_COUNT = "c" SC_GAUGE = "g" SC_SET = "s" def __init__(self, host='localhost', port=8125): """ Sends stat...
# Pattern Problems rows = 7 columns = 7 print("# --- Left Triangle --- #") for row_index in range(rows): for column_index in range(columns): if column_index <= row_index: print("*", end="") else: print(" ", end="") # Moving the cursor to next row print() """ # Output...
# Generated by Django 2.2.5 on 2019-10-20 10:00 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('wiki', '0007_auto_20191016_2104'), ] operations = [ migrations.AlterField( model_name='wikipage', name='display_inde...
import math name=str(input()) #Here enter the name of the person agent=int(input()) #Here enter count of the available agents at the moment others=str(input()) #Here enter the all others' names others=others.split(" ") others.append(name) others.sort() index=others.index(name) place=index+1 line=math.ceil(place/age...
class Solution: # @param A, a list of integers # @return an integer def trap(self, A): length = len(A) if length < 2: return 0 count = 0 start = -1 pos = 0 while pos<length: if A[pos] > 0 : start = pos ...
class Persona(object): def __init__ (self, nombre, apellido, fecha_de_nacimiento, dni, direccion ): self.nombre = nombre self.apellido = apellido self.fecha_de_nacimiento = fecha_de_nacimiento self.dni = dni self.direccion = direccion def __str__ (self): return ...
from distutils.core import setup, Extension hello_module = Extension('pokereplay', sources=['pokereplay.cpp']) setup(name='pokereplay', version='0.2.0', description='Hello world module written in C++', ext_modules=[hello_module])
import logging from enso.contrib.scriptotron.tracebacks import safetyNetted from enso.contrib.scriptotron.events import EventResponderList class GeneratorManager(object): """ Responsible for managing generators in a way similar to tasklets in Stackless Python by iterating the state of all registered g...
# -*- coding: utf-8 -*- from Analyze import DataProcess as DP import pandas as pd import DataInter as DI def batch_etf(etflist,cyclelist): stragegyname = 'etfMonitor' dataset = 'etfs' tradeCycle = '' filepath = DP.get_stragegy_filepath(stragegyname,dataset,tradeCycle) colNames = ['code', 'tradeCyc...
from allauth.socialaccount.providers.facebook.views import FacebookOAuth2Adapter from dj_rest_auth.registration.views import SocialLoginView from dj_rest_auth.views import UserDetailsView from users.serializers import UserMeSerializer class FacebookLogin(SocialLoginView): adapter_class = FacebookOAuth2Adapter ...
from math import exp def discount_factor_observed_at(observation_date, valuation_date, maturity, k, sigma, reference_curve): """ :param observation_date: :param valuation_date: :param maturity: :param k: Mean Reversion Rate :param sigma: :param reference_cur...
#!/usr/bin/env python # encoding: utf-8 ''' @author: zst @file: Locatation_curve_prediction.py @date 2019-09-18 15:59 @desc: ''' import numpy as np from sklearn.preprocessing import PolynomialFeatures import joblib def prediction(LactationNumber, database): # 305预测 X = np.arange(1, 306)[:, np.newaxis] ...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import sys sys.path.insert(1, '../../') from webserver.allinone_backend import launch_all_in_one_backend launch_all_in_one_backend()
#!/usr/bin/python3 ''' This is the '5-hbtn_header.py' module. 5-hbtn_header takes in a URL, sends a request to the URL and displays the value of the variable X-Request-Id in the response header. Assignment Requirements: * You must use the packages requests and sys * You are not allow to import other packages than re...
try: file = open("lista.txt", 'r+') print(open("lista.txt", 'r+').read()) except IOError: file = open("lista.txt", 'w') students = [] t = '' while t != 'K': t = input("Podaj liste studentow: [koniec: K ]") students.append(t) students = students[:len(students)-1] if file.mode == 'w': for line in ...
#!/usr/bin/env python3 import os import random from typing import List CONFIG_FILE = os.path.expanduser("~/.ssh/config") def make_suffix_list(min: int, max: int) -> List[str]: out = [] for i in range(min, max + 1): out.append(str(i)) return out NO_SUFFIX = [""] SERVERS = { # # Off-C...
#You are given an n x n 2D matrix representing an image. # #Rotate the image by 90 degrees (clockwise). # #Follow up: #Could you do this in-place? class Solution(object): def rotate(self, matrix): """ :type matrix: List[List[int]] :rtype: void Do not return anything, modify matrix in-place instead. """ l...
from random import randint, uniform,random def nuevabanda(): r = randint(5,10) instrumentos = ["Guitarra","Bajo","Piano","Maracas","Flauta","Acordeon","Gaita","Guacharaca","Llamador","Bateria"] banda = [] for i in range(0,r): ins = randint(0,9) obj =instrumentos[i...
import random import os import torch from torch import nn import numpy as np import pandas as pd from torch_geometric.utils import remove_self_loops from rdkit import Chem from rdkit.Chem.Scaffolds import MurckoScaffold # binary class class FocalLoss(nn.Module): def __init__(self, gamma=2, alpha=0.25): s...
# test_fixture.py import pytest import os import smtplib # yield - Teardown @pytest.fixture def make_directory_and_txt_file_yield(): directory_name = "/data/" directory_path = os.getcwd()+directory_name try: if not(os.path.isdir(directory_path)): os.makedirs(os.path.join(directory_path...
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Date : 2017-09-27 9:02:49 # @Author : kangvcar (kangvcar@126.com) # @Link : http://www.github.com/kangvcar/ import ssl from selenium import webdriver def Start(url): # 取消证书认证 ssl._create_default_https_context = ssl._create_unverified_context() # 调用P...
#!/usr/bin/env python import socket import ssl import sys TCP_IP = '127.0.0.1' TCP_PORT = 8888 BUFFER_SIZE = 1024 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) s.connect((TCP_IP, TCP_PORT)) ss = socket.ssl(s) print ss.read(52-15) while 1: send = '' send = raw_input("What to send: ") +...
import os import asyncssh from app.utility.base_world import BaseWorld class Tunnel(BaseWorld): def __init__(self, services): self.name = 'ssh_tunneling' self.description = 'Accept tunneled SSH messages' self.log = self.create_logger('tunnel_ssh') self.services = services ...
import sys, os PROJECT_ROOT = os.path.dirname(__file__) # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) MONGODB_DATABASES = { # 'default': {'name': 'ftlcopy'} 'default': {'name': 'ftlcopy', 'host': '52.77.232.185', 'po...
""" Base class """ import numpy as np class Baseset: """ Base class """ def __init__(self, *args, **kwargs): self._index = self.build_index(*args, **kwargs) self.train = None self.test = None self.validation = None self._iter_params = None self.reset_iter() ...
from setuptools import setup, find_packages setup( name = "django-test-utils", version = "0.3", packages = find_packages(), author = "Eric Holscher", author_email = "eric@ericholscher.com", description = "A package to help testing in Django", url = "http://github.com/ericholscher/django-tes...
""" Linearly interpolated EOSs from tabulated values. Tabulated values are copied from Norbert Wex's java code, with three columns - rho: g/cm^3 - p: erg/cm^3 (g/s^2/cm) - energy density / c^2: g/cm^3 """ __author__ = "Lijing Shao" __email__ = "Friendshao@gmail.com" __license__ = "GPL" import numpy...
#!/usr/bin/python # -*- coding: utf-8 -*- #; Copyright 2016 <Benne> #; https://github.com/Ro0x2A/ #; Creation date [11.06.2016] import smtplib class Mailer(object): def __init__(self, server, port, usr, pwd='', debug=False): self.smtp = None self.server = server self.port = int(p...
from typing import AsyncGenerator from uuid import uuid4 from api.repositories.base_repository import BaseRepository class BucketRepository(BaseRepository): @property def collection_name(self) -> str: return 'bucket' async def upload_async(self, file: bytes) -> str: user_id = str(uuid4(...
import sys from multiprocessing.pool import Pool as Pool import requests from requests.adapters import HTTPAdapter from tqdm import tqdm from sec_helpers import _fetch_helper import multiprocessing def download_10ks(cik_list_path, output_path): adapter = HTTPAdapter(max_retries=10) s = requests.Session() ...
import netket as nk import time # 1D Lattice L = 20 g = nk.graph.Hypercube(length=L, n_dim=1, pbc=True) # Hilbert space of spins on the graph hi = nk.hilbert.PySpin(s=0.5, graph=g) # Ising spin hamiltonian ha = nk.operator.Ising(h=1.0, hilbert=hi) # RBM Spin Machine alpha = 1 dtype = complex ma = nk.machine.RbmSpi...
class Solution: # @return an integer #just like 3-sum,O(n^2) times #need to mark the cloest result def threeSumClosest(self, nums, target): nums.sort() result=nums[0]+nums[1]+nums[2] for i in range(len(nums)-1): lo,hi=i+1,len(nums)-1 while(lo<hi): ...
import os import sys import time import random import re import json import pickle import pandas as pd import seaborn as sns import matplotlib.pyplot as plt import numpy as np from sklearn.manifold import TSNE from collections import defaultdict if __name__ == "__main__": folders = [d for d in os.listdir("....
#coding=utf-8 #Exercise: Implement the sigmoid function using numpy. #Instructions: x could now be either a real number, a vector, or a matrix. The data structures we use in numpy to represent these shapes (vectors, matrices…) are called numpy arrays. You don’t need to know more for now. import numpy as np def sigm...
import lasagne from lasagne.layers import InputLayer from lasagne.layers import DenseLayer,DropoutLayer from lasagne.layers import ConcatLayer from lasagne.layers import NonlinearityLayer from lasagne.layers import GlobalPoolLayer from lasagne.layers.dnn import Conv2DDNNLayer as ConvLayer from lasagne.layers.dnn import...
from pathlib import Path from typing import Any, Callable, Optional, Tuple import pandas as pd import torch import torch.nn.functional as f import PIL from torch.utils.data import Dataset class CelebA(Dataset): ''' CelebA PyTorch dataset The built-in PyTorch dataset for CelebA is outdated. ''' b...
from repository.jucator_repository import exceptie_repo from domain.jucator_validare import exceptie_jucator class MeniuBaschet: def __init__(self, srv): self.__srv = srv def __adauga_jucator(self): nume = input("Introduceti nume: ") prenume = input("Introduceti prenume: ") in...
import fabric.api def _marker(marker): return ' # MARKER:%s' % marker if marker else '' def _get_current(): with fabric.api.settings(fabric.api.hide('warnings', 'stdout'), warn_only=True): output = fabric.api.run('crontab -l') return output if output.succeeded else '' def crontab_set(content): """ Sets cronta...
import numpy as np import pandas as pd from sklearn.metrics import confusion_matrix,accuracy_score dataset = pd.read_csv('practice.csv') dataset.head() X = dataset.iloc[:, 4:].values Y = dataset.iloc[:, 3].values from sklearn.cross_validation import train_test_split X_train, X_test, Y_train, Y_test = train_test_split(...
from stacker.blueprints.base import Blueprint from troposphere import Ref from troposphere_mate import Output import troposphere_mate.ec2 as ec2 class Vpc(Blueprint): VARIABLES = { "CidrBlock": { "type": str, "description": "Vpc CidrBlock" }, "PublicSubnets": { ...
# Copyright (c) 2014-2017, iocage # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted providing that the following conditions # are met: # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and th...
from django.conf.urls import url from . import views urlpatterns = [ url(r'^add/$', views.AddProduct.as_view()), url(r'^list/(?P<company_id>\d+)/$', views.GetProducts.as_view()), ]
from django.contrib import admin from .models import * class ProductAdmin(admin.ModelAdmin): readonly_fields = ('id',) class TechnologyAdmin(admin.ModelAdmin): readonly_fields = ('id',) class CasestudyAdmin(admin.ModelAdmin): readonly_fields = ('id',) class CaseGroupAdmin(admin.ModelAdmin): readonly...
import trimesh import numpy as np import slam.curvature as get_curvatures if __name__ == '__main__': # Generate a sphere mesh = trimesh.creation.icosphere() # Show th sphere mesh.show() # Calculate Rusinkiewicz estimation of mean and gauss curvatures PrincipalCurvatures, PrincipalDir1, PrincipalDir2 = get_...
def placar(pontos): print(" _________________________________") print("| |") print("| ROBO: {:^24} |".format(pontos[0])) print("| VOCÊ: {:^24} |".format(pontos[1])) print("|_________________________________|")
''' return the kth last element of a list ''' from llist import createRandomList def getKthLastElem(inList, k): ''' return the kth last element of inList (linked list) ''' fwd, back = inList.head, inList.head for _ in range(k): if fwd is None: raise IndexError("list index -%s o...
from twisted.internet import protocol from twisted.protocols.basic import LineReceiver class ICUProtocol(LineReceiver): def __init__(self, factory, conok_callback=None, rcv_callback=None): self.factory = factory self.conok_callback = conok_callback self.rcv_callback = rcv_callback def connectionMade(self): ...
import serial , time uart = serial.Serial('/dev/cu.usbmodem141103',115200,timeout=0)#acm0 or acm1 uart.close() uart.open() #uart.write('AE'.encode()) inTempIdx = 0 inHumIdx = 1 outTempIdx = 2 outHumIdx = 3 soilMoisureIdx = 4 fanStateIdx = 5 pumpStateIdx = 6 lightStateIdx = 7 stateFromSTM = [0 for i in range(8)] u...
import numpy as np import re from collections import Counter,defaultdict, deque import itertools from string import ascii_uppercase, ascii_lowercase from copy import deepcopy from blist import blist data = open('input').read().strip().split(',') dists = [] def get_dist(data): counts = Counter(data) reduced = {...
# Define your item pipelines here # # Don't forget to add your pipeline to the ITEM_PIPELINES setting # See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html # useful for handling different item types with a single interface from itemadapter import ItemAdapter import sqlite3 import os import scrapy from sc...
# -*- coding: utf-8 -*- """ Copyright 2015 Creare 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...
import mysql.connector from mysql.connector import errorcode class Translator(): def __init__(self): self.host="" self.user="" self.database="" # connection self.connection = None self.cursor = None def connect(self, host, username, password, db): try: ...
import os import torch.nn as nn import torch import numpy as np import sys from tqdm import tqdm from .BaseModel import BaseModel from .networks.darknet import Darknet from .networks.darknet_reg import Darknet_reg from .loss.RegionLoss import RegionLoss, RegionLoss_1Class, RegionLoss_1Class_reg from .loss.HPOLoss impo...
import sys from collections import deque from bisect import bisect_left, bisect_right # input = sys.stdin.readline N = int(input()) numbers = list(map(int, input().split())) # numbers.reverse() dp_table = [1]*(N+1) include =[numbers[0]] max_value = numbers[0] print(numbers) print(include) for i in numbers : add = ...
import numpy as np import sys if sys.version[0] == 2: range, input = xrange, raw_input for t in range(int(input())): B, M = map(int, input().split()) all_state = 2**(B*(B-1)//2) for state in range(all_state): A, AA = np.array([[0] * B for _ in range(B)]), np.array([[0] * B for _ in range(B)]) ...
""" Model validation and loader. Validate a captcha model or a query model and load the model. Available functions are load_captcha_model and load_query_model. Models are loaded based on their filenames. """ from .util.check import type_check, range_check def load_captcha_model(filename): """ Load a captcha...
from django.db import models from django.contrib.sitemaps import ping_google # Create your models here. class BigCategory(models.Model): name=models.CharField(max_length=200) created_at=models.DateTimeField(auto_now_add=True) def __str__(self): return self.name def get_latest_post(self): ...
#!/usr/bin/python3 # -*- coding:utf-8 -*- import numpy as np from IPython import embed from softmax import Softmax from crossentropy import CrossEntropy class Softmax_CE: def forward(self, x, target): exp_vec = np.exp(x) self.pred = exp_vec / exp_vec.sum() self.target = target re...
import tornado.web from handler.base_handler import BaseHandler from model.models import * class IndexHandler(BaseHandler): def get(self): try: terms = self.db.query(Term).all() print(terms[0].term_id) self.render("home.html",terms=terms,pager=None,talks_new=None, pos...
from multiprocessing import Pool import models from functools import reduce import numpy as np from operator import itemgetter import heapq import random import matplotlib.pyplot as plt from networkx.drawing.nx_agraph import graphviz_layout, to_agraph from copy import deepcopy import seaborn as sns #import pygraphviz a...
""" Convenience wrapper around the Python world of json encoding and decoding, looking for the fastest library implementation first and then falling back to stdlib if necessary. """ from __future__ import absolute_import from sockjs.tornado.log import core as LOG try: import simplejson as json LOG.debug("so...
#!/usr/bin/python """Generate html for waveforms.""" import os from optparse import OptionParser audio_template = '<audio src="%s" controls="controls">Audio Tag not supported.</audio>' html_head = '<!DOCTYPE HTML>\n<html>\n<body>\n' html_end = '</body>\n</html>\n' table_head = '<table border="1">' table_end = '</t...
#!/usr/bin/python3 import sqlite3 import sys import re if len(sys.argv) != 3: print("Usage: ./toprank Genres MinRating") sys.exit(1) genres = set([x.lower() for x in sys.argv[1].split("&")]) score = float(sys.argv[2]) # print(genres, score) query = f""" SELECT m.id,m.title, m.content_rating,m.lang,m.yea...
import numpy as np import matplotlib.pyplot as plt import json import sys SMALL_SIZE = 15 MEDIUM_SIZE = 20 LARGE_SIZE = 30 def load_data(filepath): with open(filepath,'r') as f: data = json.load(f) return data def load_folder(foldername, namebasis, N_exp): # load experiment folder exp_list =...
##write a logic to check wether given number is happy number or not ##a number is said to be happy if it yields 1 or 7 when replaced by the sum of squares of itd digit repeatedly.if this process ##results in an endless cycle of number containing any single digit other than 1 or 7 ##then the number will b an unhappy ...
import sys from typing import Collection, Tuple, Optional, Union import pandas as pd import numpy as np from scipy.sparse import issparse from anndata import AnnData from . import _simple as pp from . import _highly_variable_genes as hvg from ._utils import _get_mean_var from sklearn.utils.extmath import safe_sparse_d...
# Middle Function # Write a function called middle that takes a list and returns a new list # that contains all but the first and last elements. my_list = [1,2,3,4] # Ex: middle(my_list) >> returns [2,3] def middle(list): return list[1:-1]
""" https://leetcode.com/problems/valid-mountain-array/ """ A = [0, 3, 2] class Solution: def validMountainArray(self, A: List[int]) -> bool: peak_right = True peak_left = True if len(A) >= 3: peak = max(A) index = A.index(peak) ...
from app import app from flask_wtf.csrf import generate_csrf # 调用函数生成 csrf_token @app.after_request def after_request(response): # 调用函数生成 csrf_token csrf_token = generate_csrf() # 通过 cookie 将值传给前端 response.set_cookie("csrf_token", csrf_token) return response
import time def sing(): for x in range(1,6): print('我在唱最炫民族风') time.sleep(3) def dance(): for x in range(1,6): print('我在跳广场舞') time.sleep(2) def main(): sing() dance() if __name__ == '__main__': main()
import sys sys.stdin = open("D6_10806_input.txt", "r") import heapq T = int(input()) for test_case in range(T): N = int(input()) A = list(map(int, input().split())) K = int(input()) h = [] heapq.heappush(h, (0, K)) while h[0][1]: x, y = heapq.heappop(h) heapq.heappush(h, (x + y...
import numpy as np import matplotlib as plt import pandas as pd from minisom import MiniSom from matplotlib import pylab from pylab import bone,pcolor,colorbar,plot,show row_data = pd.read_csv('heart.csv') X = row_data.iloc[:,:-1].values Y = row_data.iloc[:, -1].values # print(row_data) # print(X) som = MiniSom(x=5...
import pandas as pd import graphviz from datetime import datetime #initialize D graph of Graphviz d = graphviz.Digraph(filename='rank_same.gv') #Load case time model dataframe case_data = pd.read_excel("case_longitudinal_view.xlsx") print(case_data.columns) case_focus = case_data[case_data["CaseID"]=="CS0072591"] ...
import sys class Hanoi: def __init__(self, N, verbose = False): if (N > 0): self.number = N else: raise ValueError("Wrong number of disks!") self.peg = [list(reversed(range(self.number + 1))), [], []] self.peg[0].remove(0) self.display() self.showEachMove = verbose self.numberOfMoves = 0 self.r...
# -*- coding:utf-8 -*- import sys reload(sys) sys.setdefaultencoding('utf-8') # from mysql import connector # from MySQLdb import connect from contextlib import contextmanager from .items import QuestionItem, AnswerItem from .config import DB_CONFIG, QUESTION_TABLE, ANSWER_TABLE #add by lucas # -*- coding:utf-8 -*- #...
import csv dimension = 16 actors_mapping = {} contacts_ids_mapping = {} def create_actors_mapping(): a_id = 0 with open('florentine-actors.csv') as f: lines = f.readlines() for line in lines: line = line.replace('\n', "") # [0:len(line)-1] print(line) acto...
def bubble_sort(items): '''Return array of items, sorted in ascending order''' index = len(items) - 1 while index >= 0: for i in range(index): if items[i] > items[i + 1]: items[i], items[i + 1] = items[i + 1], items[i] index -= 1 return items def merge(list1,...
import matplotlib.pyplot as plt import pandas as pd import numpy as np import numpy sonar = pd.read_csv("Sonar_Detection.csv") sonar.dropna(how='all', inplace=True) sonar = sonar.plot(kind='scatter', x='Species', fontsize=9, y='Count', marker = 'o', s=14, alpha=0.73, color='Blue') #s=marker size median = ...
""" Reference implementation of a two-level RCN model for MNIST classification experiments. Examples: - To run a small unit test that trains and tests on 20 images using one CPU (takes ~2 minutes, accuracy is ~60%): python science_rcn/run.py - To run a slightly more interesting experiment that trains on 100 images...
import numpy as np from PIL import Image import matplotlib.pyplot as plt img = np.array(Image.open("/home/nikky/Downloads/50TPancard.jpg")) h, w, d = img.shape newImage = np.zeros((h, w, d), dtype=np.uint8) for i in range(1, h-1): for j in range(1, w-1): r, g, b = img[i-1, j-1] listV = [r, g, b]...
from flask import * from flask_mysqldb import MySQL import hashlib import random from blockchain import block, blockChain import os import threading app = Flask(__name__) app.secret_key = os.urandom(24) app.config['SESSION_COOKIE_HTTPONLY'] = False mysql = MySQL(app) # MySQL configurations mysql.app.config['MYSQL_US...
""" Script to extract features from pre-trained CNN and optimize and train a Linear SVC on top of extracted features. :args model_name: Name of the pre-trained CNN to use; one of alexnet, vggnet :args gpu: Flag to indicate if CPU or GPU mode should be used; 0 = CPU, 1 = GPU :args mode: Indicator for running script in ...
def findOrgs(invData): doc = nlp(str(invData)) #matches = matcher(doc) tokens=[t.text for t in doc] j=[t.i for t in doc if t.text.lower() in ['party:-','to']] k=[t.i for t in doc if t.text.lower() in ['particulars','description']] if len(j)>0: part1=' '.join(tokens[0:j[len(j)-1]]) ...
# For question go to: # https://www.hackerrank.com/challenges/between-two-sets/problem n, m = list(map(int, input().split())) n_a = list(map(int, input().split())) m_b = list(map(int, input().split())) countInt = 0 iter = 1 while iter <= 100: if all(iter % num1 == 0 for num1 in n_a): if all(num2 % iter =...
from django.contrib import admin from .models import Member, Profile # Register your models here. class ProfileInline(admin.StackedInline): model = Profile class MemberAdmin(admin.ModelAdmin): inlines = [ProfileInline] admin.site.register(Member, MemberAdmin)
import random from dataclasses import dataclass, field from mvc_game import Game @dataclass class ConjugateArticle(Game): '''Decline the correct form of the article for a noun, given case.''' name: str = 'Conjugate the Article' instruction: str = field(init=False) example: str = '(der) Frau - accusa...
from osv import osv, fields class course_create(osv.osv_memory): _name = 'obuka.course.create' _description = 'Create courses' _columns = { 'course_number': fields.integer('Number of courses', required=True), 'instructor_id': fields.many2one('res.partner', 'Instructor', required=True) ...
"""pmprj URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.8/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based...
# ssh -p2221 student@149.156.197.221 # sftp -P2221 student@149.156.197.221 from __future__ import division from __future__ import print_function import time import os from usbtmcDevice import UsbtmcDevice d_path = 'figs/' # connect to instruments dev_scope = UsbtmcDevice('/dev/usbtmc0') id = dev_scope.ask('*idn?')...