text stringlengths 8 6.05M |
|---|
from collections import defaultdict
import random
with open('YOUR_TEXT_FILE.txt', encoding='utf8') as txt:
script = txt.read()
def create_tf_matrix(text):
words = text.split(" ")
tf_matrix = defaultdict(list)
succeeding_words = zip(words[0:-1], words[1:])
for w1, w2 in succeeding_words:
tf_matrix... |
#!/usr/bin/env python3
# Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file
# for details. All rights reserved. Use of this source code is governed by a
# BSD-style license that can be found in the LICENSE file.
# This script builds and then uploads the Dart client sample app to AppEngine,
# wh... |
from __future__ import absolute_import, division
from __future__ import print_function, unicode_literals
import random
import unittest
import numpy as np
import six
from six.moves import range, zip
from smqtk.algorithms import get_nn_index_impls
from smqtk.algorithms.nn_index.faiss import FaissNearestNeighborsIndex
... |
# encoding=utf8
"""
Author: 'jdwang'
Date: 'create date: 2017-01-13'; 'last updated date: 2017-01-13'
Email: '383287471@qq.com'
Describe: 所有属性规则的父类:比如 Price 等都是该类的子类
"""
from __future__ import print_function
__version__ = '1.3'
import re
from info_meta_data import InfoMetadata
class RegexBase(o... |
from django.contrib import admin
from .models import *
@admin.register(Category,Categorylevel,Qualification,Maindocument,Staffdocument)
class ViewAdmin(admin.ModelAdmin):
pass
|
# Copyright 2020 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 internal_plugins.test_lockfile_fixtures.lockfile_fixture import (
JVMLockfileFixture,
JVMLockfi... |
import cv2
img = cv2.imread('C:/Users/eugur/Downloads/Jupyter_lab/Computer-Vision-with-Python/DATA/00-puppy.jpg')
while True:
cv2.imshow('Puppy',img)
# if we have waited at least 1 ms AND we ve pressed the escepace key
if cv2.waitKey(1) & 0xff == 27:
break
cv2.destroyAllWindows() |
sexo = str(input('Informe seu sexo: [M/F] → ')).upper()
while sexo != 'M' and sexo != 'F':
sexo = str(input('Dados inválidos! Por favor, informe seu sexo: ')).upper()
print(f'Sexo {sexo} registrado com sucesso!')
|
import requests
from bs4 import BeautifulSoup
url = 'https://en.wikipedia.org/wiki/Pawan_Kalyan'
resp1 = requests.get(url)
print(resp1)
resp = requests.get(url).content
# print(resp)
soup = BeautifulSoup(resp, 'html.parser')
headlines = soup.find('h1', id='firstHeading')
print(headlines.text)
info = sou... |
from train_config import *
import torch.nn.functional as F
def main(args):
print("Arguments: ", args)
print("cpus:", os.sched_getaffinity(0))
_, testset, _, index = u.load_data(
data_dir=args.data_dir,
data_files=args.data_files,
test_size=1.,
classify=args.classify,
... |
import pde
from matplotlib import pyplot as plt
import sys
import logging
logging.basicConfig(stream=sys.stdout, level=logging.DEBUG)
f,a = plt.subplots(3)
prob = pde.problems.instpoisson1d.unforced
prob.plot(a)
solver = pde.solvers.linearsolver(prob)
solver.solve()
solver.plot(a)
plt.show() |
from abc import ABCMeta, abstractmethod
import os
import os.path as osp
class BaseManager(metaclass=ABCMeta):
def __init__(self, params):
self.params = params
self.ROOT = params["ROOT"]
self.WORK_DIR = params["WORK_DIR"]
self.raw_dirname = params["raw_dirname"]
self.data_pat... |
import numpy as np
import math
from oval import Oval
from roots_finder import RootsFinder
class WignerCaustic:
"""
Class generating wigner caustic for the given oval
"""
def __init__(self, oval: Oval):
self.oval = oval
def wigner_caustic(self):
parameterization_t = self.oval.pa... |
from sklearn.datasets import make_moons
from fuzzy_c.my_lib import main_execution_gmm
if __name__ == '__main__':
N = 300
data = make_moons(n_samples=N, noise=0.05, random_state=1)
X = data[0]
Y = data[1]
main_execution_gmm(X)
|
"""# 0. SETUP """
# --------------------------------------------------------------------
# --------------------------------------------------------------------
# --------------------------------------------------------------------
import sys
import pandas as pd
import math
import datetime as dt
from scipy.spatial.dis... |
n = int(input("Enter a year: "))
if n%4==0:
if n%100 == 0:
if n%400 ==0:
print(f"{n} is a leap year")
else:
print(f"{n} is not a leap year")
else:
print(f"{n} is a leap year")
else:
print(f"{n} is not a leap year") |
import tensorflow as tf
from window import WindowGenerator
from baseline import MultiStepBaseline
import numpy as np
import matplotlib.pyplot as plt
from data import Data, get_data_df
"""
Train model to predict next 3 days of stock prices, given 7 days of the past
"""
class FeedBack(tf.keras.Model):
def __init__... |
from django.test import TestCase
from django.core.exceptions import ValidationError
from django.db.utils import IntegrityError
from mealplanner.models import Week, Day
class WeekTest(TestCase):
def test_days_of_a_week_are_unique_to_a_week(self):
week = Week.objects.create(week_number=1)
Day.obje... |
import re
import os
# import resource
import string
import pickle
import nltk
from bs4 import BeautifulSoup
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.model_selection import train_test_split
from sklearn import metrics
from sklearn.metrics import confusion_matrix
from pprint import pprin... |
#!/usr/bin/env python
import sys
import json
for line in sys.stdin:
try:
data = json.loads(line)
if ( 'status' in data ):
sys.stdout.write( data['status'] + "\n" )
except:
continue
|
from selenium import webdriver
driver = webdriver.Firefox(executable_path='C:\\Program Files\\Mozilla Firefox\\geckodriver-v0.29.0-win64\\geckodriver.exe')
import json
import time
import pandas as pd
# https://www.sportskeeda.com/cricket/ipl-teams-and-squads
season_obj = {
'2019': '1165643',
'2018': '1131611',... |
from __future__ import division
import numpy as np
from munkres import Munkres, print_matrix
import sys
import itertools
import math
from operator import itemgetter
from permanent import permanent as rysers_permanent
from scipy.optimize import linear_sum_assignment, minimize, LinearConstraint
from pymatgen.optimization... |
"""
Created on 5 fevr. 2013
@author: davidfourquet
inspired by Telmo Menezes's work : telmomenezes.com
"""
"""
this class inherits from networkx.Diself. It stores a distance matrix and some global variables about the network.
It allows us to update them easily instead of computing them many times.
"""
impo... |
import os
from typing import Tuple
import pygame as pg
from game_screen import map
from asset import get_sprite, BURGER, BUBBLE_FF, BUBBLE_OO, BUBBLE_OF, BUBBLE_FO
from config import SCREEN_WIDTH, SCREEN_HEIGHT
class ThreatBubble(pg.sprite.Sprite):
def __init__(self, monster_position: Tuple[int, int]):
... |
import json
import cPickle as pickle
def loadTweets(filepath='resultsFirst100K.json'):
tweets = []
with open(filepath, 'rb') as f:
for line in f:
tweet = json.loads(line)
tweets.append(tweet)
return tweets
def addToDictionary(d, key, item):
if key not in d:
d[ke... |
print('Hello, World')
print('Go away')
print(3607 * 34227)
# ----------------------------------------------------------------------
# This line is a COMMENT -- a note to human readers of this file.
# When a program runs, it ignores everything from a # (hash) mark
# to the end of the line with the # mark.
# -------... |
#!/usr/bin/env python3
"""
gpio-monitor is a program that will wait and display GPIO status when it change. The goal is
learning how to manipulate gpio through python3.
We will use some basic python module to have more versatility (as argparse) but we will embeded
it on sub-module so it will not interfer with basic GP... |
#Leo Li
#11/12/18
#the periodic table of elements
#Description: In this text-based periodic table of elements, users can view the whole table with properties, specifically the name of the element, the chemical symbol of the element, the molar mass of the element, and the atomic number of the element. It can also print ... |
# Generated by Django 2.2.1 on 2019-06-12 08:38
import bbs.save
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL)... |
'''Módulo responsável por importar textos em formato .txts e exportá-los em outros formatos'''
import os.path
import re
import pandas as pd
from pandas import DataFrame
DIRETORIO_DOS_ARQUIVOS_PADRÃO = 'base_dados/'
NOME_ARQUIVO_PLANILHA_PADRÃO = 'referencia_russo.xlsx'
def abre_documento(nome_documento, nome_pasta =... |
import pickle
import numpy as np
from wiki_dataloader.wiki_dataloader import WikiDataLoader
from word_embedding.embedding import Embedding
from classification.classify import Classify
from classification.visualize import Visualize
# Load 1k articles for 5 wikipedia categories.
wiki_data_loader = WikiDataLoader(5)
# ... |
from flask import Flask, request, render_template, session, redirect, url_for, flash, g
import db
import sys
import hashlib
import functools
import bcrypt
from models.UserModel import User
app = Flask(__name__)
app.secret_key = b'_5#y2L"F4Q8z\n\xec]/'
def login_required(func):
@functools.wraps(func)
def wrap... |
from sklearn.preprocessing.data import MinMaxScaler
import torch
from torch import nn
from torch.distributions.multivariate_normal import MultivariateNormal
import torch.nn.functional as F
import numpy as np
import matplotlib.pyplot as plt
from sklearn.preprocessing import StandardScaler
from sklearn.preprocessing impo... |
# -*- coding: utf-8 -*-
"""
Scoring Functions
Here, several scoring functions are collected.
@author: Markus Meister
"""
#%% -- imports --
import numpy as np
import pandas as pd
#%% -- Scoring Functions --
# RMSE
def rmse(p, y,convertExpM1=False):
def f(x,y):
return np.sqrt(np.mean(... |
import urllib3
def getNameNodes():
i = 0
res = {}
archivo = open('links.csv', 'rt')
for linea in archivo:
k = linea.replace(' ', '')
k = k.replace('\n', '')
if i > 0:
j = k.split('.')
if j[0] in res:
res[j[0]].append(k)
... |
from io import StringIO
import matplotlib.pyplot as plt
import numpy as np
import requests
import pandas as pd
url = "http://news.northeastern.edu/interactive/2021/08/updated-covid-dashboard/datasets/covidupdate_testData.csv"
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, lik... |
### This script is passed a smiles string ###
### searches ZINC using the url based ###
### features, downloads the resulting html ###
### and searches it for molecules. ###
import sys
import urllib2
import urllib
### input
### command: python <this_script> <filename> <tan_cutoff> <zinc_return_coun... |
import math
# Qt
from PyQt5.QtCore import Qt
from PyQt5.QtCore import QPoint
from PyQt5.QtCore import QLine
from PyQt5.QtGui import QBrush
# API
from Arrow import *
from PipelineObjects import PipelineObject
class Pipeline:
def __init__(self, objects=[], dtype=float):
self.objects = objects
def __len__(self):
... |
apikey="<--put your NCBI key here-->"
ncbo_key="<--put your NCBO key here-->"
|
from __future__ import print_function
from setuptools import setup, find_packages
from setuptools.command.test import test as TestCommand
import io
import codecs
import os
import sys
import EcxAnx
import tests
here = os.path.abspath(os.path.dirname(__file__))
class PyTest(TestCommand):
def finalize_options(self... |
from ast import literal_eval
import numpy as np
import matplotlib.pyplot as plt
import itertools, copy
def sizeof(z): return np.sqrt(z.real**2 + z.imag**2)
def map_(z, c=0): return (z)**2 + c
def to_complex(u): return np.complex(u[0], u[1])
def in_M(z):
c = copy.copy(z)
count = 0
while sizeof(z) <=2:
if cou... |
# encoding:utf-8
from __future__ import unicode_literals
from helpers.director.shortcut import page_dc
from helpers.director.engine import BaseEngine,page,fa,can_list,can_touch
from django.contrib.auth.models import User,Group
from helpers.func.collection.container import evalue_container
from helpers.maintenance.upda... |
import pygame
import global_variables as gv
btn_x_left_ratio = 1 / 50
btn_x_right_ratio = 52 / 50
btn_y_top_ratio = 4 / 50
btn_y_bottom_ratio = 51 / 50
class TitleScreenView:
def __init__(self, window):
pygame.font.init()
self.__display = window.display
self.__surface = window.surface
... |
import zope.interface
from buddydemo.interfaces import IPostalInfo, IPostalLookup
class Info:
zope.interface.implements(IPostalInfo)
def __init__(self,city,state):
self.city, self.state = city, state
class Lookup:
zope.interface.implements(IPostalLookup)
_data = {
'12345': ('Piliyandala', 'Western'... |
def solution(n, k):
# 10진수 일 때는 바로 진행
if k == 10:
# count('')
Pn = str(n).split('0')
for _ in range(Pn.count('')):
Pn.remove('')
else:
# k진수일 때 자리수 구하기
length = 0
k_str = []
while k ** length <= n:
length += 1
k_str.... |
# -*- coding: utf-8 -*-"""
"""
This module registers images to the database, The CLI to this operation has
been depricated.
"""
import argparse, argcomplete
import os
import os.path as osp
import sys
from .lamplight import image_info, save_images
from . import model as mod
from .utility import commit... |
from OpenGL.GL import *
from glew_wish import *
import glfw
from math import *
import random
class Piso:
posicionX=0
posicionY=0
def dibujar(self):
glPushMatrix()
glTranslate(self.posicionX, self.posicionY, 0.0)
glBegin(GL_POLYGON)
glColor3f(0.0941, 0, 0.2... |
###
### Copyright (C) 2018-2019 Intel Corporation
###
### SPDX-License-Identifier: BSD-3-Clause
###
from ....lib import *
from ..util import *
spec = load_test_spec("vpp", "scale")
@slash.requires(have_gst)
@slash.requires(*have_gst_element("msdk"))
@slash.requires(*have_gst_element("msdkvpp"))
@slash.requires(*have... |
# $ fab git_pull -f env.py
# $ fab git_pull:repo=dotfiles -f env.py
from fabric.api import *
from fabric.contrib.console import confirm
# It is important to know that these command-line switches are interpreted before
# your fabfile is loaded: any reassignment to env.hosts or env.roles in your
# fabfile will overwri... |
from django.shortcuts import render_to_response, get_object_or_404
from django.template import RequestContext
from django.http import HttpResponseRedirect, HttpResponse
from django.core.urlresolvers import reverse
from django.template import RequestContext
from italy.models import Regioni, Provincie, Comuni
def index(... |
"""
This type stub file was generated by pyright.
"""
import os
from __future__ import absolute_import
from datetime import datetime, tzinfo
from contextlib import contextmanager
from typing import Callable, Dict, Generator, Iterator, List, Optional, TypeVar, Union
from babel.core import Locale
from babel.support impo... |
'''
Created on Jan 9, 2017
@author: Steinert Robotics
'''
import argparse
import cv2
import imutils
from collections import deque
import numpy as np
ap = argparse.ArgumentParser()
ap.add_argument("-v", "--video",
help="path to the (optional) video file")
ap.add_argument("-b", "--buffer", type=int, d... |
import json
from datetime import date, timedelta
from decimal import *
from math import ceil
from typing import List
import isodate
import pdfkit
import requests
from jinja2 import Environment, FileSystemLoader, select_autoescape
from slugify import slugify
templates_env = Environment(
loader=FileSystemLoader('te... |
import os
import os.path
import pathlib
from typing import Any, Callable, Optional, Sequence, Tuple, Union
from PIL import Image
from .utils import download_and_extract_archive, verify_str_arg
from .vision import VisionDataset
class OxfordIIITPet(VisionDataset):
"""`Oxford-IIIT Pet Dataset <https://www.robots... |
import math
def length(x, y):
return math.sqrt(x * x + y * y)
def rotate_vec(x, y, a):
return x * math.cos(a) - y * math.sin(a), x * math.sin(a) + y * math.cos(a)
def fix(x, y, origin_width, origin_height):
flag = False
if x < 0:
x = 0
flag = True
if x > origin_width - 1:
... |
#!/usr/bin/python
# Filename: CaesarCipher.py
# Author: Hercules Lemke Merscher
class CaesarCipher(object):
''' Cifra de Cesar.'''
def encrypt(self, msg, key):
if msg == None:
return None
size = len(msg)
encrypted_msg = []
for i in range(size):
cha_i... |
import unittest
from katas.kyu_6.lotto_6_of_49 import \
check_for_winning_category, number_generator
class Lotto6of49TestCase(unittest.TestCase):
def setUp(self):
self.winning_numbers = number_generator()
def test_equal_1(self):
self.assertEqual(len(self.winning_numbers), 7)
def tes... |
import speech_recognition as sr
from datetime import *
import pyttsx3
import wikipedia
import webbrowser
import os
import subprocess
import ctypes
import time
import pyjokes
import random
from requests import get
from googlesearch import search
engine = pyttsx3.init("sapi5")
voices = engine.getPropert... |
import gspread
from oauth2client.service_account import ServiceAccountCredentials
import os
from google.oauth2 import service_account
from google.cloud import firestore
import RPi.GPIO as GPIO
import time, sys
from gpiozero import Servo
from time import sleep
IN_FLOW_SENSOR = 23
OUT_FLOW_SENSOR = 24
#TRIG1 = 17 #lev... |
import torch
import torch.nn as nn
import torch.optim as optim
from torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence
import os
from torch.utils.data import Dataset, DataLoader
from data_set import MyData, logger, collate_fn
import numpy as np
class Network(nn.Module):
def __init__(self, in_d... |
def new(X, Y, room, team, num):
if room.find("1") == -1: # 방이 다 비었을 때
room = "1"*Y + room[Y:]
team[num] = "%d:%d:%d" % (X, 0, Y)
print("%d %d" % (1, Y))
return room, team, 0
elif room.find("0") == -1 or room.find("%s" % "0"*Y) == -1: # 모든 방이 사용중일 때, 원하는 평수의 방이 없을 때
print(... |
import sys
import boto3
import os
def list_objects(start_after="tt0000000/"):
bucket = os.environ["MOVIES_BUCKET"]
client = boto3.client('s3')
objects = client.list_objects_v2(
Bucket=bucket,
Prefix='tt',
StartAfter=start_after,
Delimiter="/",
)
return objects... |
from prodict import Prodict
from aioredis.pool import ConnectionsPool
class Partner:
init: str
sync: str
class State(Prodict):
redis_pool: ConnectionsPool
partners: Prodict
def get_partner(self, partner) -> Partner:
if partner:
return self.partners.get(partner, None)
|
"""
Copyright 2017-2018 Fizyr (https://fizyr.com)
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 or agreed to in w... |
import pygame
import time
import random
#import subprocess
#import os
pygame.init()
gameDisplay = pygame.display.set_mode()
pygame.display.set_caption('Get Over Here Mr.Mike!!!')
clock = pygame.time.Clock()
def blitImg(img, x, y):
gameDisplay.blit(pygame.image.load(str(img)),(x,y))
def read_file(filename):
... |
def tidyNumber(n):
l_n = list(str(n))
return sorted(l_n) == l_n
'''
Definition
A Tidy number is a number whose digits are in non-decreasing order.
Task
Notes
Number passed is always Positive .
Return the result as a Boolean
Input >> Output Examples
tidyNumber (12) ==> return (true)
Explanation:
... |
# -*- coding: utf-8 -*-
from collections import Counter
class Solution:
def domainToLevels(self, domain):
parts = domain.split(".")
if len(parts) == 3:
return [".".join(parts[-3:]), ".".join(parts[-2:]), parts[-1]]
elif len(parts) == 2:
return [".".join(parts[-2:]... |
#! /usr/bin/env python
from djl_ui import *
from djl_input import *
from djl_post_responder import *
from djl_post_processor import *
djl_seperator()
print_exit_tip()
fb = FacebookAccessInput()
fb.show()
year = YearInput(fb.me["birthday"])
year.show()
processor = PostProcessor(year.birthdate, fb)
processor.get_pos... |
from sys import stdin, stdout
n = int(input())
negitives = []
positives = []
for i in range(2):
negitives.append([])
positives.append([])
sums = 0
answer = [0]*n
for i in range(n):
x = [float(x) for x in input().split()][0]
# print(x)
if x < 0:
if abs(int(x) - x) >= 10**-6:
negitives[1].append((i, x))
sum... |
#!/usr/bin/env python
# Copyright (c) 2012 Google Inc. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""
Verifies that a project hierarchy created with the --generator-output=
option can be built even when it's relocated to a different path.... |
n = int(raw_input())
arr = list()
for i in range(1,n+1):
if i%3 == 0 and i%5 ==0:
arr.append("FizzBuzz")
elif i%3 == 0:
arr.append("Fizz")
elif i%5 == 0:
arr.append("Buzz")
else:
arr.append(str(i))
print arr |
# Let us denote A -> B as the process where B is obtained by summing all
# the factorial of the digits of A.
# We have:
# 145 -> 145
# 169 -> ... -> 169
# 871 -> ... -> 871
# 872 -> ... -> 872
#
# For a natural number A, we denote NonRepeatTerm(A) to be the number of
# non-repeating terms in the chain A... |
# pihsm: Turn your Raspberry Pi into a Hardware Security Module
# Copyright (C) 2017 System76, Inc.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at y... |
from food_planner.settings import ITEM_LOC, PRICE_LOC, MEAL_LOC
PRICES = """chicken2breast,300.0,0.006
eggs,12.0,0.170833333
ham,10.0,0.1
tortilla_wraps,8.0,0.11875
edam,10.0,0.175
2avocado,2.0,1.25
4_pork_loins,4.0,0.75
petit_pois,1000.0,0.0013
baby_potatoes,1000.0,0.001
asparagus_tips,125.0,0.0144
2_salmon,2.0,1.62... |
import factory
from users.models import User
class UserFactory(factory.django.DjangoModelFactory):
class Meta:
model = User
|
# coding=utf-8
from flask_wtf import FlaskForm
from wtforms import StringField, SubmitField, TextAreaField
from wtforms.validators import Required, Length
from flask_pagedown.fields import PageDownField
class NameForm(FlaskForm):
name = StringField(u'你的名字?', validators=[Required()])
submit = SubmitField(u'提交'... |
from django.contrib import admin
from .models import Article, Video
class ArticleAdmin(admin.ModelAdmin):
fieldsets = [
('Critical Information', {'fields': ['title', 'publisher', 'time']}),
('Others', {'fields': ['description', 'part_1', 'part_2', 'part_3']}),
]
list_display = ('title', 'p... |
print("Day 1 - Python Print Function")
print("The function is declared like this:")
print("print('what to print')")
# can use \n between what we want to print to put it on different lines too; see below
# print("Day 1 - Python Print Function\nThe Function is declared like this:\nprint('what to print;)") |
# -*- coding: utf-8 -*-
"""
Created on Wed Mar 13 16:25:56 2019
@author: Administrator
"""
for i in range(1,10):
s=" "
for j in range(1,10):
s+=str.format("{0:1}*{1:1}={2:<2} ",i,j,i*j)
print(s)
print('上三角输出')
a = 1
while a <=9: #外层循环控制行数
b = 1
while b <= a: #内层循环控制列数
print("%... |
import xlrd
import xlwt
from collections import Counter
def filterBookListMaker(book,bookRule):
sheetrule = bookRule.sheet_by_name('字段对照表')
sheetRuleCol = sheetrule.col_values(0)
taDef = sheetrule.row_values(sheetRuleCol.index('天安'))#天安表
taofDef = sheetrule.row_values(sheetRuleCol.index('天安')+2)#天安表所属... |
#
# This file is part of LUNA.
#
# Copyright (c) 2020 Great Scott Gadgets <info@greatscottgadgets.com>
# SPDX-License-Identifier: BSD-3-Clause
""" Interfaces to LUNA's PSRAM chips."""
import unittest
from amaranth import Signal, Module, Cat, Elaboratable, Record, ClockDomain, ClockSignal
from amaranth.hdl.rec import... |
import os, sys, requests, tweepy
from bs4 import BeautifulSoup
from datetime import datetime
import logging
logger = logging.getLogger()
ch = logging.StreamHandler(sys.stdout)
ch.setLevel(logging.INFO)
frmt = logging.Formatter('%(asctime)s - %(name)s:%(levelname)s - %(message)s')
ch.setFormatter(frmt)
logger.addHandle... |
#!/usr/bin/env python3
#
# Copyright (c) 2019, the Dart project authors. Please see the AUTHORS file
# for details. All rights reserved. Use of this source code is governed by a
# BSD-style license that can be found in the LICENSE file.
# Simple tool for verifying that sources from the standalone embedder do not
# di... |
"""controller_ver3 controller."""
# You may need to import some classes of the controller module. Ex:
# from controller import Robot, Motor, DistanceSensor
from controller import Robot
from controller import InertialUnit
from controller import Gyro
from controller import Keyboard
from controller import Motor
import ma... |
#
# @lc app=leetcode.cn id=1122 lang=python3
#
# [1122] 数组的相对排序
#
# @lc code=start
class Solution:
def relativeSortArray(self, arr1: List[int], arr2: List[int]) -> List[int]:
rank = {x:i for i,x in enumerate(arr2)}
def CMP(x):
return rank[x] if x in arr2 else x+1000
arr... |
#coding=utf-8
from numpy import *
def loadTrainData(trainFile):
fp = open(trainFile)
lines = fp.readlines()
docLabel, docVec = [], []
for tmp in lines:
line = tmp.strip().split(' ')
docLabel.append(int(line[0]))
docVec.append([int(i) for i in line[1:]])
return doc... |
from django.urls import path
from alimentos.views import food, create_food, delete_food, update_food
urlpatterns = [
path('food/', food, name='food'),
path('create_food/', create_food, name='create_food'),
path('update_food/<int:id>', update_food, name="update_food"),
path('delete_food/<int:id>', dele... |
#!/usr/bin/python
from Emakefun_MotorHAT import Emakefun_MotorHAT, Emakefun_Servo
import time
mh = Emakefun_MotorHAT(addr=0x60)
myServo = mh.getServo(1)
speed = 9
while (True):
myServo.writeServoWithSpeed(0, speed)
time.sleep(1)
myServo.writeServoWithSpeed(90, speed)
time.sleep(1)
myServo.writeS... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('basketball', '0019_auto_20150818_1944'),
]
operations = [
migrations.AlterField(
model_name='game',
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Filename: __init__.py
# @Date: 2020/3/6
# @Author: Mark Wang
# @Email: wangyouan@gamil.com
from .path_info import PathInfo
class Constants(PathInfo):
GVKEY = 'gvkey'
COUNTRY = 'country'
COUNTRY_ISO3 = 'country_iso3'
COUNTRY_ISO3N = 'country_iso3n'
... |
from typing import List
from fastapi import APIRouter
from starlette.responses import JSONResponse
from app.response.tags import TagsAllRespose
from app.api.operation.tags import create_tag, get_tags
from app.schemas.tags import Tag, TagCreate
router = APIRouter()
@router.post("/add_tag/", response_model=Tag, tags... |
import time
import Board
print('''
**********************************************************
********功能:幻尔科技树莓派扩展板,串口舵机控制例程*******
**********************************************************
----------------------------------------------------------
Official website:http://www.lobot-robot.com/pc/index/index
Online mal... |
#!/usr/bin/python
'''
Cue_Control_Middleware.py
Written by Andy Carluccio
University of Virginia
This file is designed to run on a properly configured YUN Linux Environment
Extensive documentation is available at:
Good things to know about communication with the Arduino environment:
1. The first int sent is always t... |
from sklearn.preprocessing import StandardScaler
from sklearn.preprocessing import MinMaxScaler
from sklearn.preprocessing import RobustScaler
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
# Generalizar -> Scaling(data_train,data_test,columns,metodo):
def Scaling_StandardScale... |
# GUESS GAME
def guess_game(s_no):
# The secret code will be stored here
secret_name = s_no
# The answer of the user will be stored here temporarily
guess = ""
# The number of times the user has guessed from beginning
guess_counts = 0
# The number of times the user can guess
guess_limit ... |
"""This script is used to generate a BPSK or QPSK OFDM signal to transmit using USRPs.
Usage:
- Generate a BSPK signal:
python3 generate_ofdm.py
- Generate a QPAK signal:
python3 generate_ofdm.py --use_qpsk=True
"""
from __future__ import print_function, division
from utils import ofdm_util as... |
import tools
import Chrome_driver
from time import sleep
import zipfile
import os
import shutil
from shutil import copyfile
import Changer_windows_info as changer
import db
from os.path import join, getsize
import luminati
def get_updateinfo():
print('======get_updateinfo')
sql_content = "select * from update_... |
from app.DAOs.MasterDAO import MasterDAO
from app.DAOs.AuditDAO import AuditDAO
from psycopg2 import sql, errors
class PhotoDAO(MasterDAO):
"""
All Methods in this DAO close connections upon proper completion.
Do not instantiate this class and assign it, as running a method
call will render it useless... |
from flask import Flask, request
from newspaper import Article
import tensorflow as tf
import numpy as np
from flask_cors import CORS
ml = 2500
model_path = 'model/V3/'
# load vocab
dict_vocab = []
try:
with open(model_path + 'vocab.txt', 'r') as inf:
for line in inf:
dict_vocab.append(eval(line))
vocab = dict... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.4 on 2017-11-20 22:36
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.Crea... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.