text stringlengths 38 1.54M |
|---|
# Board.py
# author: James
# date: 04/12/2018
# board created
class Board:
board = []
def __init__(self):
self.board = [
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
[0, 0, 0, 0, 0],
]
# ... |
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import tkinter
from tkinter import *
import sqlite3
import xlrd
import xlwt
from tkinter import filedialog
import tkinter.messagebox
########################################################
'''数据库'''
# 创建一个连接对象,连接到本地数据库
conn = sqlite3.connect("python.db")
# 创建一个游标对象,调用其execute... |
from PIL import ImageFont, ImageDraw, Image
import sys
from random import random
from avatargenerator import colorfunc, utils
from avatargenerator.styles import AvatarStyle
def generateLetterAvatar(letter1, letter2="", styles=AvatarStyle, size=512, dir_path="", file_name=""):
if letter2:
text = lette... |
from django.shortcuts import render, redirect
from .form import AddFilmForm, AddDirectorForm
from .models import *
from django.views.generic import CreateView
from django.urls import reverse_lazy
from django.contrib.auth.mixins import LoginRequiredMixin
def home(request):
director=Director.objects.all()
film... |
# Copyright 2015 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from __future__ import absolute_import
import logging
import dependency_manager
class BinaryManager(object):
""" This class is effectively a subclass of... |
def determinant(matrix):
return (matrix[0][0]*matrix[1][1])-(matrix[0][1]*matrix[1][0])
def pMatrix(matrix,n):
if len(matrix)==2:
return determinant(matrix)
else:
result = []
for i in range(1,len(matrix)):
tmp = []
for j in range(len(matrix[0])):
... |
"""
Django settings for mvote project.
Generated by 'django-admin startproject' using Django 1.8.19.
For more information on this file, see
https://docs.djangoproject.com/en/1.8/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.8/ref/settings/
"""
# Build paths... |
#!/usr/bin/python
from meinmodul import saghallo, version
# Andere Moeglichkeit:
# from meinmodul import *
saghallo()
print 'Version', version
|
import pandas
import numpy
import datetime
import utils.time
from utils.apicalls import AppsFlyer
from utils.queries import QUERY_PAX_APPSFLYER_INSTALLS
from init.init import databseinit
from utils.paths import PATH_CUSTOS_APPSFLYER, PATH_DEFINE_VALUES, PATH_CUSTOS_GMAPS
from utils.apicalls import GoogleAds
im... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
"""
-------------------------------------
@Project :auto_test
@File :EmailUtil.py
@IDE :PyCharm
@Author :coke
@Time :2021/01/08 10:34
-------------------------------------
"""
import smtplib, os
from email.mime.text import MIMEText
from email.mime.image import ... |
from rest_framework import serializers
from app1.models import Song , Podcast ,Audiobook
class Song_serializer(serializers.ModelSerializer):
class Meta:
model = Song
fields = "__all__"
class Podcast_serializer(serializers.ModelSerializer):
class Meta:
model = Podcast
... |
from Naive525 import Solution as naive
from HT525 import Solution as ht
testcase = [
([0, 1], 2),
([0, 1, 0], 2),
([0, 1, 0, 1], 4)
]
def test_naive():
for nums, ans in testcase:
assert naive().findMaxLength(nums) == ans
def test_ht():
for nums, ans in testcase:
assert ht().find... |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... |
from tkinter import *
from tkinter import ttk
import pyttsx3
win=Tk()
win.geometry('800x180')
win.title("Text to Speech")
text = Entry(win, width=100, bg="White")
text.place(x=180, y=30)
but1 = ttk.Button(win, text="Speak", command=lambda: buttonpressed(1))
but1.grid(row=0, column=0, ipadx=50, ipady=50)
def buttonpre... |
# 1.9 String Rotation: Assume you have a method i 5 S u b s t r i n g which
# checks ifone word is a substring of another. Given two strings, 51 and 52,
# write code to check if s2 is a rotation of s1 using only one call to
# isSubstring (e.g., "waterbottle" a rotation "erbottlewat").
def string_rotation(s1, s2):
... |
# Generated by Django 3.0.8 on 2020-08-11 02:37
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),
]
ope... |
from rest_framework.pagination import PageNumberPagination
from rest_framework.response import Response
class UserInfoPagination(PageNumberPagination):
def get_paginated_response(self, data):
return Response(data)
|
# Question 14
# WAP to check if a number is armstrong
def isArmstrong(number):
power = len(str(number))
sum = 0
temp = number
while temp != 0:
sum = sum + ((temp % 10) ** power)
temp //= 10
return sum == number
number = int(input("Enter the number: "))
if isArmstrong(number):
... |
#!/usr/bin/python
tsukino=[12,14,15,16]
def numer(tsukino):
usagui=[]
usagui=tsukino[::-1]
return usagui
numer(tsukino)
print numer(tsukino)
|
# FRAKTALE
# 11-06-2021
# SMOK HEIGHWAYA
from turtle import Screen, Turtle
def smok():
obieg = 0
start = 'R'
poprzedni = 'R'
while obieg < 15:
start = poprzedni + 'R'
# ODWRÓCENIE KOLEJNOŚCI SEKWENCJI
poprzedni = poprzedni[::-1]
for x in ran... |
#You are given an integer array cost where cost[i] is the cost of ith step on a staircase. Once you pay the cost, you can either climb one or two steps.
#You can either start from the step with index 0, or the step with index 1.
#Return the minimum cost to reach the top of the floor.
class Solution:
def minCostCli... |
"""
Prints exceptions to stdout; useful for seeing errors
when running a test server
"""
class ExceptionLoggingMiddleware(object):
def process_exception(self, request, exception):
if request.META["SERVER_NAME"] != 'testserver':
import traceback
print traceback.format_exc()
|
#preprocessing for data base
import pandas as pd
base = pd.read_csv('credit-data.csv')
base.loc[base.age < 0, 'age'] = 40.92
previsores = base.iloc[:, 1:4].values
classe = base.iloc[:, 4].values
from sklearn.preprocessing import Imputer
imputer = Imputer(missing_values = 'NaN', strategy = 'm... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.8 on 2019-05-23 07:56
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('wildlifecompliance', '0200_merge_20190523_1452'),
]
operations = [
migrations.Alter... |
import os
import pandas as pd
import panel as pn
from .pn_model import StockScreener
def app(doc):
data_path = os.path.join(os.path.dirname(__file__), 'datasets/market_data.csv')
df = pd.read_csv(data_path, index_col=0, parse_dates=True)
ss = StockScreener(df)
ss.panel().server_doc(doc)
|
# -*- coding: utf-8 -*-
# Generated by Django 1.9 on 2016-03-21 15:37
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('prayers', '0015_prayer_received_at'),
]
operations = [
migrations.CreateModel(... |
# -*- coding: utf-8 -*-
""" unit test example """
from PythonTipChallenge import binary_tree
import unittest
class TestBinaryNode(unittest.TestCase):
def setUp(self):
self.node = binary_tree.BinTreeNode(value=1)
def test_value_property(self):
value = self.node.value
self.assertEqual... |
""" MacGyvers's game Classes """
import random
import pygame
from pygame.locals import*
from constants import*
class Level:
""" class who create the level """
def __init__(self, fichier):
self.fichier = fichier
self.structure = 0
def generate(self):
""" enable the level creation... |
GUESE_A_LETTER = input('enter a letter\n')
if not GUESE_A_LETTER.isalpha() and len(GUESE_A_LETTER) > 1:
print('E3')
elif len(GUESE_A_LETTER) > 1:
print('E1')
elif not GUESE_A_LETTER.isalpha():
print('E2')
else:
print(GUESE_A_LETTER.lower()) |
# Stdlib
from datetime import datetime, timedelta
from typing import Union
# External Libraries
import jwt
# Sayonika Internals
# from framework.models import User
from framework.jsonutils import CombinedEncoder
import framework.models
class JWT:
"""Class for generating and validating JWTs."""
algorithm = ... |
import random
import math
import pylab as pl
import numpy as np
from matplotlib.colors import ListedColormap
def generateData(numberOfClassEl, numberOfClasses):
data = []
for classNum in range(numberOfClasses):
centerX, centerY = random.random() * 5.0, random.random() * 5.0
for rowNum in range... |
from filterpy.kalman import KalmanFilter
import numpy as np
f = KalmanFilter (dim_x=2, dim_z=1)
f.x = np.array([[2.], # position
[2.]]) # velocity
u = np.array([[2.], # position
[3.]]) # velocity
B = np.array([[1.,0.], [0.,1.]])
F = np.array([[2.,1.], [0.,1.]])
H = np.ar... |
print('~Find and Replace~')
phrase = input('Enter a phrase:')
find_letter = input('Enter a letter to find:')
replace_letter = input('Enter a letter to replace:')
new_phrase = phrase.replace(find_letter,replace_letter)
print('Original phrase: %s'%(phrase))
print('New phrase: %s'%(new_phrase))
lists = ([i for i,char in... |
#coding:utf-8
import tornado.web
import tornado.ioloop
import tornado.httpserver
import tornado.options
from tornado.options import define,options
from tornado.web import RequestHandler,url
tornado.options.define("port",default="7890",type=int,help="runserver this is help")
class IndexHandler(tornado.web.RequestHand... |
# Files
# you can read, write and append to a file in python
#f = open("name or path", "mode", "buffer")
# here the open method has 3 parameters, name or path of the file, mode in which you want to open the file and buffer
# the third buffer parameter is optional to set the buffer size
# modes: w - when you want to wr... |
from time import sleep
from multiprocessing.dummy import threading
class ShutdownTask(object):
def __init__(self):
self.__running = True
def terminate(self):
self.__running = False
def run(self):
# 轮询方式必须根据业务来,不然没有意义
while self.__running:
print("do something")... |
#!/usr/bin/env python3
import matplotlib.pyplot as plt
file = open('kmer_contig.txt', 'r')
x_axis = []
y_axis = []
for line in file:
line = line.rstrip()
line = line.split('\t')
x_axis.append(int(line[0]))
y_axis.append(int(line[1]))
print(x_axis,y_axis)
plt.scatter(x_axis, y_axis)
plt.show()
|
# Generated by Django 3.2.3 on 2021-07-15 23:23
from django.db import migrations, models
import django.utils.timezone
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='add_flight',
fields=[
... |
import numpy as np
class CorrelacaoPerseptron2:
def __init__(self, caminho):
self.quantidade_linhas = 8012
# w1, w2, w3, w4, historico0, historico1, historico2, historico3, w0
# self.Lista_Predicoes_Predi = [[peso_incial, peso_incial, peso_incial, peso_incial, peso_incial, peso_incial, peso_incial, peso_i... |
import os
from server import APP
from script.main import delete_server
@APP.route("/instances/delete/<id>")
def instance_delete(id):
try:
delete_server(server_hash=id)
return '<h3><center>Instance deleted successfully</center></h3>'
except ValueError:
return '<center><h3>Instance not found or already de... |
import time
import json
import Cargo
import serial
import struct
from emonhub_interfacer import EmonHubInterfacer
"""
[[MBUS]]
Type = EmonHubMBUSInterfacer
[[[init_settings]]]
device = /dev/ttyUSB0
baud = 2400
[[[runtimesettings]]]
pubchannels = ToEmonCMS,
address = 100
... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
import imagekit.models.fields
class Migration(migrations.Migration):
dependencies = [
('user_auth', '0002_userdetails_residence'),
]
operations = [
migrations.AlterField(
... |
## coding: utf-8
'''
This python file is used to precess the vulnerability slices, including read the pkl file and split codes into corpus.
Run main function and you can get a corpus pkl file which map the same name slice file.
'''
from __future__ import print_function
from get_tokens import *
import os
impor... |
#Zoe Caballero Dominguez A01747247
#Mision 09: diferentes funciones utilizando listas.
# Crea una nueva lista con solo los valores pares de la lista enviada como parámetros
def extraerPares(lista):
nuevaLista = []
for dato in lista:
if dato%2 == 0:
nuevaLista.append(dato)
... |
#importing the libraries
import requests
import string
from nltk.corpus import stopwords
from nltk import word_tokenize
from nltk.tokenize import RegexpTokenizer
from nltk.stem import WordNetLemmatizer
from nltk.stem.porter import PorterStemmer
import pandas as pd
#downloading profane word list
def get_prof... |
from OpenStackAccess import OpenStack
import yaml
with open("OpenStackConfig.yaml", 'r') as ymlfile:
cfg = yaml.load(ymlfile)
access = {
'auth_url': cfg['access']['auth_url'],
'username': cfg['access']['username'],
'password': cfg['access']['password'],
'tenant_name': cfg['access']['tenant_name']... |
import unittest
from unittest import mock
import mysql.connector as connector
import mysql.connector.errors as errors
from src import msqlforapp
from src.msqlforapp import (
mysqlconnect,
create_table_people,
create_table_drinks,
insertVarintopeople,
insertVarintodrinks,
joining_drink_people,
... |
#!python2
# Tui Popenoe
# Challenge32E.py - Base 26 Multiplication
from sys import argv
values = {
'a' : 0,
'b' : 1,
'c' : 2,
'd' : 3,
'e' : 4,
'f' : 5,
'g' : 6,
'h' : 7,
'i' : 8,
'j' : 9,
'k' : 10,
'l' : 11,
'm' : 12,
'n' : 13,
'o' : 14,
'p' : 15,
'... |
from django import forms
from django.forms import widgets, ValidationError
from .models import *
class UserForm(forms.Form):
name = forms.CharField(min_length=4, label="用户名", error_messages={"required": "不能为空哦", "invalid": "格式错误了"},
widget=widgets.TextInput(attrs={"class": "form-control... |
import threading
import time
import traceback
from datetime import datetime, timezone
from typing import List
from unittest.mock import Mock
import pytest
from growthlib.domain.models import Growth
from growthlib.services import unit_of_work
pytestmark = pytest.mark.usefixtures("mappers")
def insert_Growth... |
# Generated by Django 2.2 on 2019-05-18 15:58
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('workapp', '0008_auto_20190513_1819'),
]
operations = [
migrations.CreateModel(
name='SelectCandidate',
fields=[
... |
# ┌─┐ ┌─┐
# ┌──┘ ┴──────┘ ┴──┐
# │ │
# │ ─┬┘ └┬─ │
# │ │
# │ ─┴─ │
# └───┐ ┌───┘
# │ │
# │ └──────────────┐
# │ ├─┐
# │ ┌─┘
# └┐ ┐ ┌───────┬──... |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def verticalTraversal(self, root: TreeNode) -> List[List[int]]:
g = collections.defaultdict(list)
... |
# Copyright (C) 2020 Claudio Marques - All Rights Reserved
import logging
import socket
import requests
import logging
import sys
from threading import Thread
from lib.enumerations import HttpResponseEnum
from utils import Constants
# logging.basicConfig(level=logging.INFO, filename=Constants.log_path, f... |
"""
Storage
=======
Saving and loading traces and results objects.
"""
from .auto import autosave
from .hdf5 import write_array
from .read_from_hdf5 import (
OptimizationResultHDF5Reader,
ProblemHDF5Reader,
ProfileResultHDF5Reader,
SamplingResultHDF5Reader,
load_objective_config,
read_result,
... |
"""
compute median and mean of read coverage and abundance (FPKM)for different reference genes sets
(e.g. house-keeping genes, liver-enriched genes) expressed in our RNA-Seq
Author:Rahul Das
"""
import os, sys
import csv
import numpy as np
#human housekeeping genes
def hk_genes():
supportDir = '/rawdata/projects/RNA... |
# Starting with Date & time from python libraries.
# "datetime" is a python standard module and "date", "time" & "datetime" are libraries within them
# Python importing example -
import time # Directly importing the library
from datetime import date ... |
# Check whether the given 4 points form a square or not.
p1=[int(x) for x in input().split()]
p2=[int(x) for x in input().split()]
p3=[int(x) for x in input().split()]
p4=[int(x) for x in input().split()]
s1=p1[0]+p2[0]+p3[0]+p4[0]
s2=p1[1]+p2[1]+p3[1]+p4[1]
if s1==s2:
print('yes',end='')
else:
print('no',end='')
|
class Solution(object):
def titleToNumber(self, s):
"""
:type s: str
:rtype: int
"""
# if not s:
# return 0
l = list(s)
ans = 0
for c in l:
ans = (ord(c) - ord('A') + 1) + ans * 26
return ans
def titleToNumber2(s):
... |
# -*- coding: utf-8 -*-
"""
Created on Thu May 3 12:52:55 2018
@author: nicol
"""
import numpy as np
import sklearn.gaussian_process as gp
import numpy.linalg as np
from scipy.spatial import distance
import heapq
from random import randint
import random
from random import *
import sys
import sklearn
... |
import copy
with open("Advent_7_Bags.txt", "r") as text_file:
text_lines = text_file.readlines()
compiled_lines = []
for line in text_lines:
compiled_lines.append(line.replace(".\n", ""))
import re
bag_regex = re.compile(r"""
(\d??)
\s?
... |
def LiqEtlp_pP(P,T,x_N2):
x = (P-5.63256585e+02)/2.47804800e-01
y = (T--1.74161904e+02)/1.07862000e-01
z = (x_N2-6.50773187e-01)/1.41595601e-02
output = \
1*2.19370241e+01
liq_etlp = output*1.00000000e+00+0.00000000e+00
return liq_etlp |
import time
def startTimer():
startExperiment = time.time()
def currentTime():
return str((time.time() - startExperiment) / 60)
return currentTime |
goal = [1,2,3,4,5,6,7,8,None]
def isGoal(node):
(state, yeah, path) = node
return state == goal
def swapNew(state, a, b):
copy = state[:]
copy[a], copy[b] = copy[b], copy[a]
return copy
def getHash(node):
(state, yeah, path) = node
return str(state)
def h1(node):
(state, yeah,... |
from tkinter import *
from Banco import *
from Tela_Cadastrar_Nota import *
from Tela_Relatorio import *
import ctypes
def Tela_Exibe_Notas(codigo_Usu):
def Limpa_Entry():
Entry_Codigo.delete(first=0,last=5)
Entry_Titulo.delete(first=0,last=50)
Entry_Descricao.delete(first=0,last=50)
def fechar_Janela():
... |
from google.oauth2 import service_account
import pandas_gbq
import numpy as np
import pandas as pd
import math as mt
import datetime as dt
"""[summary]
Function for scoring workload by statuses (In Progress and Done) for one employee, NumOfAllDays = 63, NumOfIntervalDays = 7
[description]
Data - pandas... |
#!/usr/bin/env python
import feedparser
from StringIO import StringIO
from lxml import etree
import requests
import json
import re
import urlparse
from os.path import expanduser
from configobj import ConfigObj
from jira.client import JIRA
config = ConfigObj(expanduser('~/.m6rc'))
config = config['jira']
JIRA_HOST = ... |
def validPhoneNumber(phoneNumber):
import re
pattern = re.compile(r"^(\(\d{3}\)\s{1}\d{3}-\d{4})$")
return True if re.match(pattern, phoneNumber) else False
|
import datetime
from . import (
index,
users,
maps,
)
def add_date_url(url):
now = datetime.datetime.now()
return f'{url}?date={now.strftime("%Y%m%d")}'
def get_subblueprints(views=[]):
blueprints = []
for view in views:
blueprints.append(view.module)
if "subviews" ... |
def add(a, b):
if b == 0:
# base case
return a
# recursive step
return add(a, b-1) + 1
|
#!/usr/bin/env python
#-*-coding: utf-8 -*-
import rospy
from std_msgs.msg import String
def talker():
pub = rospy.Publisher('chatter',String,queue_size=10) #yayıncımızı olusrutduk.
rospy.init_node('talker',anonymous=True)
rate = rospy.Rate(10) #10hz
while( not rospy.is_shutdown()):
hello_str="hello world %s" ... |
#!/usr/bin/python
import chaintools as ct
import sys
import re
f=sys.argv[1:]
dpm=[]
for input in f:
chain=re.sub('[a-z0-9]{4}-','', input[:-4])
readfile=re.sub('-[a-zA-Z]{1}', '', input)
data=open(readfile, 'r').readlines()
expdata=[line for line in data if re.match('^EXPDTA', line)]
if "NMR" in expdata[0]:
... |
from django.shortcuts import render
from django.views.generic import ListView, CreateView, DeleteView, UpdateView, TemplateView
from django.views.generic.detail import DetailView
from pelicula.models import Genero, Cliente, Pelicula
from django.template import loader
# -------------- Vista de Gen... |
#!/usr/bin/env python3
"""parse training and test data. predict CHUNK-tags via MLP classifier. create outputfile in matching format for conlleval."""
import time
from datetime import datetime
from gensim.models import word2vec
from pprint import pprint
from sklearn.model_selection import RandomizedSearchCV, GridSearchC... |
"""
**************************************************
*
Author = Abhishek Sharma <mail.abhi13@gmail.com> *
*
**************************************************
A simple script to bulk restore
"""
import threading
from s3mgr import s3mgr #run clone https://github.com/paliwalvimal/aws-s3mgr-pytho... |
# Copyright 2021, The TensorFlow Federated Authors.
#
# 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... |
# coding=utf-8
# Copyright 2015 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
unicode_literals, with_statement)
from pants.backend.p... |
import torch
import torch.nn.functional as F
from torch import nn
from dbrar.resnext import ResNeXt101
class _AttentionModule(nn.Module):
def __init__(self):
super(_AttentionModule, self).__init__()
self.block1 = nn.Sequential(
nn.Conv2d(64, 64, 1, bias=False), nn.BatchNorm2d(64), nn.... |
import numpy as np
import matplotlib.pyplot as plt
from sklearn.utils import shuffle
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import StratifiedKFold
from sklearn.neighbors import KernelDensity
from sklearn.metrics import accuracy_score
from sklearn.naive_bayes import GaussianNB
f... |
#Christopher Marotta
#January 21, 2019
#Iterative Binary Search
def find(listInput, targetNumber):
listBegin = 0
listEnd = len(listInput)-1
returnNum = -1
if (listBegin > listEnd):
returnNum = -1
elif (listBegin <= listEnd):
middleIndex = (listBegin+listEnd)//2
middleNumber ... |
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
def removeKthNode(head, k):
nodeIndeces = {}
i = 0
cur = head
while cur is not None:
nodeIndeces[i] = cur
cur = cur.next
i += 1
# print('I', i)
if k > i:
t... |
from flask import Flask
from config import Config
app = Flask(__name__)
# Make the WSGI interface available at the top level so wfastcgi can get it.
wsgi_app = app.wsgi_app
app.config.from_object(Config)
from app import route |
# Generated by Django 2.1.4 on 2018-12-31 20:11
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('data', '0004_userapi_description'),
]
operations = [
migrations.AlterField(
model_name='userapi',
name='description'... |
# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html
# useful for handling different item types with a single interface
import pymysql
class HowtoPipeline(object):
def __init__(self):
self... |
# p65 Zadanie
import random
def srednia(lista):
if lista == []:
return 0
sum = 0
licznik1 = -1000
licznik2 = 1000
for n in lista:
licznik1 += 1
wynik = licznik1 / licznik2
return wynik
print("Elementy losowo z zakresu od [-1000 do 1000]: ")
lista = []
li... |
# Generated by Django 2.0.3 on 2019-11-13 03:55
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('blog', '0006_auto_20190629_2259'),
]
operations = [
migrations.AlterField(
model_name='category',
name='description'... |
# keycontrol.py
# Charlie DeLorey
# 08/01/2019
# purpose: control arm with keyboard keys
# **program takes the current gripper state ("open" or "close") as commandline argument**
# Currently no support for end effector orientation (rx, ry, rz)
"""
KEY MAPPING
Open gripper: Close gripper:
... |
import numpy as np
from pingouin.tests._tests_pingouin import _TestPingouin
from pingouin.power import (ttest_power, anova_power)
class TestPower(_TestPingouin):
"""Test power.py."""
def test_ttest_power(self):
"""Test function ttest_power."""
nx, ny = 20, 20
d = 0.5
power = t... |
from itertools import combinations
from collections import defaultdict
from sympy.core import S, Ge, Le, symbols, nan, oo, zoo
from sympy.functions import sqrt
from sympy.logic import And
from sympy.sets import Intersection
from sympy.utilities import lambdify
from sympy.polys import Poly
from sympy.solvers import solv... |
import sys
import os
import unittest
sys.path.append(os.getcwd())
import solution
class WidgetTestCase(unittest.TestCase):
def test_s(self):
self.assertEqual(solution.solution('1'), 0)
self.assertEqual(solution.solution('2'), 1)
self.assertEqual(solution.solution('3'), 2)
self.as... |
from Unit import Unit
from dataclasses import dataclass
from Modifiers import *
from Casts import *
@dataclass(frozen=True)
class Devil(Unit):
def __init__(self):
Unit.__init__(self, "Devil", 166, 27, 25, (36, 66), 11, list([KingBuff()]), None)
|
import binascii
ihdr_start = bytearray(b'\x49\x48\x44\x52')
ihdr_end = bytearray(b'\x08\x06\x00\x00\x00')
crc32 = 0x56250434
for w in range(2000):
for h in range(2000):
ihdr = ihdr_start + w.to_bytes(4, 'big') + h.to_bytes(4, 'big') + ihdr_end
if binascii.crc32(ihdr) == crc32:
print(w, ... |
#################################################################################
# FOQUS Copyright (c) 2012 - 2023, by the software owners: Oak Ridge Institute
# for Science and Education (ORISE), TRIAD National Security, LLC., Lawrence
# Livermore National Security, LLC., The Regents of the University of
# California... |
import sys
stack = []
string = "(())())"
def VPS(string) :
top = -1
for x in string :
if x == "(" :
stack.append("(")
top = top + 1
elif x == ")" :
if top == -1 :
return "NO"
del stack[top]
top = top - 1
print(stack)
if top == -1 :
return "YES"
else :
... |
#Takes input of user
num = input('Give me a number: ')
num = int(num)
#Takes input and checks remainder to see if it equals odd or even
is_odd = num % 2 != 0
#returns true if it is odd and false if it is even
if is_odd:
print(f'{num} is odd')
else:
print(f'{num} is even') |
from js9 import j
class cloudapi_images(j.tools.code.classGetBase()):
"""
Lists all the images. A image is a template which can be used to deploy machines.
"""
def __init__(self):
pass
self._te={}
self.actorname="images"
self.appname="cloudapi"
#cloudapi... |
class Solution:
def countSquares(self, matrix):
counter = 0
for i in range(len(matrix)):
for j in range(len(matrix[0])):
if matrix[i][j] == 1 and i != 0 and j != 0:
matrix[i][j] = min(matrix[i-1][j-1], matrix[i-1][j], matrix[i][j-1]) + 1
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Jul 3 13:49:33 2018
@author: tom verguts
create figs (and table) of chapters 1
"""
import matplotlib.pyplot as plt
import numpy as np
np.set_printoptions(precision = 3, suppress = True)
x = np.linspace(start = -1, stop = 3, num = 20)
xvals = [2.7, 2.... |
from enum import Enum
class ActionType(Enum):
MOVE = 0
SWITCH = 1
DETAILS_CHANGED = 2
FORM_CHANGED = 3
REPLACE = 4
SWAP = 5
CANT = 6
FAINT = 7
FAIL = 8
DAMAGE = 9
HEAL = ... |
import os
class FileSystemIncludeHandler:
def __init__(self):
self.__locations = []
def addSearchPath(self, location):
self.__locations.append( location )
def getIncludeContent(self, file):
for location in self.__locations:
for directory, dirNames, file... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.