text stringlengths 8 6.05M |
|---|
from braindecode.online.ring_buffer import RingBuffer
import numpy as np
from braindecode.datahandling.preprocessing import exponential_running_mean,\
exponential_running_var_from_demeaned
class StandardizeProcessor(object):
def __init__(self, factor_new=1e-3, eps=1e-4,
n_samples_in_buffer=10000)... |
#! /usr/bin/env python
# -*- coding:utf-8 -*-
__author__ = ["Rachel P. B. Moraes", "Fabio Miranda"]
import rospy
import numpy
from numpy import linalg
#import transformations
from tf import TransformerROS
import tf2_ros
import math
from geometry_msgs.msg import Twist, Vector3, Pose, Vector3Stamped
from ar_track_alvar_... |
import sys
import os
import time
from asignacion_de_residencias import *
if len(sys.argv) != 5:
if len(sys.argv) == 2 and (sys.argv[1] == "-h" or sys.argv[1] == "--help"):
print "\nPara correr el programa se necesitan 4 parametros:\n" \
"\t-1.El nombre del archivo a crearse en la entrada\n" \... |
from django.shortcuts import render
def sample_task(request):
# Save true values of Channels and Functions in session.
request.session['trigger_channel'] = 'Facebook'
request.session['action_channel'] = 'Dropbox'
request.session['trigger_fn'] = 'new_photo_post_by_you'
request.session['action_fn'] ... |
import logging
import sys
import inject
import datetime
sys.path.insert(0,'../../../python')
from model.config import Config
logging.getLogger().setLevel(logging.INFO)
from autobahn.asyncio.wamp import ApplicationSession
from asyncio import coroutine
'''
python3 getWorkedOvertimePeriod.py date1 date2
python3 getWo... |
import getopt
import sys
import os
import tensorflow as tf
def parseArgs():
short_opts = 'hw:u:p:t:c:b:v:'
long_opts = ['work-dir=', 'git-user=', 'git-pwd=', 'tfrecord-save-dir=', 'config-dir=', 'ubuntu-pwd=', 'verbose=']
config = dict()
config['work_dir'] = ''
config['tfrecord_save_dir'... |
# list
kursus = ['masak', 'jahit', 'mengemudi','komputer', 'matematika']
pelajaran = ['matematika', 'bahasa indonesia', 'sejarah','ppkn']
# akses data berdasarkan index pertama
print(kursus[0])
# akses data berdasarkan index terakhir, jika tidak tahu index terakhirnya
print(kursus[-1])
# akses data hanya berdasarkan... |
#coding:utf8
from base.IterativeRecommender import IterativeRecommender
import math
import numpy as np
from tool import qmath
from random import choice
from tool.qmath import sigmoid
from math import log
from collections import defaultdict
from scipy.sparse import *
from scipy import *
class WRMF(IterativeRecommender)... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.2 on 2018-08-06 12:53
from __future__ import unicode_literals
from django.db import migrations, models
import user_input.models
class Migration(migrations.Migration):
dependencies = [
('user_input', '0053_dailyuserinputstrong_activities'),
]
op... |
from abc import ABC, abstractmethod
# Абстрактный класс для проверки синтаксиса
class SyntaxChecker(ABC):
def __init__(self):
super().__init__()
# Проверка синтаксиса, где
# fileName (str) - имя файла
# fileContent (str) - содержимое файла
# start (int) - начало проверяемого участка
... |
from django.conf.urls import url, include
from . import views
urlpatterns = [
url(r'^home/$', views.neighborhood_home, name='home'),
url(r'^status/$', views.neighborhood_status, name='status'),
url(r'^index/$', views.index, name='index'),
url(r'^details/$', views.neighborhood_details, name='details'),
url(r'^get... |
t,x1,y1,x2,y2 = map(int,input().split())
s = str(input())
a = x2 - x1
b = y2 - y1
from itertools import islice
def nth_index(iterable, value, n):
matches = (idx for idx, val in enumerate(iterable) if val == value)
return next(islice(matches, n-1, n), None)
if a > 0 and b > 0:
f = nth_index(s,'E'... |
# Generated by Django 2.0.3 on 2018-04-08 10:59
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('recipes', '0005_auto_20180408_1041'),
]
operations = [
migrations.RemoveField(
model_name='medi... |
from django.contrib.auth.models import User, AbstractUser
from django.db import models
from mptt.fields import TreeManyToManyField
from django.urls import reverse
from listy.models import Category
from django.conf import settings
from django.contrib.auth import get_user_model
#
class ProfilManager(models.Manager):
... |
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import LSTM
from keras.callbacks import EarlyStopping
from sklearn.preprocessing import MinMaxScaler
from sklearn.metrics import mean_squared_error
import os, math
import keras.backend as K
import pandas as pd
import numpy as np
import... |
import models
from django.contrib import admin
from django.contrib.auth.models import User
class CategoryAdmin(admin.ModelAdmin):
prepopulated_fields = {"slug": ("title",)}
class CategoryToPostInline(admin.TabularInline):
model = models.CategoryToPost
extra = 1
class PostAdmin(admin.ModelAdmin):
prep... |
image_height = 594
image_width = 742
resized_image_size = 255 |
import numpy as np
import pandas as pd
from tqdm import tqdm
from src import bbde
from src.experiment_helpers.single_algorithm_stats import calculate_average_results, calculate_average_de_results
def run_experiments_for_cost_function(cost_function, cost_function_name, iterations, bounds, dimensions=10):
populati... |
# -- ------------------------------------------------------------------------------------ -- #
# -- proyecto: Microestructura y Sistemas de Trading - Proyecto Final - Sistema de Trading
# -- archivo: proceso.py - funciones para procesamiento de datos
# -- mantiene: IF Hermela Peña, IF Manuel Pintado
# -- repositorio: h... |
from modules import capitalize
print (capitalize("hello")) |
#! /usr/bin/env python
import argparse
from open_site import open_site
def run(args):
open_site(args.input, args.openBrowser)
def main():
parser = argparse.ArgumentParser(
description="This interface can be used to search through the nature research journal for articles of interest"
)
pars... |
#
# Copyright © 2021 Uncharted Software Inc.
#
# 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 l... |
from rubicon_ml import domain
from rubicon_ml.client import Dataframe
def test_properties(project_client):
parent = project_client
domain_dataframe = domain.Dataframe(
description="some description", tags=["x"], name="test title"
)
dataframe = Dataframe(domain_dataframe, parent)
assert d... |
#!/usr/bin/env python
import sys
import os
import os.path as osp
import numpy as np
from random import randrange, choice
import json
from capsul.api import get_process_instance
# Make sure that python directory is in sys.path
python = osp.join(osp.dirname(osp.dirname(sys.argv[0])), 'python')
if python not in sys.pat... |
from django.shortcuts import render_to_response
from django.template import RequestContext
def e_handler404(request):
context = RequestContext(request)
response = render_to_response('404.html', context.flatten(0))
response.status_code = 404
return response
|
# -*- encoding: ms949 -*-
from sklearn.model_selection import LeaveOneOut
from sklearn.model_selection import cross_val_score
from sklearn.datasets import load_iris
from sklearn.linear_model import LogisticRegression
iris = load_iris()
logreg = LogisticRegression()
loo = LeaveOneOut()
scores = cross_val_score... |
# Generated by Django 3.2.6 on 2021-08-21 15:43
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('nostaldja', '0001_initial'),
]
operations = [
migrations.RenameField(
model_name='fad',
old_name='img_url',
new_... |
from objectBase import ObjectBase
class Lane(ObjectBase):
def __init__(self, id_=None, parent_object=None, lights=None):
super().__init__(id_=id_, parent_object=parent_object)
self.queue = []
self.lights = lights
def is_incoming(self):
return (False if self.outgoing else True)
... |
from django.shortcuts import render
from .models import job
def home(request):
Job = job.objects
return render(request,'jobs/home.html',{"Job":Job})
def app(request):
return render(request,'jobs/app.html')
|
# RachelPotter.py
# A program that changes the lowercase names in a .txt file to uppercase and prints them to a new file
def main():
infile_name = "Before.txt"
outfile_name = "After.txt"
infile = open(infile_name, "r")
outfile = open(outfile_name, "w")
for row in infile:
for letter in row:
... |
from django.db import models
from django.contrib.auth.models import User
from products.models import Products
CHAT_TYPES = (
(0, 'pending'),
(1, 'sent')
)
class Order(models.Model):
user = models.ForeignKey(User)
# shopping_address
city = models.CharField(
max_length=20)
phone = mod... |
import numpy as np
import torch
import torch.nn as nn
import torch.nn.init as init
import torch.nn.functional as F
import math
from torch.autograd import Variable
import torch.utils.model_zoo as model_zoo
class input_data(object):
def __init__(self, G):
self.onehot # Tensor (num_nodes*input_dim) one hot ... |
import numpy as np
import torch
import gym
import torch.nn.functional as F
from termcolor import cprint
from flare.qpolgrad import BaseQPolicyGradient
import flare.kindling as fk
from flare.kindling import ReplayBuffer
from typing import Optional, Union, Callable
from itertools import chain
class TD3(BaseQPolicyGradi... |
# -*- encoding: ms949 -*-
import numpy as np
import matplotlib.pylab as plt
rnd = np.random.RandomState(0)
X_org = rnd.normal(size=(1000, 3))
w = rnd.normal(size=3)
X = rnd.poisson(10 * np.exp(X_org))
y = np.dot(X_org, w)
print(X[:10, 0])
print("feature count:\n{}".format(
np.bincount(X[:, 0].asty... |
# Problem name: Increasing Array
# Description: You are given an array of n integers.
# You want to modify the array so that it is increasing, i.e., every element is at least as large as the previous element.
# On each turn, you may increase the value of any element by one. What is the minimum number of turns requir... |
class Solution:
# @param A : tuple of integers
# @return an integer
def longestSubsequenceLength(self, A):
inc = [1] * len(A)
dec = inc[:]
for i in range(1, len(A)):
for j in range(0, i):
if A[j] < A[i]:
inc[i] = max(inc[i], inc[j] + 1)... |
import requests
from django.db import models
from sources.models import CryptoExchange
class Cryptocurrency(models.Model):
base = models.CharField(max_length=10)
quote = models.CharField(max_length=10)
symbol = models.CharField(max_length=20)
exchange = models.ForeignKey(CryptoExchange, on_delete=model... |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Thu Feb 15 11:54:26 2018
@author: ian
"""
import calendar
import datetime as dt
import matplotlib.pyplot as plt
import numpy as np
import os
import pandas as pd
from scipy.stats import linregress
import pdb
def get_date_from_multi_index(idx):
return ... |
import functions
class Ship:
def __init__(self, bow, horizontal, length):
self.bow = bow
self.horizontal = horizontal
self.length = length
self.hit = [(i, j, False) for j in range(self.bow[1], self.bow[1]+self.length[1])
for i in range(self.bow[0], self... |
# This module wil allow the tester to use log data to run tests and get profiles
import re
import sys
import os
import csv
import datetime
import SimulationObjects as Sim
def readLog(fileName, fileDirectory, graphFlag=False):
# return a list of stepLists
# Metadata of the step lists follows this order:
# (problem,... |
from Deadline.Scripting import *
import json
# This script is for Dealine Online Manager, maintained by elisha.
def __main__(dlArgs, qsArgs):
action = qsArgs.get('action', None)
job_id = qsArgs.get('id', None)
if action is None or job_id is None:
return ('Lacks of parameters', 404)
rep = Rep... |
from reef import database as db
from datetime import datetime
class BookRecord(db.Model):
id = db.Column(db.Integer, primary_key=True)
user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
book_id = db.Column(db.Integer, db.ForeignKey('book.id'), nullable=False)
reader_id = db.Colu... |
import matplotlib.pyplot as plt
import pytorch_lightning as pl
import torch
import torch.nn.functional as F
import torch.nn as nn
import torchvision
from torchvision import transforms
from torch.utils.data import DataLoader, random_split
class TwoLayerNet(pl.LightningModule):
def __init__(self, hparams, input_s... |
from __future__ import unicode_literals
from django.db import models
class Customer(models.Model):
customer_id = models.CharField(max_length=100,primary_key=True)
customer_name = models.CharField(max_length=100)
customer_email = models.CharField(max_length=50)
customer_phone = models.CharField(max_length=10)
cus... |
{
"targets": [
{
"target_name": "addon",
"sources": [ "src/extension.cc" ],
"include_dirs": [
"<!(node -e \"require('nan')\")",
],
"variables": {
"use_pkg_config": "<!(pkg-config --exists libtcmalloc || echo no)"
},
"conditions": [
[ "use_pkg_confi... |
#Longest Common Subsequence
"""LCS Problem Statement: Given two sequences, find the length of longest
subsequence present in both of them. A subsequence is a sequence that appears
in the same relative order, but not necessarily contiguous. For example,
'abc',
'abg', 'bdf', 'aeg', 'acefg', .. etc are subsequence... |
# Generated by Django 3.1.5 on 2021-01-30 16:53
import django.contrib.gis.db.models.fields
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
n... |
# 5-1
# class Carre:
# def __init__(self, cote):
# self.cote = cote
# a = Carre(10)
# print(a.cote)
# class Carre:
# def __init__(self, cote):
# self.unCote = cote
# self.perimetre = self.fctPerimetre()
# self.aire = self.unCote * self.unCote
# def fctPerimetre(self): ... |
"""An Apache Beam bounded source for PostgreSQL"""
from typing import Union
from apache_beam.io import iobase
from apache_beam.options.value_provider import ValueProvider
from postgres_connector.splitters import BaseSplitter
from postgres_connector.client import PostgresClient
from postgres_connector.utils import cl... |
# Day 14: Docking Data
# <ryc> 2021
import re
def inputdata():
stream = open('day_14_2020.input')
data = []
for line in stream:
record = re.findall('(mask) = ([01X]+)|(mem)\[(\d+)\] = (\d+)',line)
if record[0][0] == 'mask':
maskN = 0
maskX = 0
maskv = 0x... |
import os, wget
import zipfile
PLUGINS_PATH = os.path.join(os.environ['APPDATA'], 'Wox', 'Plugins')
plugins_url = [
'http://api.wox.one/media/plugin/E2D2C23B084D41D1B6F60EC79D62CAH6/Wox.Plugin.IPAddress-275940ee-7ada-4a8a-b874-309e6034f39f.wox',
'http://api.wox.one/media/plugin/5C0BFEC0DF7011E695980800200C9A6... |
import sys
n , m = [int(e) for e in input().strip().split()]
v = [int(e) for e in sys.stdin.readline().strip().split()]
w = [int(e) for e in sys.stdin.readline().strip().split()]
V = [[int(e) for e in sys.stdin.readline().strip().split()] for i in range(n+1)]
x = [0 for i in range(n)] ; count = 0
while V[n][m] != 0:
... |
import tkinter
import tkinter.ttk as ttk
import editor
from util_frames import NewGameFrame, LoadGameFrame
from cbs_window import *
from world import world, set_world
from main_frames import PlayerActorFrame, CurrentLocationFrame
import os
import shutil
class Application(ttk.Frame):
def __init__(self, master=None... |
import tarfile
import os
import sys
import pickle
#import tensorflow as tf
from datetime import datetime
from multiprocessing import Pool
import getopt
from itertools import repeat
import psutil
sys.path.append('../../lib/')
import return_type_lib
import common_stuff_lib
import tarbz2_lib
import pickle_lib
#import di... |
import torch
import torch.nn as nn
import torch.nn.init as init
import torch.nn.functional as F
from torch.autograd import Function
def make_vgg(image_size):
layers = []
in_channels = 3 # 色チャネル数
cfg = [ # 層の構造をリストで定義する # 統一でよさそう?
64, 64, 'M',
128, 128, 'M',
256, 256, 256, 'M', #... |
import matplotlib as plt
import pandas as pd
import numpy as np
import sklearn.metrics as metrics
from sklearn.metrics import accuracy_score
from sklearn.metrics import f1_score
from sklearn.metrics import precision_score
from sklearn.metrics import recall_score
from sklearn.model_selection import learning_curve
from s... |
# Helper classes for TMBF control
import cothread
from cothread.catools import *
class TMBF:
def __init__(self, name):
self.tmbf = name
self.s1 = Trigger(self, 'S1')
self.s2 = Trigger(self, 'S2')
self.ext = Trigger(self, 'EXT')
self.saves = {}
def pv(self, name):
... |
from django.urls import path
from .views import ArticleListView, ArticleDetailView
urlpatterns = [
path('list/', ArticleListView.as_view(), name='list_of_articles'),
path('<int:pk>/', ArticleDetailView.as_view(), name='article_detail'),
path()
] |
import cv2
import numpy as np
from matplotlib import pyplot as plt
class Saliency:
"""Generate saliency map from RGB images with the spectral residual method
This class implements an algorithm that is based on the spectral
residual approach (Hou & Zhang, 2007).
"""
def __init__(self, img,... |
import sys, re,time
#from pexpect import *
import sys,os
sys.path.append(os.path.join(os.path.abspath(os.path.dirname(__file__)), 'sharedlib'))
import getpass, re, time
from sharedlib.sitepackages import pexpect
print len(sys.argv)
size = 7
try:
if sys.argv[1] == "-h" or sys.argv[1] == "--help":
print """
... |
import header as h
def add_nodes(g, nodes):
for el in nodes:
g[el]=dict() #add a list of node prom 1 to the max number of nodes
#g.add_nodes_from(list(range(1, h.NUM_VERTEX+1)))#add a list of node prom 1 to the max number of nodes
def add_phisical_distance_edges(g):
with open(h.PATH_DISTANCE, 'r') ... |
"""
This module exposes an endpoint to retrieve stats for the API requests
"""
import json
from flask import Response, Blueprint
from utils import DB
STATS_BLUEPRINT = Blueprint('stats', __name__)
@STATS_BLUEPRINT.route('/api/v1/stats', methods=['GET'])
def stats():
"""
This function returns the API stats
... |
import Common
def getNewNodes(cur, vis):
nodes = []
nodes.append(Node(mod(cur.curState, 'u'), cur, cur.depth +1))
nodes.append(Node(mod(cur.curState, 'r'), cur, cur.depth +1))
nodes.append(Node(mod(cur.curState, 'd'), cur, cur.depth +1))
nodes.append(Node(mod(cur.curState, 'l'), cur, cur.depth +1))... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Dec 12 14:00:59 2017
Code for degrading images
@author: ppxee
"""
### Import required libraries ###
#import matplotlib.pyplot as plt #for plotting
from astropy.io import fits #for handling fits
import numpy as np #for handling arrays
from astropy.convo... |
import os
import threading
# Global Setting for the Database
# PageSize, StartRID, etc..
# Element(byte, byte, byte, byte, byte, byte, byte, '\x00') # 8 "bytes" in one "element" Note that only 7 of the bytes can be written to!
# PhysicalPage(Element, Element, Element, ...) ... |
# File: proj2.py
# Author: Joel Okpara
# Date: 5/9/16
# Section: 04
# E-mail: joelo1@umbc.edu
# Description: Finds words on a word search using the puzzle and word list given
REFERENCE = [-1,0,1] #values used in a dictionary reference system
#inputVal() validates that the user is inputting a .txt file
#Input: A file... |
import functools
import torch
import torch.nn as nn
import torch.optim
from torch.nn import init
from torch.optim import lr_scheduler
def conv3x3(inplanes, outplanes, stride=1):
return nn.Conv2d(inplanes, outplanes, kernel_size=3, stride=stride,
padding=1, bias=False)
def get_norm_layer(la... |
'''
Created on 7 feb. 2014
@author: Pieter
'''
import unittest
from dungeonz.CageBoard import CageBoard
from dungeonz.Cage import Cage, Upgrade
from dungeonz.Petz import Pet
class Test(unittest.TestCase):
def setUp(self):
self.cb1 = CageBoard(1)
self.cb2 = CageBoard(2)
self.cb3 = CageBoar... |
import socket, os
import time
import download_dhaga
#To get ip of current node
x=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
try:
x.connect(("gmail.com",80))
myip=x.getsockname()[0]
except:
print "Client not connected to internet !!!!!"
return
#UDP part
clientSocket = socket.socket(socket.AF_INET, socket.SOCK... |
from datetime import time
from time import sleep
from GUI import *
import Main
from tkinter import messagebox
runGUI()
while (True):
hour = datetime.now().hour
min = datetime.now().minute
day = datetime.now().weekday()
if len(Main.toDoList[day]) == 0:
sleep((24 - hour)*60*60 +(60... |
# Copyright 2023 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import annotations
from textwrap import dedent
import pytest
from pants.backend.visibility.lint import EnforceVisibilityRules, VisibilityFieldSet
from pants.backend.visi... |
"""Utility functions to handle the backpropagation."""
def no_op(*args, **kwargs):
"""Placeholder function that accepts arbitrary input and does nothing."""
return None
|
import json
from django.http import HttpResponse
def ajax_error( etype='DefaultError', description='Internal server error',
additional_data={} ):
msg = {
'reason': etype,
'data': description
}
msg.update( additional_data )
return HttpResponse(
j... |
def remove(text, what):
str = ''
for x in text:
if x in what and what[x]>0:
what[x] -= 1
else:
str += x
return str
'''
Write
remove(text, what)
that takes in a string str(text in Python) and an object/hash/dict/Dictionary
what and returns a string with the chars ... |
"""
Small module containing functionality to make predict for сlassification of objects into stars, quasars and galaxy
"""
import argparse
import json
import joblib
import functools
import glob
import importlib
import os
import multiprocessing
import pickle
import re
import shutil
#import subprocess
import sys
import t... |
print('123')
print('1234g')
print('12341234') |
import pytest
import os
import numpy as np
from .. import utils
from .. import templates
def test_data_path():
"""
Data path
"""
path = os.path.join(os.path.dirname(__file__), '../data/')
assert(os.path.exists(path))
return path
def test_templates_path():
"""
Does ``templates`` path... |
# Define a function that takes an argument. Call the function. Identify what code is the argument and what code is the parameter.
def sentence(st):
# Convert the arguement to a string parameter.
convertedToString = str(st)
# Get parameter length
strLength = len(convertedToString)
# Check i... |
import RPi.GPIO as GPIO
import time
'''
Front Wheel control left and right.
====> 50HZ
0° ---- 0.5ms ---- 2.5%
45° ---- 1.0ms ---- 5.0%
90° ---- 1.5ms ---- 7.5%
135° ---- 2.0ms ---- 10.0%
180° ---- 2.5ms ---- 12.5%
Red ---- +5V ---- GPIO.2
Brown ---- GND ---- GPIO.6
Yellow -... |
#!/usr/bin/python3.4
# -*-coding:Utf-8
test x, y : (x * x) + (y * y)
f = test(3, 2)
print(f)
|
'''
Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.
Notice
Have you consider that the string might be empty? This is a good question to ask during an interview.
For the purpose of this problem, we define empty string as valid palindrome.
Example
"A man... |
#!/usr/bin/python3
''' Module with lookup function'''
def lookup(obj):
"""
Return list with dictionary of the class
"""
return list(dir(obj))
|
"""function to buggy"""
"""calculation "x-1/x"""
def buggyfunc(x):
y = x
for i in range(x):
y = y-1
z = x/y
return z
buggyfunc(20) |
#
# (C) 2013 Varun Mittal <varunmittal91@gmail.com>
# JARVIS program is distributed under the terms of the GNU General Public License v3
#
# This file is part of JARVIS.
#
# JARVIS is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public Licens... |
import matplotlib.animation as animation
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
fig,ax = plt.subplots()
fig.patch.set_visible(False)
ax.axis("off")
def animate(i):
# fig,ax = plt.subplots()
fig.patch.set_visible(False)
ax.axis("off")
#================Cal... |
#! /usr/bin/python3
import codecs
import html.parser
import re
import sqlite3
import urllib.request
class SifParser(html.parser.HTMLParser):
def __init__(self):
super().__init__()
self._tag = [None]
self._table = None
self._record = None
self._records = None
self._data = None
self._rowsp... |
import numpy as np
import matplotlib.pyplot as plt
import math
import csv
import sys
args = sys.argv
data_axis, data_value = np.loadtxt(
"./"+args[1]+".csv", delimiter=',', unpack=True)
#読み込んだ信号の長さ
data_size=len(data_value)
#信号を256個ずつ区切る
r=256
#切り出した信号の個数
M=int(data_size/256)
print("Mは、{}".format(M))
#長... |
import base64
exec(base64.b32decode("EMWS2LJNFUWS2LJNFUWS2LJNFUWS2LJNFUWS2LJNFUWS2LJNFUWS2LJNFUWS2LJNFUWS2LJNFUWS2LJNFUWS2LJNFUWS2LJNFUWS2LJNFUWS2LJNFUWS2LJNFUWS2LJNFUWS2LJNFUWS2LJNFUWS2LJNFUWS2LJNFUWS2LJNFUWS2LJNFUWS2LJNFUWS2LJNFUWS2LJNFUWQUIZAJ5RGM5LTMNQXIZJAIJ4SAU3BPJ4HIICUNBQW423TEBKG6ICCNRQWG2ZAINXWIZLSEBBXE5LTNAF... |
from functools import partial
from typing import Any, Callable, List, Optional
import torch
import torch.nn as nn
from torch import Tensor
from ..transforms._presets import ImageClassification
from ..utils import _log_api_usage_once
from ._api import register_model, Weights, WeightsEnum
from ._meta import _IMAGENET_C... |
from django.db import models
from django.contrib.auth.models import User
from questions.managers import QuestionManager
from django.conf import settings
# Create your models here.
class TimeStamp(models.Model):
"""
Reusable Abstract Timestamp Model Class.
"""
created_at = models.DateTimeField(auto_no... |
import serial
from datetime import datetime
import json
with open('input.json') as doc:
data = json.load(doc)
U_ID = int(data['u_id'], 16)
#ser = serial.Serial('/dev/tty.usbserial-A601D97W') #For Mac
ser = serial.Serial('/dev/ttyUSB0') #For RPi
def connect(params):
mode = params[0]
dev_id = hex(... |
# -*- coding: utf-8 -*-
"""
Spyder Editor
This is a temporary script file.
"""
import matplotlib.pyplot as plt
from matplotlib.widgets import Slider
import numpy as np
def calc_base(mb,mbc,opbs,opbe,opbc,bid_step,alpha):
x = np.arange(opbs,opbe,bid_step)
y = (x*opbc +mb*mbc)/(mbc+opbc)
y = (y*0.6 +... |
def sort_array(source_array):
odd = []
for i in range(len(source_array)):
if source_array[i] % 2 == 1:
odd.append(source_array[i])
source_array[i] = "n"
odd.sort()
index = 0
for v in range(len(source_array)):
if source_array[v] == "n":
source_array[... |
import modelClass
#from bayes_opt import BayesianOptimization
import GPyOpt
def main():
dataModel = modelClass.modelClass()
dataModel.loadDataSequence()
domain = [{'name': 'nCNN','type':'discrete','domain':tuple(range(1,6))},
{'name': 'nDense','type':'discrete','domain':tuple(range(0,3... |
import pandas as pd
import numpy as np
import os
# Import models
from sklearn.linear_model import LogisticRegression
from sklearn.tree import DecisionTreeClassifier
from sklearn.neighbors import KNeighborsClassifier
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis
from sklearn.naive_bayes import G... |
#!/usr/bin/env python
def fib(x):
if type(x) != 'int':
raise "Integer required"
if x < 0:
raise "Negative values are not allowed"
if x in [0, 1]:
return 1
return fib(x - 1) + fib(x - 2)
def iter_fib(x):
prev = [0, 0]
for i in xrange(0, x):
if i == 0:
... |
from django.views.generic import TemplateView
from django.shortcuts import render
from django.core.serializers import serialize
from django.http import HttpResponse
from .models import Stations
class HomePageView(TemplateView):
template_name = 'stations/index.html'
def stations_dataset(request):
stations = ... |
from _typeshed import Incomplete
def maximal_independent_set(
G, nodes: Incomplete | None = None, seed: Incomplete | None = None
): ...
|
# -*- coding: utf-8 -*-
class Solution:
def countSubstrings(self, s):
return sum((el + 1) // 2 for el in self.manachersAlgorithm(s))
def manachersAlgorithm(self, s):
c, r = 0, 0
s = "^#" + "#".join(s) + "#$"
p = [0] * len(s)
for i in range(1, len(s) - 1):
... |
# -*- coding:utf-8 -*-
from zope.interface import implements, Interface
from zope.component import getUtility, getMultiAdapter
from sc.newsletter.creator.tests.base import TestCase
from Products.PloneTestCase.setup import default_user
from DateTime import DateTime
class DummyEvent(object):
implements(IObjectEve... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.