text stringlengths 38 1.54M |
|---|
import numpy as np
from pandas import Series,DataFrame
import pandas as pd
np.random.seed(12345)
data = DataFrame(np.random.randn(1000, 4))
print data.describe()
#cap values outside the interval -3 to 3
data[np.abs(data)>3] = np.sign(data)*3
|
from datetime import datetime
from pytz import timezone
DATETIME_FORMAT = '%m/%d/%Y %H:%M:%S'
def format_datetime(datetime_value: datetime) -> str:
try:
return datetime_value.strftime(DATETIME_FORMAT)
except Exception:
return ''
def convert_datetime_to_local_timezone(value: str, datetime_fo... |
from wsgame import wsgame
import threading
import time
class MyThread(threading.Thread):
def __init__(self,serverip,acctoken,player,sfname):
super(MyThread, self).__init__()
self.serverip=serverip
self.acctoken =acctoken
self.player=player
self.sfname=sfname
def run(self)... |
''' Implement Heap Data Structure (using Array).
1. minHeap
2. maxHeap
'''
def minHeapify(arr, i):
index = i
n = len(arr)
leftChild = 2*i + 1
rightChild = 2*i + 2
if (rightChild < n) and (arr[index] > arr[rightChild]):
index = rightChild
if (lef... |
#!/usr/bin/python3
# parse keystone.common.wsgi and return number of failed login attempts
loginfail = 0 # counter for fails
getcount = 0 # counter for GET requests
postcount = 0 # counter for number of POST requests
# open the file for reading
with open("/home/student/mycode/attemptlogin/keystone.common.wsgi") as kfi... |
from flask import Flask
from flask import render_template
from flask import request
from flask import redirect
from flask import session
from flask import url_for
from flask_pymongo import PyMongo
app = Flask(__name__)
# events = [
# {"event":"Deltamath Assignment 1", "date":"2020-09-25"},
# {"even... |
# coding: utf-8
# In[42]:
get_ipython().magic('matplotlib inline')
import warnings
warnings.filterwarnings('ignore')
import seaborn as sns
import pandas as pd
import numpy as np
sns.set()
import matplotlib.pyplot as plt
from matplotlib import style
from sklearn.cross_validation import train_test_split
style.use('fi... |
# voice.py
# Voice handler for Discord
import discord
import asyncio
from discord.ext import commands
from plugins.utils import checks
import youtube_dl
class VoiceHandler:
def __init__(self, bot):
self.bot = bot
async def joinchannel(self, message):
if message.author.voice.voice_channel is... |
from Adafruit_IO import MQTTClient
import serial
import requests
ard = serial.Serial("COM7",9600)
ADAFRUIT_IO_KEY = 'aio_ckBE74gyEs9OeA3MIjmMzVFLJhE1'
ADAFRUIT_IO_USERNAME = 'Bipul07'
def connected(client):
print ('Connected. Listening changes...')
client.subscribe('bulb')
de... |
#!/usr/bin/env python3
import cv2
class Shape:
UNIDENTIFIED = "unidentified"
TRIANGLE = "triangle"
SQUARE = "square"
RECTANGLE = "rectangle"
PENTAGON = "pentagon"
CIRCLE = "circle"
def __init__(self, contour):
self._shape = self.UNIDENTIFIED
m = cv2.moments(contour)
... |
from csdl import *
class IOPS(Attribute):
def __init__(self):
super().__init__()
self.setId("https://github.com/supermuesli/csdl", "misc/dataTransfer/IOPS.py")
self.extendsId = "NumericAttribute"
self.value = None
self.makeInt = True
self.minVal = 0
self.st... |
import lxml.html
import scraper as sc
import requests
class Scraping:
def __init__(self):
self.default_url = 'http://www.sgc.org.sg/members/members-directory/?no_cache=1&tx_cpsmvz_pi1[pointer]='
self.url = lambda number: self.default_url+str(number)
self.number = 1
self.data = []
... |
import os #不知何意
def find_file(name,path = os.path.abspath('.')): #如果改成path = '.',打印相对路径
for f in os.listdir(path):
fpath = os.path.join(path,f)
if os.path.isfile(fpath) and name in os.path.splitext(f)[0]:
print(path)
print(f)
elif os.path.isdir(fpath):
... |
from django.contrib.auth.models import AnonymousUser
from channels.db import database_sync_to_async
from django.db import close_old_connections
from rest_framework.authtoken.models import Token
from channels.middleware import BaseMiddleware
from channels.auth import AuthMiddlewareStack
from rest_framework.authenticati... |
from django.contrib import admin
from api import models
admin.site.register (models.Alat)
admin.site.register (models.Data)
admin.site.register (models.MethaneProduction)
|
from .views import CreateUser
from django.urls import path
urlpatterns = [
path(
'user',
CreateUser.as_view(),
name='user-list'
),
] |
from typing import Optional
import dash_core_components as dcc
import dash_html_components as html
import id
def settings_title(text: str):
return html.H4(className="settings_title", children=text)
def settings_label(text: str):
return html.P(className="settings_label", children=text)
def create_percent... |
from django.db import models
import datetime
from django.contrib.auth.models import User, auth
from django.db.models import Sum, Count
from django.utils.timezone import now
# Create your models here.
class department(models.Model):
name = models.CharField(max_length=75, unique=True)
related_profession_name =... |
__author__ = 'bensoer'
import select
class ListenerProcess:
__keepListening = True
__connections = {}
__firstMessageReceived = False
__firstMessage = b''
__rejectFirstMessageMatches = False
__replySent = False
def __init__(self, socket, decryptor):
'''
constructor. This se... |
#!/usr/bin/env python3
#
# Copyright 2013 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.
import fnmatch
import optparse
import os
import sys
from util import build_utils
from util import md5_check
def Jar(class_files, ... |
from django.db import models
from sqlalchemy import Column, Integer, String, ForeignKey, Float
from shop.shop_helper import Base, MysqlHelper
goods = [
{"name": "貂皮大衣", "price": 3000},
{"name": "Iphone手机", "price": 1200},
{"name": "洋河蓝之梦", "price": 1800},
{"name": "茅台", "price": 819},
{"name": "游艇"... |
# Generated by Django 2.0.3 on 2018-03-27 22:40
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('users', '0018_auto_20180327_2043'),
]
operations = [
migrations.RenameField(
model_name='userprofile',
old_nam... |
'''
Created on Feb 3, 2020
@author: Bishwajit.
'''
'''
Exception Handling
Errors
Syntax error
RunTime Error
Exception Handling Using Try Except and Finally
'''
# if a > 2 # Syntax Error
a, b = 20, 0
c = a / b # Runtime Exception
print(c)
|
from django import forms
from .models import Meme
from config.forms import CloudinaryField
class MemeUploadForm(forms.ModelForm):
image = CloudinaryField()
class Meta:
model = Meme
fields = ("image", "description", "category", "tags")
def __init__(self, *args, **kwargs):
self.req... |
from urllib import request
from urllib import parse
from bs4 import BeautifulSoup
from general import *
import base64
def getLink(s):
''' (string) -> string
Cuts necessary link from part of the html page.
'''
result = 'None'
if s[1]=='s':
begin = s.find('+B')+4
end = s.find(')... |
from collections import Mapping
def recursive_update(original, updates):
"""Utility function to update original dictionary recursively.
Lists are replaced, not updated. New values are added.
"""
if updates is None:
return
for key, value in updates.items():
if isinstance(value, Ma... |
from copy import deepcopy
from unittest import TestCase as tc
import re
from myfile import is_number
class SmallDimension:
"""描述某一类量纲的单位和阶数"""
def __init__(self,dim,unit):
self.dim=dim
self.order=unit
def __eq__(self, other):
"""判断阶数是否相同"""
if self.order==other.order:
... |
# Contributted some elements and functions by Polina Volnuhina
# CSC 480-01, Kurfess
# 10/14/2020
import numpy as np
from Metrics import *
from tqdm.notebook import tqdm
#from tqdm.notebook import tqdm
example_board = np.array([[' ', ' ', ' '],
[' ', ' ', ' '],
[' ',... |
import datetime
from airflow import DAG
from airflow.operators.empty import EmptyOperator
my_dag = DAG(
dag_id="example-dag-2-packed-as-dir",
start_date=datetime.datetime(2023, 1, 1),
schedule="@daily",
)
task1 = EmptyOperator(task_id="task-1", dag=my_dag)
task2 = EmptyOperator(task_id="task-2", dag=my_d... |
from cs50 import SQL
from datetime import datetime
db = SQL("sqlite:///finance.db")
# user_id = db.execute("SELECT id FROM users WHERE username = 123")
# print(user_id[0]["id"])
# rows = db.execute("SELECT username FROM users")
# for row in rows:
# if "123" in row["username"]:
# print("Found")
# pri... |
#!/usr/bin/env python
#
# Project:
# glideinWMS
#
# File Version:
# $Id: stopFrontend.py,v 1.10 2011/02/10 21:35:31 parag Exp $
#
# Description:
# Stop a running glideinFrontend
#
# Arguments:
# $1 = work_dir
#
# Author:
# Igor Sfiligoi
#
import signal,sys,os,os.path,fcntl,string,time
sys.path.append(os.pa... |
#!/usr/bin/env python3
class CharacterClass():
def __init__(self, name, hitDice, skillPoints, classSkill, baseAttackBonus, fortitude, reflex, will, spellsPerDay, spellsKnown, specialAbilities, ):
self.name = name
self.hitDice = hitDice
self.skillPoints = skillPoints
self.classSkill = classSkill
self.baseAtt... |
# # # Flipping Image # # #
# Given a binary matrix A, we want to flip the image horizontally, then
# invert it, and return the resulting image.
# To flip an image horizontally means that each row of the image is reversed.
# For example, flipping [1, 1, 0] horizontally results in [0, 1, 1].
# To invert an image m... |
from pyfrc.physics import drivetrains
from config import *
import time
from pprint import pprint
class PhysicsEngine(object):
'''
Simulates a 4-wheel mecanum robot using Tank Drive joystick control
'''
def __init__(self, physics_controller):
'''
:param physics_controller: `pyfrc.physics.core... |
from django.db import models
# import os
# from django.conf import settings
class FlightsData(models.Model):
# departure_city = models.ForeignKey(DepartureCity, on_delete=models.CASCADE)
# arrival_city = models.ForeignKey(ArrivalCity, on_delete=models.CASCADE)
departure_city = models.CharField(max_length... |
"""
<Program Name>
rsa_keys.py
<Author>
Vladimir Diaz <vladimir.v.diaz@gmail.com>
<Started>
June 3, 2015.
<Copyright>
See LICENSE for licensing information.
<Purpose>
The goal of this module is to support public-key and general-purpose
cryptography through the pyca/cryptography (available as 'cryptograp... |
# (C) British Crown Copyright 2011 - 2016, Met Office
#
# This file is part of cartopy.
#
# cartopy is free software: you can redistribute it and/or modify it under
# the terms of the GNU Lesser General Public License as published by the
# Free Software Foundation, either version 3 of the License, or
# (at your option)... |
from hashlib import md5
from operator import attrgetter
try:
import simplejson as json
except ImportError:
import json
from pyehr.ehr.services.dbmanager.drivers.factory import DriversFactory
from pyehr.utils import get_logger
from pyehr.ehr.services.dbmanager.errors import OptimisticLockError,\
RedundantU... |
#use sieve of erastone
table = [True for _ in range(2000000)]
table[0] = False # for this question we do no count one as prime
for i in range(1, len(table)):
if table[i]:
step = (i + 1)
num = step + step
while num <= len(table):
table[num - 1] = False
num += step
an... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Aug 1 17:25:57 2019
@author: ziwei
"""
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Jul 27 21:13:41 2019
Difference from <proposal4July2019_v5_10sTwiceLDA_50p.py>:
#1. level up the number of topics from 50 to 100. ... |
from matplotlib import pyplot, cm
from matplotlib.colors import Normalize
ax = pyplot.figure()
norm = Normalize()
magnitude = numpy.sqrt(u[::2]**2 + v[::2]**2)
puyplot.quiver(u[::2],v[::2],norm(magnitude),scale=60,cmap=pyplot.cm.jet)
ax.savefig('frame'+str(i).zfill(5)+'.png',dpi=300)
ax.clear()
|
from wk2_objects import yourBank
class badBank(yourBank):
'''this class inherits the attributes and methods from yourBank class but adds some more functions '''
def deposit_plus_vat(self, amt): #function adds a user defined balance (plus 20% vat)
self.balance=self.balance+amt*1.2
'''
#STEVES CODE
#... |
# -*- coding: utf-8 -*-
from ecore.http import request
from ecore import api, fields, models, SUPERUSER_ID
import md5
class Lead(models.Model):
_inherit = 'crm.lead'
@api.one
def _count_pageviews(self):
self.pageviews_count = len(self.score_pageview_ids)
@api.depends('score_ids', 'score_ids.... |
# Generated by Django 1.9.6 on 2016-08-30 21:47
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('coderdojochi', '0005_auto_20160817_2313'),
]
operations = [
migrations.AddField(
model_name='session',
name='gender... |
from prefixcommons.curie_util import expand_uri, contract_uri, NoPrefix
bp_id = "GO:0008150"
bp_iri = "http://purl.obolibrary.org/obo/GO_0008150"
def test_prefixes():
assert contract_uri(bp_iri) == [bp_id]
assert expand_uri(bp_id) == bp_iri
assert contract_uri("FAKE", strict=False) == []
try:
... |
import os
import pickle
import sys
import ipdb
import argparse
from tqdm import tqdm
from os.path import expanduser
# kge_dir_path = expanduser('~')+'/KnowledgeGraphEmbedding/'
# kbe_dir_path = expanduser('~')+'/kg-bert/'
olp_dir_path = 'olpbench'
parser = argparse.ArgumentParser()
parser.add_argument('-... |
from __future__ import annotations
from prettyqt import widgets
class SingleLineTextEdit(widgets.PlainTextEdit):
def __init__(self, *args, object_name: str = "singleline_textedit", **kwargs):
super().__init__(*args, object_name=object_name, **kwargs)
self.textChanged.connect(self._on_text_changed... |
import socket
def mysend(sock, msg):
totalsent = 0
while totalsent < len(msg):
sent = sock.send(msg[totalsent:])
if sent == 0:
raise RuntimeError('broken')
totalsent += sent
def myreceive(sock, msglen):
msg =''
while len(msg) < msglen:
chunck = sock.recv(m... |
place = 1
x = 1
while 0 < x <= 100:
x = int(input())
if x == 1:
continue
if x > 12:
continue
if x != 0:
if place + x <= 100:
place += x
if place == 9:
place = 34
elif place == 40:
place = 64
elif place == 67:
place = 86
if place == 54:
... |
"""Code for constructing data pipelines that involve tables inside
workbooks."""
from .recordset import RecordSet
from .version import __version__
from .workbook import InputTable, InputWorkbookModel
|
import requests
from source.models.rt_rating import RTRating
class OmdbService:
__API_URL = 'http://www.omdbapi.com/?'
def __init__(self, movie_id):
self.id = movie_id
def get_rt_rating(self):
payload = {'i': self.id, 'plot': 'short', 'r': 'json', 'tomatoes': 'true'}
response =... |
from django.conf.urls import url
from django.urls import path, re_path
from . import views
urlpatterns = [
path('category/', views.CategoryRootView.as_view(), name='catalog.root'),
path('category/<slug>', views.CategoryView.as_view(), name='catalog.category'),
path('product/<slug>', views.ProductView.as_vi... |
'''Faça um programa que ajude um jogador da MEGA SENA a criar palpites. O programa vai perguntar quantos jogos serão
gerados e vai sortear 6 números entre 1 e 60 para cada jogo, cadastrando tudo em uma lista composta.'''
from random import randint
from time import sleep
print('\033[1;33m-=\033[m' * 20)
lista = list()
j... |
def fizz_buzz(n1 = 1, n2 = 100):
remainder = 0
num_list = []
num_list.extend(range(n1, n2+1))
#print(num_list)
for num in num_list:
if num % 3 == 0 and num % 5 == 0:
print("FizzBuzz")
elif num % 3 == 0:
print("Fizz")
elif num % 5 == 0:
prin... |
from django.contrib import admin
from . import models
# MARK : Action
def make_Enable(modeladmin, request, queryset):
queryset.update(isEnable=True)
make_Enable.short_description = "Enable"
def make_Disable(modeladmin, request, queryset):
queryset.update(isEnable=False)
make_Disable.short_description = "Disa... |
from django.db import models
char_max = 200
class TestUserForForum(models.Model):
name = models.CharField(max_length=char_max)
created_at = models.DateTimeField(auto_now_add=True)
update_at = models.DateTimeField(auto_now=True)
class TestCourseForForum(models.Model):
name = models.CharField(max_lengt... |
from typing import *
class Solution:
""" 单调栈 """
# [2,1,5,6,2,3]
def largestRectangleArea(self, heights: List[int]) -> int:
heights = [0] + heights + [0]
stack = []
res = 0
for i in range(len(heights)):
while len(stack) > 0 and heights[i] < heights[stack[-1]]:
... |
# -*- coding: utf-8 -*- python3
"""
Created on Tue Mar 10 06:00:59 2020
@author: Antiochian
"""
import random
class Perfect_Player:
def __init__(self,name):
self.name = name
self.inf = 1024
self.max_table = {}
self.min_table = {}
def make_move(self,board):
if board... |
import datetime
class WeekTime:
def __new__(cls, hour=0, minute=0, second=0, microsecond=0):
"""
WeekTime(hour, minute, second)
"""
self = object.__new__(cls)
self._hour = hour
self._minute = minute
self._second = second
return self
@property
... |
#this file parse the data from hspice .out results
import re
import numpy as np
###################################
def parsehspicev1(wheretosimpath,filenameoutput,vds,Lparam):
filepath =wheretosimpath
filenameaux = filenameoutput+'.lis'
outputfiletoread = open(filepath+filenameaux, 'r')
#state machine
#00:... |
# # -*- coding: utf-8 -*-
from odoo import models, fields, api, _
from odoo.addons import decimal_precision as dp
class StockoutOrder(models.Model):
_name = 'stockout.order'
_inherit = ['mail.thread', 'mail.activity.mixin', 'portal.mixin']
_description = 'Stockout Order'
_order = 'id desc'
@api.depends('order_l... |
from .config_parser import (Application, Media, ApplicationDatabase, AdminUser, AcunetixApi)
application_config = Application()
media = Media()
database = ApplicationDatabase()
admin_user = AdminUser()
acunetix_api_config = AcunetixApi
|
import os
from pymongo import MongoClient
COLLECTION_NAME = 'tasks'
class MongoTask(object):
def __init__(self):
mongo_url = os.environ.get('MONGO_URL')
self.db = MongoClient(mongo_url).tasks
def find_all(self, selector):
return self.db.tasks.find(selector)
def find(self, selector):
return self.db.t... |
import sys
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--io_files", help="file(s) from which to draw input/output pairs", type=str, default=None)
parser.add_argument("--prefix", help="prefix for the file to save to", type=str, default=None)
args = parser.parse_args()
# Creating a set of... |
import numpy as np
import models
import matplotlib
import matplotlib.pyplot as plt
plt.style.use('ggplot')
from data import molarConv
import data
import sympy as sp
def plotterCran(minB,maxB,model,cRan,q,w,j):
for c in cRan:
bFhighRes = np.linspace(minB,maxB,num=100,endpoint=True)
fHR = np.zeros(100)
for i,x in... |
## @TODO Tidy up code
## @TODO Update crossmod.ml documentation
## @TODO determine API rate limit based on concurrent and single endpoint tests
## experiment with different numbers of worker processes
## @TODO Make sure key is private
## @TODO Integrate API with database
## Tie rate limit to key, di... |
from flask import Flask
app = Flask(__name__)
@app.route('/churn_rate', methods = ['GET'])
def samplefunction():
with open("churn_rate.html") as html_file:
return html_file.read()
if __name__ == '__main__':
port = 8000
app.run(host='0.0.0.0', port=port) |
# !/usr/bin/env python
# -*- coding: utf-8 -*-
# @Aquamarine GY 2017.10.30
'''
Structure of top_dict:{node_1:{node_2:[Tn],node_3:[Tn]}, node2:{node1:[Tn],},node_3:{Tn}}
'''
import networkx as nx
import matplotlib.pyplot as plt
import random
import numpy as np
a = np.array([[0, 1, 1], [1, 2, 2], [2, 3, 1], [2, 3, 3], ... |
# conding: utf-8
from __future__ import unicode_literals
from nocaptcha_recaptcha.fields import NoReCaptchaField
from django import forms
from django.shortcuts import get_object_or_404
from django.utils.translation import ugettext_lazy as _
from conversation.models import Comment
class BaseCommentForm(forms.ModelFo... |
## only even
def only_even(numbers):
onlyEven = []
for num in numbers:
if num % 2 == 0:
onlyEven.append(num)
print(onlyEven)
check_number= [2, 10, 5, 42, 3, 7, 22, 44, 55, 86, 96]
only_even(check_number)
#--------------------------
def only_even(numbers):
onlyEven = []
for... |
from common import TreeNode
class Solution:
def minDepth(self, root):
if not root:
return 0
f, floor = [root], 0
while f:
floor += 1
next = []
for node in f:
if not node.left and not node.right:
return floo... |
import logging
from smartgymapi.lib.math import normalize, triangle_number
log = logging.getLogger(__name__)
def get_ordered_list_similarity(target_list, comparison_list):
"""Returns similarity of 2 lists that are ordered by importance.
These 2 lists should contain values that are ordered by most
impo... |
#/Users/ammanuelisaac/Desktop/Gabfest/askreddit
import praw, random, time, sys
reddit = praw.Reddit(client_id='',
client_secret='',
user_agent='')
print(reddit.read_only)
#--------------------------------------------------------#
#selects a random subred... |
import socket
import argparse
port = 65000
def opendoor():
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 지정한 host와 prot를 통해 서버에 접속합니다.
client_socket.connect(("192.168.0.215", port))
sendData = "open"
client_socket.sendall(sendData.encode('utf-8'))
# 소켓을 닫는다.
client_so... |
from django.db import models
class Post(models.Model):
user = models.ForeignKey('auth.User', related_name='posts', on_delete=models.CASCADE)
title = models.CharField(max_length=200, blank=True, default='')
body = models.TextField(blank=False)
likes_counter = models.IntegerField(blank=True, default=0)
... |
from setuptools import setup
setup(
name="distutils_ext_pkg",
entry_points={
"distutils.commands":[
"distutils_ext_pkg = distutils_ext_pkg.main:distutils_ext_pkg"
]
}
)
|
from __future__ import print_function
from __future__ import division
import pandas as pd
import numpy as np
from sklearn.preprocessing import LabelEncoder
from keras.models import Sequential
from keras.layers.core import Dense, Dropout, Activation
from keras.optimizers import SGD
from keras.utils import np_utils
from... |
from django.core.cache import caches, DEFAULT_CACHE_ALIAS
from django.core.cache.utils import make_template_fragment_key
from jinja2.nodes import Keyword, Const, CallBlock
from jinja2.ext import Extension
from .api import get_last_invalidation
class CachalotExtension(Extension):
tags = {'cache'}
allowed_kwar... |
# Import Python library random
import random
Num = random.randint(1,100)
UserNum = int(input("Guess a number between 1 and 100 :"))
attempts = 0
# Define how many times user attempts guesses..
while attempts < 5:
attempts +=1
if UserNum < Num:
print ("Too low!")
UserNu... |
# 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 writing, software
# distributed under th... |
"""
Запросить у пользователя данные в форме анкеты ;
Полученные данные записать в файл .txt ;
Открыть файл, изменить данные.
ограничение на количество попыток и возврат в начало
"""
#NameList = [Name, SurName, Age, Sex, Country, City, Married, Child, Job]
def Name():
while True:
Name = str(input('И... |
import numpy as np
# Generates neighbors of the position (i,j) from a given matrix
def get4Neighbors(i,j,mat):
nbr = np.empty(4)
nbr[0] = mat[i-1][j]
nbr[1] = mat[i][j-1]
nbr[2] = mat[i][j+1]
nbr[3] = mat[i+1][j]
return nbr
# Generates a drain_possibility matrix where 1's denote water storing... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('package', '0006_remove_package_skill'),
]
operations = [
migrations.CreateModel(
name='LadderLogTemplate',
... |
import unittest
from lexex import *
scheme_grammar = {
ROOT: [
(IGNORE, '\\s+'),
('open-paren', '\\(', 's-expr')
],
's-expr': [
(IGNORE, '\\s+'),
('quote', '`'),
('number', '[0-9]*.?[0-9]+'),
('word', '[-!?+*/A-Za-z_][-!... |
#03/09
#mikaela
#programa sobre a media dos alunos
p1 = int(input('Digite a nota da p1\n'))
p2 = int(input('Digite a nota da p2\n'))
p3 = int(input('Digite a nota da p3\n'))
aulas = int(input('Digite o num de aulas\n'))
faltas = int(input('Digite o numero de faltas\n'))
media = (p1 +p2 +p3)/3
porc = (faltas *100)... |
from db_config import db_init as db
class Stock(db.Model):
__tablename__ = 'stock'
stockCode = db.Column(db.String, primary_key=True, nullable=False, autoincrement=True)
stockName = db.Column(db.String(255), nullable=False)
|
from django.urls import path, re_path
from . import views
urlpatterns=[
path('', views.home, name='home'),
path('create_user', views.create_user),
path('find_user', views.find),
path('json_users', views.json),
path('users_html', views.all_users),
] |
from app import db
from flask import current_app
from sqlalchemy.orm import relationship
class Rental(db.Model):
__tablename__ = "rentals"
id = db.Column(db.Integer, primary_key=True)
customer_id = db.Column(db.Integer, db.ForeignKey("customers.customer_id"))
video_id = db.Column(db.Integer, db.Fore... |
# Generated by Django 3.2.8 on 2021-11-11 12:22
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('Forum', '0008_post_whatsapp'),
]
operations = [
migrations.CreateModel(
name='Filters',
fields=[
('i... |
from __future__ import division, print_function, absolute_import
import tflearn
import tflearn.data_utils as du
# Data loading and preprocessing
import tflearn.datasets.mnist as mnist
X, Y, testX, testY = mnist.load_data(one_hot=True)
X = X.reshape([-1, 28, 28, 1])
testX = testX.reshape([-1, 28, 28, 1])
X, mean = du.... |
def str_eval(val):
import distutils.util
import ast
def strtobool(val):
return bool(distutils.util.strtobool(val))
operations = [ast.literal_eval, strtobool]
for operation in operations:
try:
return_string = operation(val)
break
except (ValueError, ... |
# coding: utf-8
from __future__ import unicode_literals
import pytest
TAGGER_TESTS = [
('あれならそこにあるよ',
(('代名詞,*,*,*', 'PRON'),
('助動詞,*,*,*', 'AUX'),
('代名詞,*,*,*', 'PRON'),
('助詞,格助詞,*,*', 'ADP'),
('動詞,非自立可能,*,*', 'VERB'),
('助詞,終助詞,*,*', 'PART'))),
('このファイルには小さなテストが入っているよ',
... |
#!/usr/bin/python
import sys
from graph import Graph
from kruskal_path import kruskalsSolver
from dynamic_programming import dynamicSolver, cluster_and_solve
DYNAMIC_THRESHOLD = 12
answers = []
# command line arguments: first number is start, second number is end (inclusive)
try:
start, end = int(sys.argv[1]), ... |
import os
import os.path as P
import sys
import time
import traceback
import subprocess
from PyQt4 import QtCore, QtGui
import ReplayUploader
import Config
W, H = 300, 400
class Uploader:
def __init__(self, app):
self.app = app
self.w = self.create_main_window()
self.dotastats_host = s... |
import torch
import torch.nn as nn
import numpy as np
import tqdm
import torchvision.transforms as transforms
import torchvision.datasets as dsets
from sklearn.metrics import confusion_matrix
from matplotlib import pyplot as plt
import random as rand
device = torch.device("cuda" if torch.cuda.is_available() else "cpu"... |
def football(players: str) -> bool:
consecutive = 0
prev = ''
for player in players:
if prev == player:
consecutive += 1
else:
consecutive = 1
prev = player
if consecutive >= 7:
return True
return False
if __name__ == '__main__':
print('YES' if football(input()) else 'NO') |
import numpy as np
import random
import math
import matplotlib.pyplot as plt
def f(x, y):
return 3 * x ** 2 + 2 * y ** 2
def grad_f(x, y):
return np.array([6 * x, 4 * y])
def h(x, y):
return 1 - (x + y)
def phi(x, y):
return math.log(- h(x, y))
def grad_phi(x, y):
return np.array([1 / (- h(x, y)), 1 / (- h(x,... |
import graphene
import library.schema
class Query(library.schema.Query, graphene.ObjectType):
"""
Projects main Query class, this will inherit multiple queries.
"""
pass
class Mutation(library.schema.Mutation, graphene.ObjectType):
"""
Projects main Mutation class, this will
inherit mult... |
import os
import glob
import math
import ROOT
from ROOT import *
import sys
from optparse import OptionParser
parser = OptionParser()
parser.add_option('--cut', metavar='F', type='string', action='store',
default="",
dest='cut',
help='')
parser.add_option('--cut2', metava... |
import liblo
import time
addresses = [liblo.Address("192.168.1.200","2222"),liblo.Address("192.168.1.201","2222"),liblo.Address("192.168.1.202","2222"),liblo.Address("192.168.1.203","2222"),liblo.Address("192.168.1.204","2222"),liblo.Address("192.168.1.205","2222"),liblo.Address("192.168.1.206","2222"),liblo.Address("... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.