text stringlengths 38 1.54M |
|---|
from tkinter import *
import numpy as np
from PIL import Image, ImageTk
from datetime import datetime
now = datetime.now()
# Palettes de couleurs
#----------------------
col_hex = ["#03071e", "#370617", "#6a040f", "#9d0208", "#d00000", "#dc2f02", "#e85d04", "#f48c06", "#faa307", "#ffba08"]
#col_hex = ["#386641", "#6... |
from speedysvc.serialisation.RawSerialisation import \
RawSerialisation
class ServerProviderBase:
___init = False
def __init__(self, server_methods):
"""
TODO!!!! ===========================================================
:param server_inst:
"""
# Couldn't see mu... |
from newsplease import NewsPlease
def get_news_attributes(news_url):
article = NewsPlease.from_url(news_url)
return article |
"""
LeetCode 211
"""
class Node:
def __init__(self, is_word=False):
self.is_word = is_word
self.next = dict()
class WordDictionary:
def __init__(self):
self.root = Node()
def addWord(self, word: str):
cur = self.root
for i in range(len(word)):
c = wo... |
from django.contrib import admin
from .models import Contact
@admin.register(Contact)
class ContactAdmin(admin.ModelAdmin):
list_display = (
'position_title',
'full_name',
'show_delegates',
'show_partners',
'show_judges',
)
ordering = ['position_title'] |
import argparse
from src import ProblemState
from src.input_parser import InputParser
class AutonomousTheoremProver(object):
def __init__(self, _problem_state: ProblemState):
self.problem_state = _problem_state
def prove(self):
"""
Autonomous Theorem Prover
=================... |
#This webscraping code is designed to spider data from ca.gov about reservoir levels.
#The user inputs a reservoir code from this site (https://cdec.water.ca.gov/misc/daily_res.html)
#Along with a starting date and a number of months from the starting date.
#The program reads html with BS4, cleans the data, takes the r... |
# -*- coding: utf-8 -*-
""" wrapper functions for DensOp """
import ctypes
from ctypes.util import find_library
import pathlib
import math
import numpy as np
import qlazy.config as cfg
from qlazy.util import get_lib_ext, densop_check_args
from qlazy.QState import QState
from qlazy.DensOp import DensOp
lib = ctypes.CD... |
#@+leo-ver=4-thin
#@+node:zorcanda!.20051208141646:@thin Phaser.py
import javax.swing as swing
import java.awt.event as aevent
import java.awt as awt
import java
class Phaser( swing.JPanel, aevent.ActionListener ):
'''This class gradually phases a component into the gui when added.
Also does phasing out if ... |
"""
Group_4 Capstone Project
Copyright (c) 2019
Licensed Northeatern unniversity
"""
import numpy as np
# Create a function to make column values(string) to consistent
def flag_brands(col_name, file_name, dest_col, Dict):
"""
:param col_name: Column Name to perform changes
:param file_name: Data... |
import scrapy
import pickle
import zlib
import time
import re
from lxml import html
from bson.binary import Binary
from NeoScrapy.items import BitCoinTalkLink, BitCoinTalkComment, BitCoinTalkUserProfile, BitCoinTalkUserStat, \
BitCoinTalkUserHistory
class BttSpider(scrapy.Spider):
name = 'bitcointalk'
all... |
from odoo import models, fields, tools, api, _
from odoo.modules.module import get_module_resource
import base64
import re
from odoo.exceptions import ValidationError
from lxml import etree
from odoo.tools.misc import DEFAULT_SERVER_DATE_FORMAT
class ResUsersStudent(models.Model):
_inherit = "res.users"
_descr... |
# Module: get_matrix.py
# Description: get matrix combined pro and rna data together
import pandas as pd
import hashlib
import os
data_dir = "/home/amber/Documents/Final-project/data/"
train_pro = data_dir + "a_total_pro.csv"
train_rna = data_dir + "a_total_rna.csv"
tab_file = data_dir + "a_sum_tab.csv"
outputfil... |
# Dependencies
import pandas as pd
import numpy as np
from adtk.detector import ThresholdAD
from adtk.visualization import plot
from adtk.data import validate_series
# Import ecommerce data and specify date column for datetime indexing
DATE_COL = 'date'
csv_data = 'ecommerce_data.csv'
def load_data():
global dat... |
N, Ma, Mb = [int(_) for _ in input().split()]
T = [[int(_) for _ in input().split()] for i in range(N)]
dp = [[float('inf') for i in range(401)] for i in range(401)]
dp[0][0] = 0
sum_a = 0
sum_b = 0
for x in range(N):
a, b, c = T[x]
sum_a += a
sum_b += b
for i in list(range(a, sum_a+1))[::-1]:
... |
card = "Process={spin} PChannel={PChannel} VegasNc0=1000000 MReso={mass} GaReso={width} DecayMode1={DecayMode1} DecayMode2={DecayMode2} {couplings} LHAPDF=NNPDF30_lo_as_0130/NNPDF30_lo_as_0130.info ReadCSmax"
cardname = "{spin_forname}{prod}To{decaymode}To{decaymode_final}_{width_forname}_M-{mass}_13TeV-JHUgenV6.input"... |
# oop
# Classes should be singular
class PlayerCharacter:
# class object attribute (static not dynamic) doesn't change
membership = True
# constructor method/instantiate/init
def __init__(self, name,age):
if (PlayerCharacter.membership):
# self allows you to have a reference to som... |
""" Unit tests for the xlrx module
@author: David Megginson
@organization: UN Centre for Humanitarian Data
@license: Public Domain
@date: Started 2020-03-20
"""
import unittest
import xlsxr
from . import resolve_path
class TestWorkbook(unittest.TestCase):
def setUp(self):
self.workbook = xlsxr.Workbook... |
# 크루스칼에 대해 들어가기 전 '서로소 집합'이란 것에 대해 알아야 합니다
# 서로소집합이란 겹치는 원소가 없는 집합들입니다
# 즉 정점이 5개 있는 그래프는 초기에 정점 하나 씩, 5개의 집합이 있는 서로소 집합이 생깁니다
# 서로소 집합 자료구조를 이용해서 Union-find 알고리즘을 이용하면 두 개의 원소가 같은 집합인지 판단할 수 있습니다
# 크루스칼이란 프림처럼 확장하며 탐색하는 게 아닌 거리에 따라 최솟값부터 연결하는 구조입니다
# 크루스칼은 프림과 다르게 양방향인것을 의식해서 start, end를 각각 추가안해주고 한번만 연결해줘도 괜찮습니다(uni... |
from itertools import islice
import os
import pandas as pd
#Extracting Proteins in a file
def ExtractingProteins(m):
f = open('proteins.txt','w')
infile = open(m, 'r')
text = infile.readlines()
for j in (text):
print (j[0:6])
f.write(j[0:6])
f.write('\n')
f.close()
Extractin... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
#2016 root <root@VM-17-202-debian>
from math import sqrt
nums = {int(sqrt(x)) for x in range(30)}
print nums
#prints > set([0, 1, 2, 3, 4, 5])
|
from flask import Blueprint
register = Blueprint('register', __name__)
from app.register import views |
def resp_success_status(msg: str, **data) -> dict:
"""
返回成功
:param msg:
:param data:
:return:
"""
if data and data != {}:
return {
'code': 200,
'message': f'{msg} 成功',
'data': data
}
else:
return {
... |
def main():
# escribe tu código abajo de esta línea
"""
Dame el número de mensajes: 38
Dame el número de megas: 3.1
Dame el número de minutos: 78
El costo mensual es: 95.28
"""
num_mensajes = int(input("Dame el número de mensajes: "))
num_megas = float(input("Dame el número de megas... |
# -*- coding: utf-8 -*-
import smtplib
from email.mime.text import MIMEText
from email.mime import base
from email.mime import multipart
import os
class EmailLibrary(object):
ROBOT_LIBRARY_SCOPE = 'Global'
def __init__(self):
print 'send email utility'
def send_mime_mail (self,from_user,from_p... |
import sys
if '../..' not in sys.path:
sys.path.append('../..')
import numpy as np
import matplotlib.pyplot as plt
import sec_emission_model_furman_pivi as fp
import mystyle as ms
from scipy.constants import e as qe
plt.close('all')
ms.mystyle(12)
linewid = 2
me = 9.10938356e-31
def del_elas_ECLOUD(energy, R_0=... |
#
# MLDB-832-select_star.py
# mldb.ai inc, 2015
# this file is part of mldb. copyright 2015 mldb.ai inc. all rights reserved.
#
from mldb import mldb
"""
This test checks that different select statements return the right columns
"""
def check_res(res, value):
assert res.status_code == value, res.text
return ... |
import re, collections, html5lib
from selenium import webdriver
from bs4 import BeautifulSoup
from enchant import DictWithPWL
from enchant.checker import SpellChecker
# ---- Inicia selenium ----
driver = webdriver.Firefox ()
url = "file:///C:/Users/QUALITY/Desktop/tst.html"
driver.get(url)
rawHTML ... |
from BallGame import *
from Wall import *
from Obstacle import *
##from RedObstacle import *
##from PurpleObstacle import *
from GreenObstacle import *
game = BallGame(width=800, height=650, maxSpeed=250,
moveDir='mouse dir')
## moveDir='to mouse')
for i in range(10):
w = Wall (400, 325+... |
from flask_wtf import FlaskForm
from wtforms import Form, BooleanField, StringField, TextAreaField, validators
from wtforms.validators import DataRequired
class MusicLibrary(FlaskForm):
title = StringField('Song Title', validators=[DataRequired()])
band = StringField('Band Name', validators=[DataRequired()])
... |
# DO NOT EDIT THIS FILE. This file will be overwritten when re-running go-raml.
from flask import Blueprint
import handlers
coolness_api = Blueprint('coolness_api', __name__)
@coolness_api.route('/coolness', methods=['POST'])
def CreateSomethingCool():
"""
It is handler for POST /coolness
"""
retur... |
#-------------------------------------------------------------------------------
# Name: module1
# Purpose:
#
# Author: Tanmya
#
# Created: 04/08/2019
# Copyright: (c) Tanmya 2019
# Licence: <your licence>
#-------------------------------------------------------------------------------
... |
#!/usr/bin/env python
###############################################################################
#
# Main Application for 1D Image
#
###############################################################################
import sys
import numpy
from math import *
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtC... |
import os
__version__ = '1.0.6'
__license__ = 'MIT'
__author__ = 'mmsa12'
name = "EmoTFIDF"
PACKAGE_DIR = os.path.dirname(os.path.abspath(__file__)) |
n=input('Introduza um qualquer valor: ')
print('Introduziu uma letra maiúscula', n.isupper())
print('Introduziu um número ou uma letra', n.isalnum())
print('Introduziu um número decimal', n.isdecimal())
print('Introduziu uma letra minúscula', n.islower()) |
# Generated by Django 3.1.2 on 2020-10-22 13:40
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('MyFacebook', '0008_auto_20201022_1338'),
]
operations = [
migrations.AlterField(
model_name='details',
name='Passwor... |
###########################################################
# Author: Orion Crocker
# Filename: __init__.py
# Date: 05/18/20
#
# client init
# self explanatory
###########################################################
import sys
from client.irc_client import IRCClient
assert sys.version_info[0] == 3, "Requires p... |
# If Conditions
is_male = False
is_tall = True
if is_male or is_tall:
print("You are a male or tall or both")
else:
print("You are neither male nor tall")
if is_male and is_tall:
print("You are a tall male")
elif is_male and not(is_tall):
print("You are a short male")
elif not(is_male) and is_tall:
... |
from django import forms
from django.shortcuts import get_object_or_404
from django.forms import ModelForm, ChoiceField
from .models import League
class LeagueCreateForm(forms.ModelForm):
class Meta:
model = League
fields = ['name', 'password', 'owner_amount', 'skater_amount', 'goalie_amount', 'draft_goalies'... |
from django.contrib import admin
from league.models import Owner, Player, Team, League, Transaction, trade, team_trade, add, drop, add_drop, Roster
admin.site.register(Owner)
admin.site.register(Player)
admin.site.register(Team)
admin.site.register(League)
admin.site.register(Transaction)
admin.site.register(trade)
ad... |
from flix.core2.markerList import MarkerList
from flix.web.serverSession import ServerSession
import flix
import flix.core2.mode
import flix.fileServices
import flix.fileServices.fileLocal
import flix.fileServices.repathDefault
import flix.web.serverSession
import flix.plugins.pluginDecorator
from flix.cor... |
from flask import Flask, render_template
from modules import convert_to_dict
from flask_bootstrap import Bootstrap
app = Flask(__name__)
Bootstrap(app)
elements_list = convert_to_dict("Periodic_Table.csv")
@app.route('/')
def index():
ids_list = []
name_list = []
for element in elements_list:
ids... |
from regression_tests import *
# Little endian 64-bit dynamic library
class TestMachoDynamicLE(Test):
settings = TestSettings(
tool='fileinfo',
input='macho_x86_64.dylib',
args='--json --verbose'
)
def setUp(self):
assert self.fileinfo.succeeded
def test_analyze_basic_... |
from django import forms
class HashtagForm(forms.Form):
hashtag = forms.CharField(widget=forms.TextInput(attrs={'autofocus': 'autofocus', 'id': 'hashtag'}))
|
# python元组
list = ("chenweilong",1,3.1415926,"longbaba")
tlist = ("tlist",123)
print(list)#输出完整元组
print(list[0])#第一个
print(list[0:3])#第一个到第三个
print(list[1:])#到结尾
print(tlist * 2)
print(list + tlist)
list[0] = "longlong"#元组元素不可改变 他是只读的 |
from random import randrange
def shuffle(myList):
taken, newList = myList[:], myList[:]
length = len(myList)
for i in range(length):
taken[i] = ''
iterations = 0
for i in range(length):
correct = False
while not correct:
rnum = randrange(0, length)
if ... |
import torch as t
import torch.nn as nn
class FocalLoss(nn.Module):
def __init__(self, alpha=0.25, gamma=2.0):
super(FocalLoss, self).__init__()
self.alpha = alpha
self.gamma = gamma
def forward(self, preds, targets):
pos_mask = (targets == 1).float()
#print("num", pos_ma... |
# Installed Package Python(3.7) ...!
#
# import numpy
# import matplotlib
# import cv2
# import scipy
# import skimage |
from tree import *
class Node:
def __init__(self,key):
self.data = key
self.left = None
self.right = None
def childrenSum(root):
left = 0
right = 0
if root is None or root.left is None and root.right is None:
return 1
else:
if root.left is not None:
... |
class DNode:
def __init__(self, val):
self.val = val
self.next = None
self.prev = None
def traverse(self):
vals = []
while(self != None):
vals.append(self.val)
self = self.next
return vals
... |
import time
from multiprocessing import Process
import os
import config
from messagebroker import MessageBroker
from worker import Worker
CICLE_SLEEP_TIME = config.GENERAL['cycle_sleep_time']
MAX_PROCESS = config.GENERAL['max_process']
MAX_GENERAL_ERRORS = config.ERROR_HANDLER['max_general_errors']
GENERAL_ERROR_TIME... |
def rho (decay_str):
while True:
if ' rho ' in decay_str:
decay_str = decay_str.replace(" rho ", " rho(770) ")
if ' rho0 ' in decay_str:
decay_str = decay_str.replace(" rho0 ", " rho(770) ")
if decay_str.find(" rho ") == -1:
if decay_str.find(" rho0 ") == -1:... |
"""
jsonrpc11base tests
"""
import json
import jsonrpc11base
from jsonrpc11base.service_description import ServiceDescription
from jsonrpc11base.errors import APIError
import pytest
import os
class MyError(APIError):
code = 123
message = "My error"
def __init__(self, id):
self.error = {
... |
import unittest
from ray.rllib.algorithms.registry import (
POLICIES,
get_policy_class,
get_policy_class_name,
ALGORITHMS_CLASS_TO_NAME,
ALGORITHMS,
)
class TestPolicies(unittest.TestCase):
def test_load_policies(self):
for name in POLICIES.keys():
self.assertIsNotNone(get... |
from collections import defaultdict
from collections import defaultdict
from collections import defaultdict
class UCTNode:
def __init__(self, state, parent=None):
"""
- n_visits is the number of visits in this node
- n_a is a dictionary {key, value} where key is the action taken from
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*- #
from __future__ import unicode_literals
AUTHOR = 'Omar Quimbaya'
SITENAME = 'San Antonio Developers'
SITEURL = ''
THEME = 'themes/brutalist'
PATH = 'content'
TIMEZONE = 'America/Chicago'
DEFAULT_LANG = 'en'
# Feed generation is usually not desired when developing
FEE... |
from colorama import init, Back, Fore, Style
class ColourfulPrint:
def __init__(self):
init(autoreset=True)
@staticmethod
def format_p1_name(text):
return Fore.CYAN + Style.BRIGHT + text
@staticmethod
def format_p2_name(text):
return Fore.RED + Style.BRIGHT... |
'''
Given a non-negative number - N. Print N!
Input Format
Input contains a number - N.
Constraints
0 <= N <= 10
Output Format
Print Factorial of N.
Sample Input 0
5
Sample Output 0
120
'''
number = int(input())
factorial = 1
if number < 0:
print("0")
else:
for itr in range(1, number+1):
factoria... |
import numpy
import elect
import bound_reader
print()
print(elect.add(1, 2))
print()
print(elect.magic_array())
print()
print(elect.magic_decade())
print()
print(elect.magic_matrix())
print()
print(elect.random_cube(3,3,3,3.45))
print()
print(elect.random_cube(3,3,3,3))
print()
print(elect.subtract(3.34, 7.98))
... |
from flask import Flask, render_template, request, redirect
app = Flask(__name__)
@app.route('/')
def home():
return render_template('./index.html')
@app.route('/index.html')
def home2():
return home()
@app.route('/<file_name>')
def page_loader(file_name):
return render_template(f'./{file_name}')
@app.... |
from glob import glob
from os.path import basename, splitext
from setuptools import find_packages, setup
PROJECT_URL = 'https://github.com/melexis/warnings-plugin'
requires = [
'junitparser>=1.0.0,<2.0',
'ruamel.yaml>=0.17.21',
]
setup(
name='mlx.warnings',
url=PROJECT_URL,
use_scm_version={
... |
from django.db.models.signals import post_save
from django.dispatch import receiver
from asgiref.sync import async_to_sync
from channels.layers import get_channel_layer
from apps.courses.models import Evaluation
__all__ = (
"notify_user_about_new_evaluation",
)
# pylint: disable=unused-argument
# sender and **... |
import numpy as np
import cvxpy as cp
import sys
import os
import json
MINM = -100000000
#Hyperparameters
DELTA = 0.001
GAMMA = 0.999
#Define all pos
all_pos=[]
all_pos.append('C')
all_pos.append('N')
all_pos.append('S')
all_pos.append('E')
all_pos.append('W')
#Define all state
all_states=[]
all_states.append('D')
... |
import theano
import theano.tensor as T
import numpy
import cPickle
# Similarity functions ----------------------------
def L1sim(left,right):
return -T.sum(T.sqrt(T.sqr(left-right)),axis=1)
def L2sim(left,right):
return -T.sqrt(T.sum(T.sqr(left-right),axis=1))
def dotsim(left,right):
return T.sum(left*r... |
import json
class TreeNode(object):
def __init__(self, text, id, depth, parent=None, children=None):
self.text = text
self.id = id
self.depth = depth
self.children = children
self.parent = parent
self.objs = None
@staticmethod
def from_json(path):
wi... |
from django.urls import path
from ec import views
urlpatterns = [
path('item/', views.ItemListView.as_view(), name='item_list'),
path('item/<slug>', views.ItemDetailView.as_view(), name='item_detail'),
path('additem/<slug>', views.addItem, name='additem'),
path('order/', views.OrderView.as_view(), name... |
#!/usr/bin/env python3
#
# Copyright 2020 by Philip N. Garner
#
# See the file COPYING for the licence associated with this software.
#
# Author(s):
# Phil Garner, October 2020
#
# Oracle: https://bescherelle.com/conjugueur.php
# List of 'verb' forms of verbs with auxiliary être.
# First two are venir and aller
aux... |
from unittest import mock
import pytest
from movies.exceptions import MovieDoesNotExist, MultipleMoviesExist
from movies.services import (
generate_list_movies_with_people,
generate_movie_data_with_people,
)
class TestListMovieWithPeopleService:
@pytest.fixture(autouse=True)
def init_fixtures(self):... |
name = "Tam H. Nguyen"
age = 32 # Not a lie, not very young
height = 175 #cm, in inches = 175/2.54 = 68.897637795275591
height_in_inches = height / 2.54
weight = 65 #kg, in pound: lb = 65 * 2.20462 = 143.3 lb
weight_in_pound = weight * 2.20462
eyes = "Black"
teeth = "Yellow"
hair = "Black"
print(f"Let's talk about {na... |
from flask import Flask
from flask_restful import Api
import logging
from resources.parking_spot import ParkingSpot
from resources.reservation import Reservation, AddReservation
app = Flask(__name__)
api = Api(app)
api.add_resource(Reservation, '/reservation/<int:confirmation_num>')
api.add_resource(AddReservation, '/... |
'''Que tal un bucle for que cruze dos listas, seria genial no?, vamos a ver'''
creditos_inscritos={'Juan':18,'Maria':17,'Estiben':15,'Carolina':20,'Kelly':12, 'Emmanuel':20,'Luis':18,'Patricia':17}
programa={'Juan':'Ing Ambiental','Maria':'Fisica Pura','Estiben':'Administracion','Carolina':'Contaduria','Kelly':'Enfer... |
import sys
sys.path.append('../../')
from challenge import Challenge
from generate import generate_input
# Challenge(
# filename: str,
# code: str,
# challenge_input: str, <-- 默认不带input
# host_path=None, <-- 指定存放代码的路径,默认为当前路径
# timeout=None, <-- 单例超时时间,默认为5s
# cpu=None, <-- CPU个数,默认为1核
# memory=None, <-- 内存限制, 默认30M... |
#!/usr/bin/python
from mininet.net import Mininet
from mininet.topo import Topo
from mininet.link import TCLink
from mininet.log import setLogLevel
class StarTopo(Topo):
'''
A simple star topology
'''
def build(self, n=3):
switch = self.addSwitch('s1')
for h in xrange(n):
... |
from PyQt5.QtCore import pyqtSlot
from PyQt5.QtWidgets import QWidget, QFileDialog, QMessageBox
from PyQt5 import uic
from qtpy import QtWidgets
from semantic_similarity.graph_creator import build_graph
from semantic_similarity.main import compute_similarity
class FileManager(QWidget):
def __init__(self, parent,... |
# pr3_3_2
# MFCC 参数比较
from scipy.signal import *
import matplotlib.pylab as plt
from Universal import *
from MFCC import *
import numpy as np
import librosa
import math
def mel_dist(x1, x2, fs, num, wlen, inc):
"""
计算两信号x1,x2的MFCC参数和距离
:param x1: signal 1
:param x2: signal 2
:param fs: sample frequency
:param ... |
from xml.etree import ElementTree as ET
import wolframalpha
import urllib
# Consts
app_id = ''
# Variables
client = wolframalpha.Client(app_id)
def get_current_time(place):
timeRes = client.query('time in ' + place)
timePod = timeRes.pods[1]
currentTime = timePod.text
return currentTime
def get_loca... |
#########################################################
# #
# Chirs Weir #
# Tondiggidy Simonutti #
# T0ng Liu #
# Codigail Doyle ... |
import csv
from pprint import pprint
# Get the source data
data = list(csv.DictReader(open("./statestyle/data.csv", "r")))
# Create the normalizer
crosswalk = {}
for row in data:
for key, value in row.items():
if value and key not in ['type', 'stateface']:
crosswalk[value] = row
cr... |
#!/usr/bin/python
#########################################################################
# acceptor_test.py
#########################################################################
import server
import os
import unittest
import pickle
import socket
import time
import message
from message import MESSAGE_TYPE
cla... |
##---------------------------------------------------------
##
## Goods and Services Tax
##
## Define a function with one parameter, a number representing
## a wholesale price, that returns the GST component to be added
## to that wholesale price (where GST is 10%).
##
## The tests below tell us how your function ... |
# Q1, A
def reverse_word(word):
"""
請寫一個程式把裡面的字串反過來。
>>> reverse_word("junyiacademy")
'ymedacaiynuj'
"""
return "".join(reversed(word))
# Q1, B
def reverse_sentence(sentence):
"""
請寫一個程式把裡面的字串,每個單字本身做反轉,但是單字的順序不變。
>>> reverse_sentence("flipped class room is important")
'deppi... |
import numpy as np
A = [[0, 0, 1, 0, 1],
[1, 1, 0, 1, 0],
[1, 0, 0, 0, 1],
[0, 0, 0, 1, 0],
[0, 1, 0, 1, 0]]
B = np.linalg.matrix_power(A,6)
C = np.linalg.matrix_power(A,3)
print B
i = 3
print B[i-1]
for i in range (1,6):
print "Number of combinations of symbol ", i, " = ", np.sum(B[i-1]) * ... |
import json
import os
import pickle
import pandas as pd
from util.classifier import load_candidates
from util.get_keys import get_keys
from util.get_one import get_one
from util.preprocessor import labels_to_lowercase
class Level2Module:
def __init__(self, l1_module):
"""
Returns ... |
# Copyright 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
# Licensed under the Apache License, Version 2.0 (the "License").
# You may not use this file except in compliance with the License.
# A copy of the License is located at
# http://www.apache.org/licenses/LICENSE-2.0
# or in the "license" file... |
import turtle
def make_window(colr, ttle):
""" Make a window with color and title """
w = turtle.Screen()
w.bgcolor(colr)
w.title(ttle)
return w
def make_turtle(colr, sz):
""" Make a turtle with color and size """
t = turtle.Turtle()
t.color(colr)
t.pensize(sz)
return t
def c... |
import numpy as np
class Doctor:
def __init__(self, identifier):
self.id = identifier
self.status = "available"
self.schedule ={}
for slot in np.arange(8.0, 17.0, .5):
self.schedule[slot] = 'open'
def __str__(self):
return "Hello I am " + self.id
def a... |
import random
inside = 0
outside = 0
pointlist = []
def setup():
#size(500, 500)
fullScreen()
background(51)
colorMode(HSB, 100)
translate(width/2, height/2)
fill(color(40, 50, 50))
circle(0, 0, height)
def draw():
translate(width/2, height/2)
stroke(color... |
from datetime import datetime
from sqlalchemy import create_engine, Column, Integer, String, DateTime
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base
engine = create_engine('sqlite:///messagedb.sqlite3')
Base = declarative_base()
Session = sessionmaker(bind=engine)
cla... |
"""
This file solves the following problem: given a tree and a subtree find the sequence of operations m_{\alpha \beta},
such that m_{\alpha \beta}(subtree) = tree.
"""
from basic import *
from tree_polynomial import TreePolynomial
class MOperation:
# This is the class of operations m_{\alpha, \beta}... |
class Solution:
def createSortedArray(self, instructions: List[int]) -> int:
m = max(instructions)
bit = [0] * (m + 1)
def u(x):
while x <= m:
bit[x] += 1
x += x & -x
def g(x):
s = 0
while x > 0:
s... |
#!/usr/bin/env python
"""This script queries The Hive for SentinelOne generated cases older
than seven days, then checks if the resolved status is True in the
SentinelOne console. Finally it closes the associated case in TheHive
"""
import time
import re
import sys
import yaml
import datetime
import requests
from theh... |
import html
import os
import sys
from mastodon import Mastodon
import path
import ruamel.yaml
import twitter
def read_config():
cfg_path = path.Path(os.path.expanduser("~/.config/bm_bot.yml"))
return ruamel.yaml.load(cfg_path.text(), ruamel.yaml.RoundTripLoader)
def write_config(config):
cfg_path = pa... |
# Generated by Django 3.1.4 on 2021-01-05 15:19
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('polls', '0012_comments_likescount'),
]
operations = [
migrations.AlterField(
model_name='comments',
name='id_social'... |
tables = [[x*y for x in range(1,13)] for y in range(1,13)]
for table in tables:
print(''.join([str(x).rjust(4) for x in table]).lstrip())
|
EMAIL_HOST = 'smtp.naver.com'
EMAIL_PORT = 587
EMAIL_HOST_USER = 'allieuslee@naver.com'
EMAIL_HOST_PASSWORD = '1029shake'
EMAIL_USE_TLS = True
|
import unittest
from credential import Credential
class TestCredential(unittest.TestCase):
def setUp(self):
self.new_credential = Credential("steve", "king", "123456", "email@gmail.com") # create Account object
def test_init(self):
self.assertEqual(self.new_credential.credential_name, "steve... |
from Stepper import stepper
testStepper = stepper([2, 3, 4]) #[stepPin, directionPin, enablePin]
testStepper.step(360*19*4, "left",0.0005); #steps, dir, speed, stayOn
|
class MinHeap:
def __init__(self):
self.heap_list = [None]
self.count = 0
# HEAP HELPER METHODS
# DO NOT CHANGE!
def parent_idx(self, idx):
return idx // 2
def left_child_idx(self, idx):
return idx * 2
def right_child_idx(self, idx):
return idx * 2 + 1
# END OF HEAP HELPER METHODS
... |
""" Created by Shahen Kosyan 2/14/17"""
if __name__ == '__main__':
n = int(input())
home_airport = input()
flights = []
while n > 0:
n -= 1
_from, _to = input().split('->')
flights.append(_from)
flights.append(_to)
count = 0
for i in range(len(flights)):
... |
# --------------------------------------------------------------------------
# Source file provided under Apache License, Version 2.0, January 2004,
# http://www.apache.org/licenses/
# (c) Copyright IBM Corp. 2016
# --------------------------------------------------------------------------
# gendoc: ignore
def as_df... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.