text stringlengths 38 1.54M |
|---|
import os
from ruamel.yaml import YAML
from itertools import combinations
import pprint
# YAML
yamlDrawings = YAML(pure=True)
# pprint
pp = pprint.PrettyPrinter(compact=True)
# Combinations
simples = combinations(range(1,50), 1)
doubles = combinations(range(1,50), 2)
triples = combinations(range(1,50), 3)
quadru... |
from flask import Flask, request, flash, url_for, redirect, render_template
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy.orm import relationship
#import config
app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///datos.sqlite3'
app.config['SECRET_KEY'] = "random string"
app.co... |
# To be included in pyth.py
class PythParseError(Exception):
def __init__(self, active_char, rest_code):
self.active_char = active_char
self.rest_code = rest_code
def __str__(self):
return "%s is not implemented, %d from the end." % \
(self.active_char, len(self.rest_code... |
#-*- coding: UTF-8 -*-
class TrackableObject:
def __init__(self, objectID, centroid):
# 存储目标ID
self.objectID = objectID
# 形心列表 存储在整个过程中该目标所有的形心位置
self.centroids = [centroid]
# 是否被计数器统计过的布尔量
self.counted = False |
## Calculate feature importance, but focus on "meta-features" which are categorized by
## rules from different perspectives: orders, directions, powers.
## for "simple methods"
from util_relaimpo import *
from util_ca import *
from util import loadNpy
def main(x_name, y_name, method, divided_by = "", feature_names =... |
# Locations of the database and csv files
data_root = '/fill/this/in'
airport_list_loc = '/fill/this/in/too/airports.csv/airports.csv'
|
#%%
"""
Analysis of a 6-pulse DQC signal with multiple dipolar pathways
-------------------------------------------------------------------------
Fit an experimental 6-pulse DQC signal with a model with a non-parametric
distribution and a homogeneous background, using Tikhonov regularization.
The model assumes three... |
# all data going to /glusterfs/users/metaknowledge/rawdata
import codecs # used for creating output file
import re # used for parsing timeout errors and resumptionTokens
import time # to be used for sleeping
import urllib2 # used for fetching data
import zlib # used for checking compression levels
nD... |
from tkinter import *
root=Tk()
root.geometry("400x170+100+100")
label_1=Label(wraplength=400,text='The N category describes spread only to the lymph nodes near the bladder (in the true pelvis) '
'and those along the blood vessel called the common iliac artery. These lymph nodes are ca... |
from django import forms
from .models import JoinEvent
from django.views.generic import DetailView
class JoinEventForm(forms.ModelForm):
class Meta:
model = JoinEvent
fields = ('event_id', 'f_name', 'l_name', 'email', 'mobile')
labels = {
'event_id': 'Event Name',
'f... |
"""
Matplotlib styles
=================
_thumb: .8, .8
_example_title: Matplotlib styles for ArviZ
"""
import matplotlib.pyplot as plt
import numpy as np
from scipy import stats
import arviz as az
x = np.linspace(0, 1, 100)
dist = stats.beta(2, 5).pdf(x)
style_list = [
"default",
["default", "arviz-colors"]... |
#written by Bernard Crnković
from datetime import time
from datetime import date
from datetime import datetime
from aes_implementation import AESCipher
from colors import Colors
import password
import sys
class JournalViewer():
def __init__(self,notebook,entry_types,jw):
self.reference_to_writer = jw... |
inputfile = 'taras.txt'
outputfile = 'taras1.txt'
password_tolooffor = "len"
myfile1 = open(inputfile, mode='r', encoding='utf_8')
myfile2 = open(outputfile, mode="w", encoding='utf_8') # create file
"""for line in myfile:
print("hello "+ line.strip()) # добаляє hello для кожної строки
# line.strip - обріж... |
#!/usr/bin/env python3
#count number of alignments
import sys
#argument you put right after $. and 1 refers to second argument
if len(sys.argv)>1:
f = open(sys.argv[1])
else:
f = sys.stdin
chromosome = []
for line in f:
# filter lines that begin with @
if line.startswith("@"):
continue
... |
import socket
import struct
rawsocket = socket.socket(socket.PF_PACKET, socket.SOCK_RAW, socket.htons(0x0800))
rawsocket.bind(("eth0", socket.htons(0x0800)))
# this will bind eth0 interface and we are using htons to specify the protocol we are intresred in
packet = struct.pack("!6s6s2s",'\xaa\xaa\xaa\xaa\xaa\xaa',... |
from tkinter import *
from PIL import Image
root = Tk()
def Enlarge(Sol_Img, Img):
im = Image.open(Sol_Img)
x = im.width
im = im.resize(size=(9 * x, 9 * x))
im.show()
im2 = Image.open(Img)
im2 = im2.resize(size=(9 * x, 9 * x))
im2.show()
def Display_Results(Img, Sol_Img):
TempImg= Imag... |
"""
Script para determinar el tiempo que tarda una suma con decorador.
"""
import time
def timer_track(function):
def wrapper(*args, **kwargs):
print(f"*args - {args} / **kwargs - {kwargs}")
start = time.time()
print(f"start --> {start}")
function(*args, **kwargs)
print(f"... |
import numpy as np
import math
import random_message
import sys
def weights_versions_test(log_max_weight = 9,
log_max_N = 3):
'''
Test with different weights and versions
'''
esp = 10**(-log_max_weight) # Our criteria
# Try different weights and versions
tes... |
## ???????
# ??????????????? int
income = int(input('请输入工资:'))
# ????
salary = 0
# ??????
shouldPay = 0
# ????
tax = 0
def calculator(num):
"""计算税后薪资的函数,参数为原始收入"""
# ??????????5000
shouldPay = num - 5000
# ????????????????????????
if shouldPay <= 0:
tax = 0
elif 0 < shouldPay <... |
# Software License Agreement (BSD License)
#
# Copyright (c) 2019 CNRS
# Author: Joseph Mirabel
import hppfcl, numpy as np
from gepetto import Color
def applyConfiguration(gui, name, tf):
gui.applyConfiguration(name, tf.getTranslation().tolist() + tf.getQuatRotation().coeffs().tolist())
def displayShape(gui, n... |
from pyCABcython import pyCABcython
import random
ca = pyCABcython("../metadata/ruleset/acl_8000", 40)
for i in range(5):
resp = ca.query_btree(random.randint(0, 429496729),
random.randint(0, 429496729),
random.randint(0, 65535),
random.randint(0, 65535))
cnt = 0
for ... |
class Solution(object):
def strobogrammaticInRange(self, low, high):
"""
:type low: str
:type high: str
:rtype: int
"""
self.ans = 0
pair = {"0":"0", "1":"1", "8":"8", "6":"9", "9":"6"}
for i in range(len(low), len(high) + 1):
self.permute(... |
def soma(numero1, numero2):
soma_total = numero1 + numero2
return soma_total
def subtração(numero1, numero2):
sub_total = 0
return sub_total
# divisao
# multiplicacao
# potência
def eh_primo(numero):
resultado = False
contador = 2
while contador <= numero:
resto = numero % contad... |
import numpy as np
import pandas as pd
import gensim
from tsne import bh_sne
from optparse import OptionParser
if __name__ == '__main__':
parser = OptionParser()
(options, args) = parser.parse_args()
assert len(args) == 2
in_file = args[0]
out_file = args[1]
model = gensim.models.word2vec.Word2Vec.load_word2... |
# Generated by Django 3.0 on 2020-09-25 05:55
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('machines', '0052_equipment_in_complex'),
]
operations = [
migrations.CreateModel(
name='Repair_re... |
import os
print(os.path.join('hello','bin','span'))
myFiles = ['accounts.txt','details.csv','invite.docx']
for filename in myFiles:
print(os.path.join('c:\\projects\\kl',filename)
; |
from models import Client, FavoriteList, Wishlist
class ClientDAO:
def __init__(self, db):
self.__db = db
def save(self, client):
cursor = self.__db.connection.cursor()
if client.id:
cursor.execute('UPDATE client SET name=%s, email=%s WHERE id=%s LIMIT 1', (client.name, c... |
from lexer.definitions.tokens import DecrementCell
from lexer.definitions.tokens import IncrementCell
from lexer.tokenizer import Tokenizer
from lexer.definitions.keywords import Keywords
from .hackersdelight_matcher import HackersDelightMatcher
class EditCellMatcher:
@staticmethod
def match(tokenizer: Token... |
from django.conf import settings
from provisioner.models import Subscription
from provisioner.resolve import Resolve
from restclients.uwnetid.subscription import modify_subscription_status
from restclients.models.uwnetid import Subscription as NWSSubscription
class Monitor(Resolve):
def confirm_activation(self):
... |
import requests
from bs4 import BeautifulSoup
import time
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
# browser = webdriver.PhantomJS('phantomjs')
chrome_options = Options()
chrome_options.add_argument("--headless")
browser = webdriver.Chrome(chrome_options=chrome_options)
im... |
"""Various tests to ensure the functionality of my solution to this kata."""
import pytest
from jaden import to_jaden_case
quotes = [
[
"most trees are blue",
"Most Trees Are Blue"
],
[
"How can mirrors be real if our eyes aren't real",
"How Can Mirrors Be Real If Our Eyes... |
from turtle import Turtle
class Score(Turtle):
def __init__(self):
super().__init__()
self.pu()
self.color('white')
self.goto(0,200)
self.pd()
self.hideturtle()
self.left_score = 0
self.right_score = 0
self.write(f'{self.left_score} | {self.ri... |
from __future__ import division
def isPrime(n):
for i in xrange(2,int(n**.5)+1):
if (n % i) == 0:
return False
return True
C = {1: 0}
def c(n):
if n not in C:
C[n] = 0
for i in xrange(2, n+1):
if n % i == 0:
if isPrime(i):
... |
from rest_framework import serializers
from .models import User, CreatedEvent
class UserSerializer(serializers.ModelSerializer):
full_name = serializers.CharField()
profile_picture = serializers.ImageField()
username = serializers.CharField()
# birth_date = serializers.DateField()
gender = seriali... |
import requests
import sys
from bs4 import BeautifulSoup
from .logger import Logger
from .cpubenchmark import cpubenchmark_scraper_single, cpubenchmark_scraper_mega
logger = Logger("harddrivebenchmark_sraper")
class single_hdd:
def __init__(
self,
id=None,
hdd_name=None,
... |
from terminal import timed_input
def obtener_direccion():
"""La funcion recibe la entrada del usuario y determina el movimiento de la serpiente"""
tecla_actual = ""
entrada_usuario = timed_input(1)
direccion = ""
if not entrada_usuario == "":
tecla_actual = entrada_usuario[0]
... |
import cv2 as cv
import numpy as np
from numpy.fft import *
# import cv2.aruco as aruco
def wiener_filter(img, kernel, K):
kernel /= np.sum(kernel)
dummy = np.copy(img)
dummy = fft2(dummy)
kernel = fft2(kernel, s = img.shape)
kernel = np.conj(kernel) / (np.abs(kernel) ** 2 + K)
dummy = dummy * kernel
... |
from rest_framework.test import APITestCase
from .factories import UserFactory
class UserViewSetTestCase(APITestCase):
def test_login(self):
username = 'abcd'
password = 'FS2322rfR@'
login_api = '/api/users/login/'
# create user
response = self.client.post(
l... |
""" -*- coding: utf-8 -*-
@author: omerkocadayi
https://github.com/omerkocadayi
https://www.linkedin.com/in/omerkocadayi/ """
import cv2
import numpy as np
img1 = cv2.imread("bitwise1.png")
img2 = cv2.imread("bitwise2.png")
cv2.imshow("Original Image 1", img1)
cv2.imshow("Original Image 2", ... |
''' This contains the packing and unpacking the padded sequences for rnn.
we want to run a LSTM on a batch of 3 character sequences ['long_str', 'tiny', 'medium']
step 1 : construct vocabulary
step 2 : convert the sequences into numerical form
step 3 : define model
step 4 : prepare data, by padding with 0 (<pad> token)... |
# Write a Python program that prints the string s with the character curr_char replaced by the character new_char.
#
# curr_char and new_char are variables that contain strings with a single character.
#
# You may assume that new_char will not be an empty string.
#
# The match must be case-sensitive (do not repla... |
from src.load_data import load_df_from_dbs
from src.nn import conv_model, evaluate, evaluate_as_classifier
from src.settings import MAX_SEQUENCE_LENGTH, character_to_index, CHARACTER_DICT, max_mic_buffer, MAX_MIC
from sklearn.model_selection import train_test_split
import numpy as np
import random
from Bio import SeqI... |
from . import engine, panel
modules = [
engine,
panel,
]
def register():
for module in modules:
module.register()
def unregister():
for module in reversed(modules):
module.unregister()
|
#!/usr/bin/env python
# Import math Library
import math
import sys
angle = float(sys.argv[1])
print(math.cos(math.radians(angle)))
|
import networkx as nx
distances = {}
with open('kilonetnew.dat', 'r') as f:
lines = f.readlines()
for l in lines:
fr,to,first,second,code = l.split(',')
distances[fr + ':' + to] = int(second)
G=nx.Graph()
def expand(lijn):
for j in range(1, len(lijn)):
G.add_edge(lijn[j - 1], lijn[j], wei... |
"""
https://leetcode.com/problems/arithmetic-slices/
"""
def sum_arithmetic(n):
# sum of all ints 1 .. n
return int((n/2.0)*(1+n))
def numberOfArithmeticSlices(arr):
n = len(arr)-1
all_diffs = []
for i in range(n):
diff = abs(arr[i]-arr[i+1])
all_diffs.append(diff)
unique_... |
import os
import re
import urllib.request
import urllib
from collections import deque
from html.parser import HTMLParser
savePath = ''
imagevis = set()
cnt = 0
def getImage(addr):
global cnt
global imagevis
try :
data = urllib.request.urlopen(addr,timeout=10).read()
except :
print (addr... |
#!/usr/bin/python3
"""
nqueens backtracking program to print the coordinates of n queens
on an nxn grid such that they are all in non-attacking positions
"""
from sys import argv
if __name__ == "__main__":
a = []
if len(argv) != 2:
print("Usage: nqueens N")
exit(1)
if argv[1].isdigit() is... |
from django import forms
class ExecutarFerramentaForm(forms.Form):
def __init__(self, configuracaoferramenta_choices, *args, **kwargs):
super(ExecutarFerramentaForm, self).__init__(*args, **kwargs)
self.fields['configuracaoferramenta_escolhida'].choices = configuracaoferramenta_choices
configuracaoferramenta_e... |
# Generated by Django 3.2.5 on 2021-08-19 12:53
import ckeditor_uploader.fields
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('kategori', '0003_auto_20210819_1453'),
]
operations = [
migrations.CreateMo... |
import logging
from django.test import TestCase
from askup.models import Qset, Question
from askup.utils.general import (
get_checked_user_organization_by_id,
get_first_user_organization,
get_user_organizations_for_filter,
)
from askup.utils.views import select_user_organization
log = logging.getLogger(... |
"""Functions for common command line formatting and procedures."""
import os
import re
import textwrap
from blessings import Terminal
# Formatting
_term = Terminal()
#: Constant for string prepended to input prompts
PROMPT_PREFIX = '> '
#: Constant for string used for terminal indentation
INDENT = ' ' * 3
#: Color/f... |
import quick2wire.i2c as i2c
import time
#bus = smbus.SMBus(1)
# This is the address we setup in the Arduino Program
address = 0x04
gpio_register = 0x09
def writeNumber(value):
with i2c.I2CMaster() as bus:
bus.transaction(
i2c.writing_bytes(address, gpio_register, value))
return -1
def r... |
import ImageChops, Image, ImageMath, ImageFilter
import numpy as np
from utils import *
class SOBEL(ImageFilter.Filter):
name = "sobel filter"
def filter(self, image):
if image.mode != "L":
raise ValueError("image mode must be L")
dx = (3, 3), 1, 0, [-1, 0, 1, -2, 0, 2, -... |
"""
@ Author : hong-il
@ Date : 2021-07-24
@ File name : close.py
@ File path :
@ Description :
"""
from datetime import datetime
import pandas_datareader as pa
from financeDB import financeDB
# DB 커넥션 클래스 초기화
fb = financeDB()
# DB 커넥트
conn = fb.get_connection()
start = datetime(2021, 7,... |
from gurobipy import *
import os
data = os.listdir('../data/')[1]
print "Data: %s" % data
u, v = [], []
with open('../data/' + data, 'r') as fInput:
for line in fInput.readlines():
x, y = map(int, line.split())
u.append(x)
v.append(y)
model = Model('MaxIndependentSet')
selected = model.addVars(range(m... |
# -*- coding: utf-8 -*-
import requests
import datetime,time,random,re
import json
import pandas as pd
from bs4 import BeautifulSoup
from queue import Queue #线程
from threading import Thread #线程
from pyquery import PyQuery as pq
from lxml import etree
import urllib.request
import urllib.parse
import string
pd.... |
#!/usr/bin/python
# -*- coding: utf-8; mode: python -*-
import gflags, os, traceback
FLAGS = gflags.FLAGS
def normalize_sub(fname):
return fname.split('/')[-2]
def report_correct(f, fname):
f.write('CORRECTO ' + normalize_sub(fname) + '\n\n')
def report_wrong(f, fname, expected, actual):
f.write('ERROR ... |
# -*- coding: utf-8 -*-
from model.person import Person
def test_add_person(app, db, json_persons, check_ui):
person = json_persons
old_persons = db.get_person_list()
app.person.create(person)
new_persons = db.get_person_list()
assert len(old_persons) + 1 == len(new_persons)
old_persons.append(... |
import bz2
username = b'BZh91AY&SYA\xaf\x82\r\x00\x00\x01\x01\x80\x02\xc0\x02\x00 \x00!\x9ah3M\x07<]\xc9\x14\xe1BA\x06\xbe\x084'
password = b'BZh91AY&SY\x94$|\x0e\x00\x00\x00\x81\x00\x03$ \x00!\x9ah3M\x13<]\xc9\x14\xe1BBP\x91\xf08'
print(bz2.decompress(username).decode()) # decompressing bytes and decoding
# username... |
import sys
import time
import datetime
import RPi.GPIO as GPIO
import requests
BUTTON_A = 6
BUTTON_B = 9
g_button_a = False
g_button_b = False
URL='http://localhost:5000/api/shower_toggle'
def main():
global g_button_a
global g_button_b
status = 0
resume = 0
loop = 0
... |
import sys
from shapely.geometry import LineString
north = 0
east = 0
direction = 'N'
changedir = {'N': {'L': 'W', 'R':'E'}, 'E': {'L':'N','R':'S'}, 'S': {'L':'E','R':'W'}, 'W':{'L':'S','R':'N'}}
segments = []
def intersection(s0, s1):
i = LineString(s0).intersection(LineString(s1))
if i:
return (i.x,... |
# -*- coding: utf-8 -*-
import arrow
import copy
import logging
import time
import requests
from . import exceptions, utils
from .utils import Sign
class APIMixin(object):
def __init__(self, partner_id, api_key):
self.partner_id = partner_id
self.api_key = api_key
self.sign = Sign(api_ke... |
import csv
##########################
# convert birth_year to integer
f = open("C:\\dev\\python\\legislators.csv", 'r')
csvreader = csv.reader(f)
legislators = list(csvreader)
for item in legislators:
# birthday = item[2]
try:
birth_year = int(item[2].split('-')[0])
except Exception:
bir... |
from flask import Flask, request, redirect, render_template, session, flash
from flask_sqlalchemy import SQLAlchemy
#from hashutils import make_pw_hash, check_pw_hash
app = Flask(__name__)
app.config['DEBUG'] = True
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+pymysql://build-a-blog:build-a-blog@localhost:8889/build... |
from typing import Union, Dict, Type
from intcode.interfaces.base_op import BaseOp
from intcode.ops.addition import AdditionOp
from intcode.ops.equals import EqualsOp
from intcode.ops.halt import HaltOp
from intcode.ops.jump_if_false import JumpIfFalseOp
from intcode.ops.jump_if_true import JumpIfTrueOp
from intcode.o... |
class Area:
def __init__(self,width,height):
self.width,self.height = width,height
self.grid = []
def add(self,row):
self.grid.append(row)
def __getitem__(self, item):
x,y = tuple(item)
return self.grid[x][y]
def __setitem__(self, key, value):
x,y = tup... |
""" cnvpytor.io
class IO: Reading/writing CNVpytor files (extension .pytor) using h5py library.
"""
from __future__ import absolute_import, print_function, division
from .genome import Genome
from .utils import *
from .version import __version__
import datetime
import logging
import os.path
import io
import numpy as ... |
from klampt import *
from klampt.control.robotinterfaceutils import *
from klampt.control.robotinterface import RobotInterfaceBase
from klampt.control.interop import RobotInterfacetoVis,RobotControllerBlockToInterface
from klampt.control.simrobotinterface import *
from klampt.control.blocks import wiggle_controller
fro... |
# %%
# VScodeで入力をテキストから読み込んで標準入力に渡す
import sys
import os
f=open(r'.\Chapter-1\A_input.txt', 'r', encoding="utf-8")
# inputをフルパスで指定
# win10でファイルを作るとs-jisで保存されるため、読み込みをutf-8へエンコードする必要あり
# VScodeでinput file開くとutf8になってるんだけど中身は結局s-jisになっているらしい
sys.stdin=f
#
# 入力スニペット
# num = int(input())
# num_list = [int(item) for item in... |
from expects import expect, be, be_none, be_true, be_a, be_false, equal, raise_error
from expects import be_callable
from spec.helper import description, before, describe, it, context
from spec.helper import TestClass, make_context
from spec.helper import MagicMock, raises
from spec import helper
from functools impor... |
from django.conf.urls import url
from rest_framework.urlpatterns import format_suffix_patterns
from users import views
urlpatterns = [
url(r'^users/$', views.user_list_api, name='users-list'),
] |
import requests
import argparse
endpoints = 'https://api.cloudflare.com/client/v4/'
ip_url = {
'v4': 'http://ip4only.me/api/',
'v6': 'http://ip6only.me/api/',
}
def getZoneID(dn):
tmp = dn.split('.')
top_lv = tmp[-2] + '.' + tmp[-1]
params = {
"name": top_lv
}
r = requests.get(endpoints + 'zones', headers=he... |
import requests
from bs4 import BeautifulSoup
import math
def webscrape(user_input):
user_input = handle_casing(user_input)
print(user_input)
url = "https://www.imsdb.com/scripts/" + user_input + ".html"
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
script = so... |
class Solution:
def findDuplicate(self, nums):
# Find the intersection point of the two runners.
tortoise = hare = nums[0]
while True:
tortoise = nums[tortoise]
hare = nums[nums[hare]]
if tortoise == hare:
break
# Find the ... |
from numpy import *
import wrenchStampingLib as ws
from kinorrt.mechanics.stability_margin import *
from kinorrt.rrt import RRTManipulationStability
# params = (array([[ 0. , 1. , -1. ],
# [ 0. , 1. , 1. ],
# [ 1. , -0. , 0.2],
# [ 1. , -0. , 0.2]]), array([[ 0. , -1. , -0.2097],
# ... |
class Variable:
def __init__(self):
super().__init__()
self.A={"Группа 1":"Группа 1","Пременная 1":10,"Пременная 2":20.2}
self.B = {"Группа 2": "Группа 2", "Пременная 1": 10, "Пременная 2": 20.2}
def __str__(self, *args, **kwargs):
str=""
for k, v in self.A.items():
... |
from flask import Flask,jsonify,request
from main import Game
app = Flask(__name__)
# Create route for get suggestion from image
@app.route("/", methods = ["POST"])
def get_table():
# Get image in base64 coding
img_str = request.form.get("img_str")
#print(img_str)
# Create game from image
game = ... |
#!/usr/bin/python
import rospy
import string
import threading
from sensor_msgs.msg import JointState
from std_srvs.srv import Trigger, TriggerResponse
from trajectory_msgs.msg import JointTrajectoryPoint, JointTrajectory
def jointTrajectoryCallback(msg):
global joint_trajectory
lock.acquire()
joint_traje... |
###MDP assignment
###Programmed by: Nick Miller
###Assistance by: Alex Cody
###Alex helped me print the U values and the policy properly-
import random
class MDP:
def __init__(self):
self.states = [0]*16
self.discount = .95
for i in range(16):
self.states[i] = i
... |
"""Generates code to perform xml decoding.
"""
# Module imports.
from operator import add
from pycim_mp.core.generators.base_generator import BaseGenerator
from pycim_mp.core.generators.generator_utils import *
from pycim_mp.core.generators.python.utils import *
# Module exports.
__all__ = ['DecodersGenerator']
#... |
"""
Consider an alternative version of Pig Latin, in which we don't check to see if the first letter is a vowel, but rather we check to see if the word contains two different vowels. Thus, 'wine' would have 'way' added to the end, but 'wind' would be translated into 'indway'. How would you check for two different vowel... |
import xlrd
from datetime import date
from datetime import datetime
import random
workbook = xlrd.open_workbook('testResult.xlsx')
worksheet = workbook.sheet_by_name('Sheet1')
file = open("testResult.txt","w")
for x in range(0, 250000):
pid=worksheet.cell(x, 0).value
rid=worksheet.cell(x, 1).value
pr... |
'''
A Keras port of the original Caffe SSD300 network.
Copyright (C) 2018 Pierluigi Ferrari
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 re... |
import chainer.links as L
import chainer.functions as F
from chainer import Chain, optimizers, Variable, serializers, initializers
from collections import deque
import copy
import gym
import matplotlib.pyplot as plt
import numpy as np
import sys
import pickle
import os
import glob
from time import sleep
import timeit
... |
from rest_framework import routers
from bootcamp.news.serializers import NewsViewSet
router = routers.DefaultRouter()
router.register("news", NewsViewSet)
|
# coding:utf-8
"""
环境:Mac Python3
pip install -U selenium
下载chromedriver,放到项目路径下
(https://npm.taobao.org/mirrors/chromedriver/2.33/)
https://sites.google.com/a/chromium.org/chromedriver/downloads
问题:
无法打开“chromedriver”,因为无法验证开发者。 仍然运行
macOS无法验证“chromedriver”的开发者。您确定要打开它吗? 打开
"""
import requests
import json
impo... |
#!/usr/bin/env python
import time
import serial
import paho.mqtt.client as mqtt
from random import randrange, uniform
import time
import json
import trionesControl.trionesControl as tc
import pygatt
counter = 0
complete = False
level_1 = 40
level_0 = 10
error_code = False
ser = serial.Serial(
... |
## Sid Meier's Civilization 4
## Copyright Firaxis Games 2005
##
## Sevopedia
## sevotastic.blogspot.com
## sevotastic@yahoo.com
##
from CvPythonExtensions import *
import CvUtil
import ScreenInput
import CvScreenEnums
import random
import string
# globals
gc = CyGlobalContext()
ArtFileMgr = CyArtFileMgr()
local... |
import unittest
from hummingbot.connector.exchange.ascend_ex import ascend_ex_utils as utils
class AscendExUtilTestCases(unittest.TestCase):
@classmethod
def setUpClass(cls) -> None:
super().setUpClass()
cls.base_asset = "COINALPHA"
cls.quote_asset = "HBOT"
cls.trading_pair = ... |
from django import forms
from django.core.exceptions import ValidationError
from django.utils.translation import ugettext as _
from userena.forms import SignupFormTos
from django.conf import settings
from .models import AllowedMailDomain, AllowedEMailAddress
class MailDomainValidationForm(SignupFormTos):
def _... |
import psycopg2
import time
import sys
import stomp
import threading
import datetime
from commons import RandomUtils
from db_tools.postgresql import PG_Client
from mq_tools.amq import Amq_Conn
from mq_tools.amq.Amq_Conn import MessageListener
from mq_tools.amq.Amq_Conn import AmqConnetion
from main_test.egms... |
# D. Расстояние по Левенштейну
def main():
word_1, word_2 = input(), input()
correction_matrix = [[0] * (len(word_2) + 1) for _ in range(len(word_1) + 1)]
for i in range(len(correction_matrix)):
correction_matrix[i][0] = i
for j in range(len(correction_matrix[0])):
correction_matrix[0... |
import re
pattern = r'eggs'
if re.search(pattern, 'abceggseggseggsabc'):
print('Match Found')
print(re.findall(pattern, 'abceggseggseggsabc'))
|
# 1.Car
class Car:
def __init__(self, name, model, engine):
self.name = name
self.model = model
self.engine = engine
def get_info(self):
return f"This is {self.name} {self.model} with engine {self.engine}"
# 2.Shop
class Shop:
def __init__(self, name, items):
... |
import sys
import pandas as pd
import os
import subprocess
import xml.etree.ElementTree as ET
print("Script:", sys.argv[0])
print("Job Index:", sys.argv[1])
print("Num Jobs:", sys.argv[2])
JOB_INDEX = sys.argv[1]
NUM_JOBS = sys.argv[2]
# Retrieve list of required ncbi ids from the web of life lookup table
taxids = p... |
from builtins import range
from ..base import MLClassifierBase
from ..utils import get_matrix_in_format
from sklearn.neighbors import NearestNeighbors
import scipy.sparse as sparse
import numpy as np
class BinaryRelevanceKNN(MLClassifierBase):
"""Binary Relevance adapted kNN Multi-Label Classifier."""
def __i... |
from migen import Module, Signal, If, Instance, ClockSignal
from litex.soc.integration.doc import ModuleDoc
from litex.soc.interconnect.csr import AutoCSR, CSRStatus, CSRStorage, CSRField
class SBLED(Module, AutoCSR):
def __init__(self, revision, pads):
rgba_pwm = Signal(3)
self.intro = ModuleDoc(... |
#!/usr/bin/python3
##########################################################################
# Copyright (c) 2019 ETH Zurich.
# All rights reserved.
#
# This file is distributed under the terms in the attached LICENSE file.
# If you do not find this file, copies can be found by writing to:
# ETH Zurich D-INFK, CAB F.7... |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
# 批量查询企业的工商信息,注册号.组织机构代码等
import requests
import ssl
import time
import re
import sys
import urllib
from openpyxl import Workbook, load_workbook
def get_info(get_url):
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.