text stringlengths 38 1.54M |
|---|
# Example of low-level Python wrapper for rpi_ws281x library.
# Author: Tony DiCola (tony@tonydicola.com), Jeremy Garff (jer@jers.net)
#
# This is an example of how to use the SWIG-generated _rpi_ws281x module.
# You probably don't want to use this unless you are building your own library,
# because the SWIG generated ... |
import sys
import csv
import requests
from bs4 import BeautifulSoup
import re
import urllib3
import datetime
tags_file = open('stanford_tags.txt', 'r')
tags = tags_file.readlines()
for i in range(0, len(tags)):
tags[i] = tags[i].strip().lower()
with open('output_files/final.tsv', 'r') as in_file:
file_reade... |
import tkinter as tk
#import subprocess import call
#Create & Configure root
root = tk.Tk()
root.title("ELEC 490: Eye Tracking Keybaord")
tk.Grid.rowconfigure(root, 0, weight=1)
tk.Grid.columnconfigure(root, 0, weight=1)
#Create & Configure frame
frame=tk.Frame(root)
frame.grid(row=0, column=0, sticky='NSEW')
#Pro... |
# pyowm is the open weather api client, use ide and docs to find methods https://openweathermap.org/api
# to look at client class import pyowm.weatherapi25.weather.Weather
import pyowm
from pyowm.exceptions.api_response_error import NotFoundError, UnauthorizedError, APIResponseError
# allows for conversion from degre... |
# ======================================================================================================================
# PROJECT NAME: Parking Sensor Mock
# FILE NAME: Main
# FILE VERSION: 1.0
# DATE: 19.05.2019
# AUTHOR: Piotr Skalski [gith... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'ui/MainWindow.ui'
#
# Created: Tue Dec 26 22:57:29 2017
# by: pyside-uic 0.2.13 running on PySide 1.2.2
#
# WARNING! All changes made in this file will be lost!
from PySide import QtCore, QtGui
class Ui_MainWindow(object):
def set... |
from django.urls import path, include,re_path
from user import views
urlpatterns = [
path('newslistpic/',views.newlistpic),
path('detail_con/',views.detail_con),
path('listpic/',views.listpic)
]
|
import os
from .indices import (
read_ids, read_path_ids, ids_match, trim_ids,
ids_startswith, ids_tail_match_head, ids_match_tail,
)
__all__ = [
'find_calc_dir', 'find_data_dir', 'find_data_fname',
'find_data_file', 'get_data_fname', 'get_data_file',
'find_data_subdir',
]
def iter_subdir(... |
class TreeNode:
def __init__(self, data, left=None, right=None):
self.data = data
self.left = left
self.right = right
def __str__(self):
fmt = 'TreeNode({}, {}, {})'
return fmt.format(str(self.data), str(self.left), str(self.right))
def to_list(self):
a = []
... |
import os
from serif import Document
from serif.model.ingester import Ingester
from serif.theory.alert_author import ALERTAuthor
import csv
import sys
csv.field_size_limit(sys.maxsize)
class CSVIngester(Ingester):
def __init__(self, lang, headers, csv_file=None, corpus=None, **kwargs):
super(CSVIngester... |
from unittest import TestCase
from basketball_reference_web_scraper.data import OUTCOME_ABBREVIATIONS_TO_OUTCOME, Outcome
from basketball_reference_web_scraper.parsers import OutcomeAbbreviationParser, PlayerBoxScoreOutcomeParser
class TestPlayerBoxScoreOutcomeParser(TestCase):
def setUp(self):
self.pars... |
#!/usr/local/bin/python -tt
import sys
import argparse
import networkx as nx
import operator
import colorsys
graphFilePostfix = None;
graphType = None;
multipleAcquireWithoutRelease = 0;
noMatchingAcquireOnRelease = 0;
separator = " ";
tryLockWarning = 0;
verbose = False;
#
# LogRecord contains all the fields we exp... |
# -*- coding: utf-8 -*-
"""
-------------------------------------------------
File Name: NoticeSqlBase.py
通知书接口/签名交易接口
契约作业通知书签名查库方法
Description :
1 . 获取建议书状态与类型
2 . 查询契约通知书
3 . 查询投保人签名明文PLAINAPPNTSIG... |
from django.test import TestCase
from couchdbkit import ResourceConflict, ResourceNotFound
from corehq.util.couch_helpers import ResumableDocsByTypeIterator, TooManyRetries
from dimagi.utils.couch.database import get_db
class TestResumableDocsByTypeIterator(TestCase):
@classmethod
def setUpClass(cls):
... |
dict = {'Name': 'Zara', 'Age': 7, 'Name': 'Manni'}
dict.get('Name')
# 'Manni'
dict.keys()
# ['Name', 'Age']
dict.items()
# [('Name', 'Manni'), ('Age', 7)]
dict.values()
# ['Manni', 7]
|
# -*- coding: utf-8 -*-
from sys import argv
script, name=argv
promot = ">: "
print("Hi,{0}.I'm {1}".format(script, name))
a=input(promot)
b=input(promot)
c=input(promot)
print("The result is {0},{1},{2}".format(a,b,c))
|
#!/usr/bin/env python3
"""mapper.py"""
import sys
from datetime import datetime as dt
input_file = sys.stdin
# Not read the first line of input file
next(input_file)
# Read lines from input_file
for line in input_file:
# Removing leading/trailing whitespaces
line = line.strip()
# Parse the input elements
tic... |
from flask.ext.sqlalchemy import SQLAlchemy
from sqlalchemy.orm import relationship, backref
from app import db, app
class Person(db.Model):
id = db.Column(db.Integer, primary_key=True)
user_id = db.Column(db.Integer, db.ForeignKey('user.id'))
first_name = db.Column(db.String(128))
last_name = db.Colum... |
#import sys
#import threading
from optparse import make_option
from django.core.management.base import BaseCommand, CommandError
from edc.subject.registration.models import RegisteredSubject
from ...models import SubjectIdentifier
class Command(BaseCommand):
args = '--check <subject_type> --update <subject_type>... |
#!/usr/bin/env python3
"""
YOLO: You Only Look Once
arxiv paper: https://arxiv.org/pdf/1506.02640.pdf
"""
import os
os.environ["KERAS_BACKEND"] = "tensorflow"
import keras
import numpy as np
from keras import layers
from keras import models
from keras.applications import vgg16
#from keras.applications import inceptio... |
'''
4.Implement the sieve of Eratosthenes algorithm for generating all prime numbers less than a
given bound
'''
def CiurulEratostene(n):
#initialize with true all the numbers in range 1 to n
prime = [True for i in range(n+1)]
p = 2
#have a p to go from 2 to p square
while (p * p <= n):
... |
from flask_sqlalchemy import SQLAlchemy
import graphene
from main.models import User, Post
from main.schema import PostObject
db = SQLAlchemy()
class CreatePost(graphene.Mutation):
class Arguments:
title = graphene.String(required=True)
body = graphene.String(required=True)
username = gra... |
import re
import gnomad
import ensembl
import csv
import sys
import time
def find_norm_freq(protein_name):
# Opens sequence file and finds amino acid location of any matches to the motif
canonical_id = gnomad.get_canonical_id(protein_name)
mutations = gnomad.get_variants(canonical_id)
results = []... |
from sym import Sym
from num import Num
from test import O
import sys
import re
class Data:
def __init__(self):
self.w = {}
self.syms = {}
self.nums = {}
self._class = None
self.rows = []
self.name = []
self._use = []
self.indeps = []
def indep(... |
from django.urls import path
from . import views
app_name = 'posts'
urlpatterns = [
path('', views.PostList.as_view(), name='list'),
path('<int:pk>/', views.PostDetail.as_view(), name='detail'),
path('<int:post_id>/comments/', views.CommentList.as_view(), name='comment-list'),
path('<int:post_id>/com... |
import pandas as pd
def __remove_percentile_outliers(data: pd.DataFrame, col, lower=0, upper=0) -> pd.DataFrame:
lower_values_to_remove = round(data.shape[0] * lower)
upper_values_to_remove = round(data.shape[0] * upper)
data = data.sort_values(col)
data = data.head(data.shape[0] - upper_values_to_rem... |
import argparse
import cv2
from ocr.detector import image_pyramid, sliding_window_batch
from ocr.helper import save_image_batch
from keras.models import load_model
import ntpath
import numpy as np
pyramid_scale, pyramid_min_width, pyramid_min_height = 0.8, 150, 150
sl_w_step, sl_w_width, sl_w_height = 5, 30, 30
ap = ... |
"""Benchmark Search algorithm"""
# pylint: disable=missing-docstring, invalid-name
import netCDF4
import bench
import util
import obsoper.grid
class BenchmarkRealData(bench.Suite):
def setUp(self):
for path in ["sample_class4.nc",
"sample_prodm.nc"]:
util.grab(path)
... |
import pandas as pd
import numpy as np
from tqdm import tqdm
import pickle
import seaborn as sns
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import matplotlib.style as style
style.use('fivethirtyeight')
# Enable high resolution plots
from IPython.display import set_matplotlib_formats
set_matplot... |
import sys
import re
import sqlite3
import os
import keyring
import getpass
import subprocess
import tempfile
import numpy as np
import pandas as pd
from trm import cline
from trm.cline import Cline
import hipercam as hcam
from hipercam.utils import target_lookup
__all__ = [
"calsearch",
]
####################... |
#!/usr/bin/env python
from setuptools import setup, find_packages
import sys
try:
import pypandoc
readme = pypandoc.convert('README.md', 'rst')
except(IOError, ImportError):
with open('README.md') as f:
readme = f.read()
install_requires = [
'cachetools>=1.1.5',
'requests>=2.7.0',
'xm... |
def solve(n):
if n == 0:
return "INSOMNIA"
s = set([ d for d in str(n) ])
l = n
while len(s) < 10:
l += n
s.update([ d for d in str(l) ])
return str(l)
if __name__ == "__main__":
t = int(raw_input())
for i in xrange(1, t+1):
n = int(raw_input())
print "Case #%d: %s" % (i, solve(n... |
# coding: utf-8
from gpiozero import Button
import ap310
import time
if __name__ == "__main__":
token = ap310.login()
vermelho = Button(2)
verde = Button(3)
while True:
if vermelho.is_pressed and verde.is_pressed:
print('Ambos')
r = ap310.changeLed(token, "yellow", "blin... |
import scipy.io as sio
import numpy as np
import sklearn
from sklearn.model_selection import KFold, StratifiedKFold
from sklearn.svm import SVC
from sklearn.grid_search import GridSearchCV
#from sklearn.preprocessing import normalize
#from MySVM import TrainMySVM, TestMySVM
from TrainMyClassifier import TrainMyClassif... |
#coding: utf8
import sys
import os
sys.path.append(os.path.join(os.path.dirname(__file__), '..', '..', '..'))
import unittest
from tests.integration.for_sqlite.helper import Student, Course, Score
from sweet_orm.orm import atomic, Model
class TestTransactionSQLite(unittest.TestCase):
def setUp(self):
Mo... |
import logging
from django.core.management.base import BaseCommand
from django.db.models import Q
from django.utils import timezone
from squalaetp.models import Xelon, ProductCategory, Indicator
from psa.models import Multimedia, Ecu
from utils.conf import XLS_SQUALAETP_FILE, XLS_DELAY_FILES, XLS_TIME_LIMIT_FILE, stri... |
import diffcp.cones as cone_lib
import numpy as np
from scipy import sparse
def scs_data_from_cvxpy_problem(problem):
import cvxpy as cp
data = problem.get_problem_data(cp.SCS)[0]
cone_dims = cp.reductions.solvers.conic_solvers.scs_conif.dims_to_solver_dict(data[
... |
# -*- coding: utf-8 -*-
"""
Created on Mon Mar 25 14:36:19 2019
@author: kg
"""
# -*- coding: utf-8 -*-
import matplotlib.pyplot as plt
from matplotlib.font_manager import FontProperties
font = FontProperties(fname=r"C:\Windows\Fonts\simhei.ttf", size=14)
plt.bar([1, 3, 5, 7], [19, 23, 50, 68], label='... |
#matplotlib 사용하기
from matplotlib import pyplot
x_name = ('1','2','3','4','5','6','7','8','9','10','11','12')
temp_2018 = [0.5,2.0,6.7,12.7,18.6,21.7,24.4,25.2,20.5,15.0,10.0,3.5]
pyplot.bar(x_name,temp_2018,
width =0.4,color = 'red',label='temp 2018')
pyplot.xlabel('Month')
pyplot.ylabel('Average Temperature')
py... |
import time
import random
start = time.time()
print("start:%0.2fs" % start)
while True:
play = input('play the game(y/n)?')
if play == 'y':
number = random.randint(0, 1000)
guess = int(input('guess a number: '))
while True:
if number > guess:
guess = int(inpu... |
"""
Support instabot's methods.
"""
import sys
import os
import codecs
def check_if_file_exists(file_path, quiet=False):
if not os.path.exists(file_path):
if not quiet:
print("Can't find '%s' file." % file_path)
return False
return True
def read_list_from_file(file_path, qui... |
from __future__ import print_function
import ctypes
import json
import logging
import os
import shutil
import subprocess
import sys
import time
import zipfile
import jinja2
import requests
from gerrit_mq import common
from gerrit_mq import orm
def add_or_update_account_info(sql, ai_obj):
"""
Update the AccountIn... |
#!/usr/bin/env python
import tensorflow as tf
import numpy as np
from file_parser import *
# converting text into vectors
#################################################
def predict_category_based_on_description(description):
description = description.lower()
Total_Number_of_Records = Travel['NUM_RECORDS']... |
# Indexing
# Slicing -> Substring
# Reversing
# Contains
# Concatenating
# Repeat
# working with loops
'''
Indexing and Slicing
'''
var1 = "Python"
var2 = "Tutorial"
#+ve indexing
print ("var1[0]:",var1[2])
#-ve indexing
print ("var1[0]:",var1[-3])
#+ve slicing
print ("var2[1:5]:",var2[1:5])
#-ve slicing
print (... |
import scrapy
import re
from datetime import datetime
from dateutil.relativedelta import relativedelta
import dateparser
from tpdb.BasePerformerScraper import BasePerformerScraper
class siteAuntJudysPerformerSpider(BasePerformerScraper):
selector_map = {
'name': '//div[@class="title_bar"]/span/text()',
... |
import numpy as np
import Node2VecFeatures as n2v
import RefexFeatures as refex
def calculate_features(self, order = 'linear'):
refex_feats = refex.calculate_features(self, order)
node2vec_feats = n2v.calculate_features(self, order)
features = np.concatenate((refex_feats, node2vec_feats), axis = 1)
sel... |
#!/usr/bin/env python3
import numpy as np
import tensorflow.keras as keras
from tensorflow.keras.layers import Input
## Basic blocks ##
def skip_connection(x, xskip):
"""
A long skip connection that concatenates output from an encoding layer to a
layer in the decoder along the channel dimension.
Pa... |
import praw, re
from urlextract import URLExtract
import json, csv
_reddit = praw.Reddit(client_id='U-9whxE5yXShxA', client_secret='OQVVmWYy2rediR-6jm0zophXizM', user_agent='python:fact:1.00 (by /u/kalebr80)')
def writeToFiles(stances, body):
with open('./fakeNews/stances_test_reddit.csv', 'w') as out:
w... |
import discord
import cogs.utils.checks
from discord.ext import commands
from cogs.utils.embed import (passembed, errorembed)
class ErrorHandler(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.Cog.listener()
async def on_command_error(self, ctx, error, bypass=False):
... |
import os
_version_file = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'version.txt')
_version = None
class IncorrectVersion(Exception):
pass
def get_version():
global _version
if not _version:
_version = _read_version()
return _version
def _read_version():
with open(_ver... |
import math
from random import random
from config import *
def get_best_individual(population):
path_length = float("Inf")
individual = None
for i in range(len(population.individuals)):
if(population.individuals[i].path_length < path_length):
path_length = population.individuals[i].path_length
i... |
class ThreeStack1:
def __init__(self, l1, l2, l3):
self.stack = [l1, l2, l3]
class ThreeStack2:
def __init__(self, l1, l2, l3)
self.stack = [0] * (10 ** 8)
self.l1_st = 0
self.l2_st = len(self.stack) // 3
self.l3_st = len(self.stack) // 3 * 2
for l, st in zip([l1... |
import itchat
itchat.auto_login()
import math
import math
import os
import PIL.Image as Image
def get_friends_lists():
friends = itchat.get_friends(update=True)[0:]
print(friends)
user = friends[0]["UserName"]
print(user)
# @c5a69b45e0b9ad6f910f282847a69e08ffb83f77f91b33f5ba39868a3eb66ae3
os.mkdir(user)
retu... |
from csi_soap_test import CsiSoapTest
import csv
if __name__ == "__main__":
csoap_test = CsiSoapTest("d:\\csi_use_csoap.log")
gsopa_test = CsiSoapTest("d:\\csi_use_gsoap.log")
n = [i+1 for i in range(20)]
row = [''] + n
out = open('d:\\test_result.csv', 'a', newline="")
csv_write = csv.writer(... |
def isBalanced(self, root):
def helper(node):
if node == None:
return (0, True)
l_height, l_balance = helper(node.left)
r_height, r_balance = helper(node.right)
return (max(l_height, r_height) + 1, l_balance and r_balance and abs(l_height - r_height) <= 1)
return h... |
#! /usr/local/bin/python3
import math
class BinarySearch:
def search(self, element, sorted_list):
if sorted_list is None or len(sorted_list) <= 0:
return -1
left = 0
right = len(sorted_list) - 1
while left < right:
mid = left + math.floor((right - left) ... |
# https://www.hackerrank.com/challenges/write-a-function/problem
def is_leap(year):
leap = False
# Write your logic here
if 1900 <= year <= 100000:
if year % 4 == 0 and year % 100 != 0:
leap = True
if year % 100 == 0 and year % 400 == 0:
leap = True
return lea... |
import constants as c
import random
class ROBOT:
def __init__(self,sim,wts):
self.send_objects(sim)
self.send_joints(sim)
self.send_sensors(sim)
self.send_neurons(sim)
self.send_synapses(sim, wts)
def send_objects(self, sim):
# self.whiteObject = sim.send_cylinder... |
#TODO: IDEAS TO INCREASE RESULT QUALITY AND USABILITY
#TODO: Analyze markup for business related information? For example, yelp uses the class
#TODO: biz-country-ca for canadian companies and biz-country-us for american companies
#TODO: When comparing against other accurate data, if we know the country/state/etc... a... |
x = 10
a = lambda y: x+y
x = 20
b = lambda y: x+y
print(a(10)) # 30
print(b(10)) # 30
x=10
a= lambda y,x=x: x+y
x=20
b= lambda y,x=x: x+y
print(a(10)) # 20
print(b(10)) # 30 |
import numpy as np
import matplotlib.pyplot as plt
from scipy import signal, misc
from mpl_toolkits.mplot3d import Axes3D
from scipy import ndimage
#시그마값이 커지면, 가우시안의 높이는 낮지만 폭이 넓어지게 된다.
#즉, 시그마의 값이 커지게 되면, 블러링 되는 정도도 커지게 된다.
def Im_filtering(im, Filter, FilterSize, dummyNum):
#이미지의 형태 불러오기
row, col... |
import sys
from pathlib import Path
import requests
document1_path = Path(sys.argv[1]).resolve()
document2_path = Path(sys.argv[2]).resolve()
with open(document1_path) as f:
content1 = f.read().strip()
with open(document2_path) as f:
content2 = f.read().strip()
data = {
"document1": content1,
"docum... |
# tutorial41.py
# import Game
# import Game.main
# print(Game.a)
# print(Game.main.b)
# import Game.Level.start
# from Game.Level import
from Game.Level.start import select_difficulty
select_difficulty(2)
# Game/__init__.py
a = 10
# Game/main.py
b = 20
# start.py
def select_difficulty(d):
print(d)
|
import time
username = ''
text = "Snape is stupid"
textSplit = text.split()
randomSpace = [' ', ' ', ' ']
eachText = []
while True:
for x in textSplit:
time.sleep(0.6)
print(x)
|
# 2014.10.18 14:39:52 Central European Daylight Time
#Embedded file name: scripts/client/AuxiliaryFx/Roccat/__init__.py
pass
+++ okay decompyling res/scripts/client/auxiliaryfx/roccat/__init__.pyc
# decompiled 1 files: 1 okay, 0 failed, 0 verify failed
# 2014.10.18 14:39:52 Central European Daylight Time
|
import argparse
from producer import RedditProducer
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Reddit Kafka Producer')
parser.add_argument('topic', type=str, help='Reddit Topics: [submission, comment, subreddit, redditor]')
args = parser.parse_args()
producer = RedditPr... |
#!/usr/bin/env python
# coding=utf-8
### binary search by python
searchlist=[12,29,32,34,38,42,49,60,66,72,88]
low=0
high=len(searchlist)-1
print low,high ### searchlist.__len__() can also get length of list
k=int(raw_input("please input the num u r searching:"))
while(low<=high):
mid=(low+high)/2
if k<... |
"""
Урок 4. Полезные инструменты
1. Реализовать скрипт, в котором должна быть предусмотрена функция расчета заработной платы сотрудника.
В расчете необходимо использовать формулу: (выработка в часах * ставка в час) + премия.
Для выполнения расчета для конкретных значений необходимо запускать скрипт с параметрами.
"""
i... |
from rrtnode import RRTNode
import line
class Graph:
"""
An RRT graph.
Args:
start_angles: The initial angles of the arm.
end_angles: The desired angles of the arm.
Instance Attributes:
start_node: Node containing cartesian coordinates and arm angles of the start position.
... |
"""
Client that performs inferences on the tensorflow serving model using the REST API.
"""
# for pre/post-proccesing
import SimpleITK as sitk
from preprocessing.metadata import Patient
from preprocessing.preprocess import Preprocessor
from augmentation.augment_data import process
import numpy as np
from scipy.ndimage... |
import os
import pandas as pd
from util.paths import ensure_dir
BASE_FOLDER_PATH = '/mnt/all1/ml20m_yt/videos_resized'
def youtube_video_link_by_id(youtube_id):
return 'https://www.youtube.com/watch?v=' + youtube_id
# Import dataframe containing the ML20M YT dataset
#
df = pd.read_csv('datasets/ml2... |
import copy # fork a chain
import datetime # get real time for timestamps
import hashlib # hash
class MinimalChain():
def __init__(self): # initialize when creating a chain
self.blocks = [self.get_genesis_block()]
def __eq__(self, other):
if isinstance(other, self.__class__):
r... |
#!/usr/bin/python3
from decimal import Decimal
from unittest import TestCase, mock
from wikidata import WikiData
class TestWikiData(TestCase):
@classmethod
@mock.patch.multiple(WikiData, __abstractmethods__=set())
def setUp(cls):
cls.wd = WikiData('0000 0001 2197 5163')
def test_format_float... |
from django import forms
from .models import Recommendation, RecommendationCategory
from .widgets import CustomClearableFileInput
class RecommendationForm(forms.ModelForm):
class Meta:
model = Recommendation
fields = ('category', 'name', 'image',
'intro', 'description', 'link_to_... |
def shell(lista):
contadorsublistas = len(lista)//2
while contadorsublistas > 0:
for init in range(contadorsublistas):
brechainsercion(lista, init, contadorsublistas)
contadorsublistas = contadorsublistas // 2
return lista
def brechainsercion(lista,init, brecha):
... |
from django.contrib.auth.hashers import make_password
from rest_framework import serializers
from core.serializers import UserSerializer
from .models import EmployeeRequest
class RequestSerializer(serializers.ModelSerializer):
class Meta:
model = EmployeeRequest
fields = (
'id',
... |
#!/usr/bin/env python
"""
This run a user specified command and log its result.
./command.py [-a] [-c command] {logfilename}
logfilename : This is the name of the log file. Default is command.log.
-a : Append to log file. Default is to overwrite log file.
-c : spawn command. Default is the command 'ls -l'.
Example:
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Apr 8 14:01:16 2020
@author: gsd818
"""
import pandas as pd
import csv
configfile: "config.yaml"
## --------------------------------------------------------------------------------
##### Modules #####
include: "rules/gwasApproaches.smk"
include: "ru... |
from django.urls import path
from . import views
app_name = 'members'
urlpatterns = (
[
path("", views.index, name="index"),
path("profile-list/", views.list_students, name="list_students"),
path("profile/<slug:member_id>/", views.profile, name="profile"),
path("signup/", views.si... |
list1 = [1, 3, 6, 78, 35, 55]
list2 = [12, 24, 35, 24, 88, 120, 155]
list3 = [num for num in list1 if num in list2]
print(list3) |
import torch
import torchaudio
import os
from pathlib import Path
from torch import Tensor
from torchaudio import transforms as T
from torch.utils.data import Dataset, DataLoader
from typing import Tuple
class SpeechCommandsv1(Dataset):
CLASSES = ['bed', 'bird', 'cat', 'dog', 'down', 'eight', 'five', 'four', 'go'... |
from langdetect import detect_langs
minThreshold = 0.7
def DetectLanguage(message):
if message == '':
return 'unk'
langCoef = detect_langs(message)
if len(langCoef) == 0:
raise LanguageDetectionError("The language of the message could not be identified.")
if langCoef[0].prob < minThre... |
import pandas as pd
dataset=pd.read_csv('Salary.csv')
x = dataset['YearsExperience'].values.reshape(-1,1)
y = dataset['Salary']
from sklearn.linear_model import LinearRegression
model = LinearRegression()
model.fit(x,y)
years=input("Enter experience of an indiviual(in years):")
print("Salary:",model.predict([[float(yea... |
# Module imports
import numpy as np
import cv2
import images
# Desciption:
# Class that defines camera properties and processes its images
# Attributes:
# camera: cv2.VideoCapture object
# resolution: camera resolution
class Camera:
def __init__(self, camera_port = 0, resolution = 1):
self.camera = cv2.VideoCaptu... |
#!/usr/local/bin/python3
import subprocess as subp
from os import chdir, listdir
from os.path import join, isfile, realpath, dirname
import getpass
import MySQLdb
import MySQLdb.cursors
import re
def run(cmd):
return subp.run(cmd, stdout=subp.PIPE, stderr=subp.PIPE)
def run2var(cmd):
out = run(cmd).stdout.... |
import os
# we can create another file for each project (folder)
def create_project_dir(directory):
if not os.path.exists(directory):
print('creating directory for now ' + directory)
os.makedirs(directory)
# create queue and final crawled files (by some if) :)
def create_data_files(project_name,... |
import torch
import torch.nn as nn
from torch import autograd
from neat.phenotype.feed_forward import FeedForwardNet
import numpy
# from neat.visualize import draw_net
from time import time
from funk_svd import SVD
def train_one_epoch(model, inputs, targets, loss_fn, optimizer, epoch_no, device, verbose=1):
'trai... |
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
from email.mime.text import MIMEText
import smtplib,sys
mail_host = 'smtp.163.com'
mail_user = 'nicefeiniu@163.com'
mail_passwd = '53557873ly'
sender = 'nicefeiniu@163.com'
receivers = ['920036515@qq.com', '281188071@qq.com']
def send_mails():
content = "Hello, my f... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 2011, Florent Lamiraux, Thomas Moulard, JRL, CNRS/AIST
import os
from dynamic_graph.sot.dynamic_pinocchio.feet_follower import FeetFollowerFromFile
from dynamic_graph.sot.dynamic_pinocchio.tools import (
checkFinalConfiguration,
clt,
plug,
robot... |
from .future import DSSFuture
import json, warnings
from datetime import datetime
class DSSConnectionListItem(dict):
"""
An item in a list of connections.
.. important::
Do not instantiate directly, use :meth:`dataikuapi.DSSClient.list_connections` instead.
"""
def __init__(self, cl... |
# Generated by Django 3.1.13 on 2022-03-24 19:37
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
import taggit.managers
class Migration(migrations.Migration):
dependencies = [
('democracylab', '0009_auto_20210302_2036'),
('taggit', '0003_tag... |
#-*- coding:utf-8; mode:python; indent-tabs-mode: nil; c-basic-offset: 2; tab-width: 2 -*-
import copy, os, os.path as path
from collections import namedtuple
from bes.system.check import check
from bes.fs.file_check import file_check
from bes.fs.file_util import file_util
from .config_data import config_data
class ... |
"""
HTML inlines
Usage: [Text content: will be Markdown formatted]{ attributes to use }
Examples:
[A normal span tag with a class]{ .warning }
[A mark tag]{ /mark }
[A del tag]{ /del }
"""
import markdown
from markdown.util import etree
import re
from tag_attribute_parser import parse_attribute_string, attributes_... |
"""
改良予定
現状は各変数の分布のみだが、相関分析できるようにする
"""
from configparser import ConfigParser
from pathlib import Path
import sys
from typing import List
from math import log2, ceil
import itertools
import pandas as pd
from matplotlib import pyplot as plt
from sklearn.preprocessing import LabelEncoder
import numpy as np
# グロー... |
from IPython import display
from matplotlib import pyplot as plt
from mxnet import autograd,nd
import random
# 生成数据集
# 设训练数据集样本数为1000,输入个数(特征数)为2。给定随机生成的批量样本特征
# 使用线性回归模型真实权重w ,偏差b ,一个随机噪声e , 来生成标签y
num_inputs = 2
num_examples = 1000
true_w = [2,-3.4]
true_b = 4.2
features = nd.random.normal(scale=1,shape=(num_exampl... |
# O(n*m)
# n = len(matrix) | m = len(matrix[0])
class Solution:
def maximalRectangle(self, matrix: List[List[str]]) -> int:
onesColumnHeight = [[0 for _ in row] for row in matrix]
for y in range(len(matrix)):
for x in range(len(matrix[y])):
if matrix[y][x] == "1":
... |
import json
import argparse
import configparser
""" Compresses all json files into a single one and draws connections between them.
It has two uses:
1) Simply fetches all the
"""
FAILS = 0
ALL_ENTRIES = dict()
## Read path to unlabelled papers and model from config
config = configparser.RawConfigParser(... |
# Generated by Django 3.2.3 on 2021-07-01 05:10
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('inventory', '0021_auto_20210530_2228'),
]
operations = [
migrations.RemoveField(
model_name='rack',
name='capacity',... |
from tkinter import *
import tkinter.font as tkfont
from display import *
from internet import *
from app import new, last
class GUI():
def __init__(self, item):
self.root = Tk()
self.liked = False
self.item = item
self.name = "Windows Spotlight"
self.author = "made with ❤ by Shikher Srivastava"
self.bg ... |
"""Parse a GPS track and add it to a DecoratedMap."""
from __future__ import print_function
import xml.sax
import os
from motionless import LatLonMarker, DecoratedMap
current_dir = os.path.dirname(os.path.abspath(__file__))
class GPXHandler(xml.sax.handler.ContentHandler):
"""GPS track parser"""
def __init__... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.