content stringlengths 0 894k | type stringclasses 2
values |
|---|---|
from machine import Pin
import utime
#import pyb
class IRQCounter:
provides = ["count", "time_since_last_trigger"]
def __init__(self, port, trigger, cooldown):
self.counter = 0
self.last_trigger = utime.ticks_ms()
def irq_handler(pin):
now = utime.ticks_ms()
i... | python |
from __future__ import print_function, division, absolute_import, unicode_literals
from builtins import bytes, dict, object, range, map, input, str
from future.utils import itervalues, viewitems, iteritems, listvalues, listitems
from io import open
import pytest
import rfpipe
from astropy import time
def test_create... | python |
'''
* Copyright (c) 2022 MouBieCat
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, dist... | python |
from setuptools import setup
setup(
name="azblob",
version="1.0.1",
author="Philipp Lang",
packages=["azblob"],
url=("https://github.com/plang85/azblob"),
license="MIT License",
description="Download Azure blobs.",
long_description=open("README.md").read(),
long_description_content... | python |
# program to create set difference.
setx = set(["apple", "mango"])
sety = set(["mango", "orange"])
setz = setx & sety
print(setz)
#Set difference
setb = setx - setz
print(setb) | python |
#!/usr/bin/env python
# coding: utf-8
# #NUMBER 1: DATA PREPARATION
# In[4]:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
print("Done importing libraries")
# In[5]:
#path_to_file= "C:... | python |
import util
from copy import deepcopy
from collections import defaultdict
def solver(paticipants, pizas):
pizas_key = defaultdict(list)
for i, v in enumerate(pizas):
pizas_key[v].append(i)
acc = [[], 0]
print('File loaded :: size of piza : %s, paticipants : %d ' % (len(pizas), paticipants))
d... | python |
"""
[LeetCode] 708. Insert into a Cyclic Sorted List
# Insert into a Cyclic Sorted List linspiration
Problem
Given a node from a cyclic linked list which is sorted in ascending order, write a function to insert a value into the list such that it remains a cyclic sorted list. The given node can be a reference to any ... | python |
# Estadística para Datos Univariados
Datos univariados (o data univariada) son datos que se describen con una sola variable. Por ejemplo, las alturas de los compñaeros de clase son datos univariados. El propósito principal del análisis de datos univariados es la descripción de los datos.
El análisis de datos univari... | python |
# Copyright 2018-2021 Xanadu Quantum Technologies 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 law or... | python |
from twisted.plugin import IPlugin
from twisted.words.protocols import irc
from txircd.module_interface import Command, ICommand, IModuleData, ModuleData
from txircd.utils import ircLower
from zope.interface import implements
from fnmatch import fnmatchcase
class WhoCommand(ModuleData, Command):
implements(IPlugin, I... | python |
"""Abstractions for handling operations with reaktor `WishList` and `Voucher` (`GiftCards`) objects."""
| python |
#! /usr/bin/env python3
# -*- coding: utf8 -*-
"""Port of NeHe Lesson 26 by Ivan Izuver <izuver@users.sourceforge.net>"""
from OpenGL.GL import *
from OpenGL.GLUT import *
from OpenGL.GLU import *
from PIL import Image
import sys
import gc
ESCAPE = b'\033'
# Number of the glut window.
window = 0
LightAmb = (0.7, 0... | python |
import functools
import queue
try:
import statistics
stdev = statistics.stdev
mean = statistics.mean
except ImportError:
stdev = None
def mean(l):
return sum(l) / len(l)
try:
import time
clock = time.perf_counter
except Exception:
import timeit
clock = timeit.default_time... | python |
from output.models.nist_data.atomic.non_negative_integer.schema_instance.nistschema_sv_iv_atomic_non_negative_integer_pattern_3_xsd.nistschema_sv_iv_atomic_non_negative_integer_pattern_3 import NistschemaSvIvAtomicNonNegativeIntegerPattern3
__all__ = [
"NistschemaSvIvAtomicNonNegativeIntegerPattern3",
]
| python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.constant.ParamConstants import *
class MybankCreditLoantradeNewloanarRepayApplyModel(object):
def __init__(self):
self._apply_repay_fee = None
self._apply_repay_int = None
self._apply_repay_penalty = None
... | python |
"""
# Syntax of search templates
"""
import re
# SYNTACTIC ANALYSIS OF SEARCH TEMPLATE ###
QWHERE = "/where/"
QHAVE = "/have/"
QWITHOUT = "/without/"
QWITH = "/with/"
QOR = "/or/"
QEND = "/-/"
QINIT = {QWHERE, QWITHOUT, QWITH}
QCONT = {QHAVE, QOR}
QTERM = {QEND}
PARENT_REF = ".."
ESCAPES = (
"\\\\",
"\\ "... | python |
# Copyright (c) 2017-present, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the license found in the LICENSE file in
# the root directory of this source tree. An additional grant of patent rights
# can be found in the PATENTS file in the same directory.
import torch
from . import Fairse... | python |
#! /usr/bin/env python3
import client
import common
import start
if __name__ == '__main__':
start.check_dirs()
common.w.replace_windows(*start.get_windows())
common.w.curses = True
config = start.read_config()
colour = start.validate_config(config)
if colour:
start.set_colours(config[... | python |
from unittest import TestCase
import string
from assertions import assert_result
from analyzer.predefined_recognizers.iban_recognizer import IbanRecognizer, IBAN_GENERIC_SCORE, LETTERS
from analyzer.entity_recognizer import EntityRecognizer
iban_recognizer = IbanRecognizer()
entities = ["IBAN_CODE"]
def update_iban_... | python |
"""
Define the list of possible commands that TeX might handle. These commands
might be composed of multiple instructions, such as 'input', which requires
characters forming a file-name as an argument.
"""
from enum import Enum
class Commands(Enum):
assign = 'ASSIGN'
relax = 'RELAX'
left_brace = 'LEFT_BRA... | python |
aluno = dict()
nome = str(input('Nome: '))
media = float(input('Média: '))
aluno['nome'] = nome
aluno['media'] = media
if media < 5:
aluno['status'] = 'Reprovado!'
elif 5 <= media < 7:
aluno['status'] = 'Recuperação!'
else:
aluno['status'] = 'Aprovado!'
print(f'Nome: {aluno["nome"]}.')
print(f'Média: {aluno["m... | python |
import config
config.setup_examples()
import infermedica_api
if __name__ == '__main__':
api = infermedica_api.get_api()
print('Look for evidences containing phrase headache:')
print(api.search('headache'), end="\n\n")
print('Look for evidences containing phrase breast, only for female specific symp... | python |
from flask import Flask, request, jsonify, redirect, url_for
import pyexcel.ext.xlsx
import pandas as pd
from werkzeug import secure_filename
UPLOAD_FOLDER = 'upload'
ALLOWED_EXTENSIONS = set(['xlsx'])
app=Flask(__name__)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
def allowed_file(filename):
return '.' in fil... | python |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import logging
import rasa_core
from rasa_core.agent import Agent
from rasa_core.policies.keras_policy import KerasPolicy
from rasa_core.policies.memoization import Memoi... | python |
import abc
from collections import namedtuple, OrderedDict
from typing import Collection, Optional, Union, Iterable, Tuple, Generator, Set, Dict, List, Any, Callable
from profilehooks import timecall
import logging
import itertools
import random
from .actions import pass_actions, tichu_actions, no_tichu_actions, pl... | python |
#!/usr/bin/python
import heat as h
dir='trace-azure-globe-6dc-24h-202005170045-202005180045'
src_dc_l = ['eastus2']
dst_dc_l = ['westus2', 'francecentral', 'australiaeast']
for src in src_dc_l:
for dst in dst_dc_l:
if dst is src:
continue
df=dir+'/' + src+'-'+dst+'.log.txt'
print df
##h.lat_he... | python |
# Time: O(s*t) # for every node in s, you traverse every node in t.
# Space: O(s) # number of nodes in s
# Mar 30th '20
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def isSubtree(s... | python |
#!/usr/bin/python
# coding=utf-8
import logging
import itertools
import rdflib
# Import NameSpace RDF
from rdflib.namespace import RDF
from rdflib import Literal
# Import Namespace class for create new RDF Graph
from rdflib import Namespace
logging.basicConfig()
rdf = rdflib.Graph()
rdf.load("data.owl")
FOAF = Na... | python |
import django
from ..base import *
from ..i18n import *
from .services import *
from ..static import *
django.setup() | python |
import os
import json
import StringIO
import shapely
from shapely.geometry import shape, mapping
from flask import Flask, request, send_file, jsonify, render_template
from werkzeug.utils import secure_filename
ALLOWED_EXTENSIONS = set(['js', 'json', 'geojson'])
app = Flask(__name__)
def allowed_file(filename):
ret... | python |
'''
Author: Hanqing Zhu(hqzhu@utexas.edu)
Date: 2022-04-07 10:38:34
LastEditTime: 2022-04-08 23:57:19
LastEditors: Hanqing Zhu(hqzhu@utexas.edu)
Description:
FilePath: /projects/ELight/core/models/__init__.py
'''
from .vgg import * | python |
# -*- encoding: utf-8 -*-
from __future__ import unicode_literals
from django import forms
from django.core.exceptions import ValidationError
from datetime import datetime
#from suit.widgets import SuitDateWidget, SuitTimeWidget, SuitSplitDateTimeWidget
#from .models import PrintTask
class TaskForm(forms.ModelForm):
... | python |
from __future__ import absolute_import
import warnings
from django.template import loader
from django.utils import six
from .. import compat
from . import filterset, filters
class DjangoFilterBackend(object):
default_filter_set = filterset.FilterSet
@property
def template(self):
if compat.is_c... | python |
from .rawheader import HeaderFactory, LAS_FILE_SIGNATURE
| python |
testinfra_hosts = ["ansible://mariadb-centos7"]
def test_mariadb_el7_config(host):
innodb7 = host.file('/etc/my.cnf.d/innodb.cnf')
assert not innodb7.contains('innodb_large_prefix=1')
testinfra_hosts = ["ansible://mariadb-centos8"]
def test_mariadb_el8_config(host):
innodb8 = host.file('/etc/my.cnf.d/... | python |
import requests
from .okra_base import OkraBase
from .utils import validate_id, validate_dates, validate_date_id
class Balance(OkraBase):
""" This handles all balance requests to the okra API. This contains the following functions.\n
Key functions:
get_balances -- This returns the realtime balance for e... | python |
# Import
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import axes3d
from warmUpExercise import warmUpExercise
from computeCost import computeCost
from gradientDescent import gradientDescent
from plotData import plotData
# Machine Learning Online Class - Exercise 1:... | python |
# Generate the randomized beta map for further testing changes of prediction accuracy and discrimination
from os.path import join as pjoin
import cifti
import numpy as np
from ATT.iofunc import iofiles
def randomize_ROI(rawdata, mask=None):
"""
Randomize the averaged data in ROI that defined by the mask
i... | python |
from discord.ext import commands
from .formats import plural
class StringMaxLengthConverter(commands.Converter):
"""A converter that only accepts strings under a certain length."""
def __init__(self, length):
super().__init__()
self.length = length
async def convert(self, ctx, arg):
... | python |
# Generated by Django 3.1.8 on 2021-06-08 17:11
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('sections', '0003_delete_techstack'),
]
operations = [
migrations.CreateModel(
name='TechStack',... | python |
import cv2 as cv
import numpy as np
import numpy.ma as ma
import scipy.interpolate
from scipy.interpolate import Akima1DInterpolator
def findTransform(fn):
pattern_size = (15,8)
trg_img_size = (1920, 1080)
scale_fact = 10 # to speed up calculations
print('processing %s... ' % fn)
orig = cv.... | python |
#!/usr/bin/env python3
#-*-coding:utf-8-*-
import random
import time
try:
import thread
except ImportError:
import _thread as thread
import board
import neopixel
from gpiozero import Button
import json
import requests
import websocket
pixels = neopixel.NeoPixel(board.D18, 60+13, auto_write=False)
#0-60:tape, 6... | python |
# -*- coding: utf-8 -*-
# Copyright 2020 Google LLC
#
# 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 o... | python |
"""Elabore um programa que calcule o valor a ser pago por um produto,
considerando o seu preço normal e condição de pagamento:
- a vista dinheiro/cheque: 10% de desconto
- em até 2x no cartão: preco normal
- 3x ou mais no cartão: 20% de juros
"""
import time
print('========== Calculando Valores de Um Produto ==========... | python |
from django.contrib.gis import admin
from vida.vida.models import Person, Shelter, Track, Form, Report, Note, Profile
import uuid
import helpers
from django.conf import settings
class VidaAdmin(admin.OSMGeoAdmin):
openlayers_url = settings.STATIC_URL + 'openlayers/OpenLayers.js'
class NoteInline(admin.StackedIn... | python |
# 혁진이의 프로그램 검증
# DFS를 이용한 풀이
# https://swexpertacademy.com/main/code/problem/problemDetail.do?contestProbId=AV4yLUiKDUoDFAUx&categoryId=AV4yLUiKDUoDFAUx&categoryType=CODE
import sys
sys.setrecursionlimit(10**9)
def dfs(x, y, dir, cur):
global r, c
stat=False
rot=False
if cmd[x][y]=='>':
dir=... | python |
def add():
x = input("Enter your number 1")
y = input("Enter your number 2")
z = x+y
print("Your final result is: ", z)
def multiply():
x = input("Enter your number 1")
y = input("Enter your number 2")
z = x*y
print("Your final result is: ", z)
def factorial():
a=int(input())
f=1
if(a>1):
fo... | python |
from typing import NewType
from pydantic import SecretStr
from mirumon.api.api_model import APIModel
SharedKey = NewType("SharedKey", SecretStr)
class CreateDeviceBySharedKeyRequest(APIModel):
name: str
shared_key: SharedKey
| python |
# Flask imports
from flask import Blueprint, render_template
errors_blueprint = Blueprint('errors_blueprint', __name__)
@errors_blueprint.app_errorhandler(404)
def page_not_found(error):
return render_template('error_pages/404.html'), 404
@errors_blueprint.app_errorhandler(500)
def internal_server_error(error):... | python |
"""empty message
Revision ID: e47fb2d3a756
Revises:
Create Date: 2017-06-30 17:30:56.066364
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'e47fb2d3a756'
down_revision = None
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto gene... | python |
from __future__ import division
from operator import attrgetter
from ryu.base import app_manager
from ryu.controller import ofp_event
from ryu.controller.handler import MAIN_DISPATCHER, DEAD_DISPATCHER
from ryu.controller.handler import CONFIG_DISPATCHER
from ryu.controller.handler import set_ev_cls
from ryu.lib import... | python |
import torch
from torch.utils.data import DataLoader, Dataset
import numpy as np
from librosa.util import find_files
from torchaudio import load
from torch import nn
import os
import re
import random
import pickle
import torchaudio
import sys
import time
import glob
import tqdm
from pathlib import Path
CACHE_PATH = ... | python |
"""
A component which allows you to send data to an Influx database.
For more details about this component, please refer to the documentation at
https://home-assistant.io/components/influxdb/
"""
import logging
import voluptuous as vol
from homeassistant.const import (
EVENT_STATE_CHANGED, STATE_UNAVAILABLE, STA... | python |
# Generated by Django 3.1.7 on 2021-03-07 16:44
from django.db import migrations
import django_enumfield.db.fields
import events.models
class Migration(migrations.Migration):
dependencies = [
('events', '0047_participant_date_of_birth'),
]
operations = [
migrations.AlterField(
... | python |
import warnings
import numpy as np
import torch
import torch.nn.functional as F
from sklearn import metrics
from torch.utils.data import DataLoader, SequentialSampler, TensorDataset
from tqdm import tqdm
from datasets.bert_processors.abstract_processor import convert_examples_to_features
from utils.preprocessing impo... | python |
from django.conf import settings
from django.conf.urls.static import static
from django.urls import path
from . import views
urlpatterns = [
path('', views.events_home, name='events_home'),
# Events urls.
path('eventos/', views.events_list, name='event_list'),
path('eventos/<pk>/configuracion/', views.... | python |
from ipykernel.comm import Comm
from varname import nameof
import inspect
# import threading
from multiprocessing import Process
from .mwserver import run_server, run_server_from_id
import uuid
import subprocess
import threading
# jupyter notebook --ip='*' --NotebookApp.token='' --NotebookApp.iopub_data_rate_l... | python |
import sys, os, collections, copy
import numpy as np
import pandas as pd
from pandas import DataFrame, Series
data_fn = 'data/WikiQA-train.tsv'
X = pd.read_csv(data_fn, sep='\t', header=0, dtype=str, skiprows=None, na_values='?', keep_default_na=False)
| python |
# -*- coding:utf-8 -*-
'''!
@file interrupt.py
@brief Interrupt detection of free fall, an interrupt signal will be generated in int1 once a free fall event occurs.
@n When a free-fall motion is detected, it will be printed on the serial port.
@n When using SPI, chip select pin can be modified by changing ... | python |
from django.conf.urls import url
from rest_framework_jwt.views import obtain_jwt_token
from . import views
from .views import RegisterUsernameCountAPIView, UserCenterInfoAPIView, UserEmailInfoAPIView,UserEmailVerificationAPIView, \
AddressViewSet
urlpatterns = [
url(r'^usernames/(?P<username>\w{5,20})/count/$... | python |
## Plotting functions
# Imports
import math
import matplotlib.pyplot as plot
import pandas
import seaborn
from evolve_soft_2d import file_paths
################################################################################
def histogram(
template,
tm: str,
data: list,
t: str,
y: str,
x:... | python |
from .box_colombia import BoxColombia
from .box_daily_square import BoxDailySquare
from .box_don_juan import BoxDonJuan
from .box_don_juan_usd import BoxDonJuanUSD
from .box_office import BoxOffice
from .box_partner import BoxPartner
from .box_provisioning import BoxProvisioning
| python |
from mintools import ormin
class Chaininfo(ormin.Model):
bestblockhash = ormin.StringField()
blocks = ormin.IntField()
mediantime = ormin.IntField()
class Block(ormin.Model):
height = ormin.IntField(index=True)
blob = ormin.TextField()
class Tx(ormin.Model):
blockhash = ormin.StringField(ind... | python |
# -*- coding: utf-8 -*-
"""Simple OSC client."""
import socket
try:
from ustruct import pack
except ImportError:
from struct import pack
from uosc.common import Bundle, to_frac
if isinstance("", bytes):
have_bytes = False
unicodetype = unicode # noqa
else:
have_bytes = True
... | python |
# Copyright (c) 2018 Robin Jarry
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distrib... | python |
import sys
import re
from setuptools.command.test import test as TestCommand
from setuptools import setup
from setuptools import find_packages
metadata = dict(
re.findall("__([a-z]+)__ = '([^']+)'", open('consul/__init__.py').read()))
requirements = [
x.strip() for x
in open('requirements.txt').readlin... | python |
import uuid
from app.api.models.namespaces import NamespacePrimaryKey, NamespaceSchema, NamespaceResources, NamespacePrimaryKeyProjectID
from app.db import namespaces, database
async def post(payload: NamespaceSchema):
query = namespaces.insert().values(payload.dict())
return await database.execute(query=que... | python |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... | python |
import logging
from webapp2_extras.auth import InvalidAuthIdError, InvalidPasswordError
from authentication import BaseHandler
from authentication import app
@app.route('/login', 'login')
class LoginHandler(BaseHandler):
def get(self):
self._serve_page()
def post(self):
username = self.requ... | python |
import random
class Dealer:
'''
Represents the dealer in the game.
Responsible for drawing a card and showing it.
Responsible for showing the current card.
Attributes: last_card, current_card
'''
def __init__(self):
#Initializes the last card and sets current card equal to it
... | python |
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
import os,sys,inspect
currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
parentdir = os.path.dirname(currentdir)
sys.path.insert(0,parentdir)
from twitter import updater
from selenium import webdriver
from selenium.webdriver.common.k... | python |
import cv2
import numpy as np
from sklearn.metrics import mutual_info_score
import time
from tkinter import Tk
from tkinter.filedialog import askopenfilename
start_time = time.time()
detector = cv2.ORB_create()
Tk().withdraw()
path1 = askopenfilename(initialdir = "E:\Research\Datasets\MVS",
fi... | python |
# Copyright 2013-2019 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class Geant4(CMakePackage):
"""Geant4 is a toolkit for the simulation of the passage of particl... | python |
# import_export_ballotpedia/views_admin.py
# Brought to you by We Vote. Be good.
# -*- coding: UTF-8 -*-
from .controllers import attach_ballotpedia_election_by_district_from_api, \
retrieve_ballot_items_for_one_voter_api_v4, \
retrieve_ballot_items_from_polling_location, retrieve_ballot_items_from_polling_loc... | python |
from django.contrib import admin
from . import models
admin.site.site_header = 'FAIR Data Management'
class BaseAdmin(admin.ModelAdmin):
"""
Base model for admin views.
"""
readonly_fields = ('updated_by', 'last_updated')
list_display = ('last_updated',)
def save_model(self, request, obj, f... | python |
#!/usr/bin/env python
from I3Tray import *
from os.path import expandvars
from icecube import icetray,dataclasses,dataio,phys_services
amageofile = expandvars("$I3_SRC/phys-services/resources/amanda.geo")
icecubegeofile = expandvars("$I3_SRC/phys-services/resources/icecube.geo")
tray = I3Tray()
tray.AddModule("I3Inf... | python |
import pytest
import numpy as np
from mcalf.utils.smooth import moving_average, gaussian_kern_3d, smooth_cube, mask_classifications
from ..helpers import class_map
def test_moving_average():
x = np.array([0.4, 1.2, 5.4, 8, 1.47532, 23.42, 63, 21, 14.75, 6, 2.64, 0.142])
res = moving_average(x, 2)
asser... | python |
def Validate(num, tar):
v = 0
while num>0:
v += num
num //= 10
return v == tar
if __name__ == '__main__':
s = input()
digits = len(s)
s = int(s)
chushu = 1
chenshu = 1
for i in range(digits-1):
chenshu*=10
chushu = chushu*10+1
success = False
... | python |
import urllib,json
def btc_alarm():
VOL_BUY=20
VOL_DIFF=100
url = "https://api.bitfinex.com/v1/trades/btcusd?limit_trades=500"
trades=json.loads(urllib.urlopen(url).read())
past_time=trades[0]['timestamp']-5*60
buy_volume=[float(trade['amount']) for trade in trades if trade['type']=='buy' and... | python |
from manim_imports_ext import *
class KmpPrefixScene(AlgoScene):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.data = "cbccbcbccb"
def compute_prefix_function(self):
t = self.data
n = len(t)
prefix = np.zeros(n, dtype=int)
prefix[0] = ... | python |
################################################################################
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this... | python |
from itertools import permutations
class Solution:
def getProbability(self, balls: List[int]) -> float:
setOfBalls = []
currentBall = 1
for b in balls:
setOfBalls.extend([currentBall] * b)
currentBall += 1
equal = 0
total = 0
for choice in... | python |
from .item import get_basket_item_model
from .basket import get_basket_model, BaseBasket
from ..settings import basket_settings
if basket_settings.is_dynamic:
from .item import DynamicBasketItem
| python |
import pandas as pd
import plotly.express as px
prices = pd.read_csv("prices_history.csv", index_col=0)
prices.index = pd.to_datetime(prices.index, unit="s")
prices_change = prices / prices.mean()
print(prices_change)
prices_total_change = (prices_change.iloc[-1][:] - prices_change.iloc[0][:]) * 100
print(prices_total... | python |
from bitresource import resource_registry
from http_resource import HttpResource
@resource_registry.register()
class KrakenHttpResource(HttpResource):
name = 'kraken'
endpoint_url = 'https://api.kraken.com/0/public/'
CurrencyResource = KrakenHttpResource('Assets')
MarketResource = KrakenHttpResource('Asset... | python |
from spidriver import SPIDriver
s = SPIDriver("/dev/ttyUSB0") # change for your port
s.sel() # start command
s.write([0x9f]) # command 9F is READ JEDEC ID
print(list(s.read(3))) # read next 3 bytes
s.unsel() # end command
| python |
'''
Which stocks move together?
In the previous exercise, you clustered companies by their daily stock price movements. So which company have stock prices that tend to change in the same way? You'll now inspect the cluster labels from your clustering to find out.
Your solution to the previous exercise has already bee... | python |
'''
Made By Sai Harsha Kottapalli
Tested on python3
About : SSH Command
Use : make a connection to SSH server and run a command
'''
import sys
import paramiko
import subprocess
import argparse
def command(ip_addr,username,pwd,cmd):
client = paramiko.SSHClient()
#can use keys for authentication
#client.load_h... | python |
from PySide2.QtCore import QAbstractItemModel, QModelIndex, Qt
from hexrd.ui.tree_views.tree_item import TreeItem
KEY_COL = 0
class BaseTreeItemModel(QAbstractItemModel):
KEY_COL = KEY_COL
def columnCount(self, parent):
return self.root_item.column_count()
def headerData(self, section, orient... | python |
#!/usr/bin/env python3
"""Tests that all evidence codes seen in NCBI's gene2go have description."""
from __future__ import print_function
__copyright__ = "Copyright (C) 2016-2019, DV Klopfenstein, H Tang. All rights reserved."
__author__ = "DV Klopfenstein"
import os
from goatools.associations import dnld_ncbi_gene... | python |
# Unless explicitly stated otherwise all files in this repository are licensed
# under the Apache License Version 2.0.
# This product includes software developed at Datadog (https://www.datadoghq.com/).
# Copyright 2018 Datadog, Inc.
import copy
import traceback
import re
import logging
import unicodedata
from aggreg... | python |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import pytest
from parglare import GLRParser, Grammar, Parser, ParseError
from parglare.exceptions import SRConflicts
def test_lr2_grammar():
grammar = """
Model: Prods EOF;
Prods: Prod | Prods Prod;
Prod: ID "=" ProdRefs;
ProdRefs: ... | python |
from hatano.errors import HatanoError
import boto3
import zipfile
import shutil
import subprocess as sp
import os
import random
import string
import sys
import json
global_conf_file = './hatano_settings.json'
region = boto3.session.Session().region_name
class ZipSrc:
def __init__(self, src, stage):
self... | python |
########################################################
# neweggQuickSearch.py is a script which automates
# automates the process of searching for products
# and returns important information back in a CSV.
# Libraries Used: urllib.request and bs4 (BeautifulSoup)
# neweggQuickSearch.py asks the user to inp... | python |
from django.forms import ModelForm
from workouts.models import WorkoutSession
class WorkoutSessionForm(ModelForm):
class Meta:
model = WorkoutSession
fields = [
'name',
'description',
'location',
'workout_date',
]
| python |
import pandas as pd
import numpy as np
import plotly.graph_objects as go
import dash
dash.__version__
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input,Output
import dash_bootstrap_components as dbc
import plotly.io as pio
import os
print(os.getcwd())
df_input_l... | python |
# -*- coding: utf-8 -*-
"""
Created on Fri Nov 12 22:57:49 2021
@author: kylei
"""
import matplotlib.pyplot as plt
import time
import numpy as np
import matplotlib as mpl
import copy
# plt.style.use("science")
mpl.rcParams["figure.dpi"] = 300
plt.style.use("ieee")
class GAAP:
def __init__(
self,
... | python |
# Copyright 2019 Xilinx 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 law or agreed to in writin... | python |
# Kivy stuff
from kivy.uix.widget import Widget
from kivy.uix.label import Label
from kivy.lang import Builder
from kivy.properties import ObjectProperty, ListProperty
from kivy.graphics import Color, Ellipse, Line
from kivy.clock import Clock
from kivy.lang import Builder
from kivy.factory import Factory
from kivy.cor... | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.