text stringlengths 8 6.05M |
|---|
from collections import Counter, namedtuple
from heapq import heapify, heappush, heappop
class Node(namedtuple("Node", ['left', 'rigth'])):
def walk(self, code, acc):
self.left.walk(code, acc + "0")
self.rigth.walk(code, acc + "1")
class Leaf(namedtuple("Leaf", ["name"])):
def walk(self, cod... |
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
import os
from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker
from sqlalchemy.ext.declarative import declarative_base
from flask_uuid import FlaskUUID
from flask_httpauth import HTTPBasicAuth
app = Flask(__name... |
#!/usr/bin/python3
'''network module'''
import urllib.request
with urllib.request.urlopen('https://intranet.hbtn.io/status')as response:
html = response.read()
print("Body response:\n\t- type: {}\n\t- content: {}\n\t- utf8 content: {}"
.format(type(html), html, html.decode()))
|
import RPi.GPIO as GPIO
from time import sleep
GPIO.setmode(GPIO.BOARD) # Reference pins by numerical position
#GPIO.setmode(GPIO.BCM) # Reference pins by BCM label value
ledPins = [11,13,15]
for pin in ledPins:
GPIO.setup(pin, GPIO.OUT) #set pin as output
i = 1
try:
while True:
GPIO.output(11... |
# -*- coding: utf-8 -*-
import logging
logging.getLogger("requests").setLevel(logging.ERROR)
logging.getLogger("robobrowser").setLevel(logging.ERROR)
|
from source import tools
from source.constants import EN1_JSONPATH,ST_VIDEOPATH,SRC_SIZE
from source.states import main_menu,maps,end_stat
from source.component import player,enemys
import json
import pygame.sprite as sprite
'''
偏移 600
max map 7680
'''
def play_video():
tools.play_video(ST_VIDEOPATH, SRC_SIZE)
... |
from ..extenstions import celery
def config_to_celery_kwargs(config):
return {
k.replace('CELERY_', '').lower(): v
for k, v in dict(config).items()
if k.startswith('CELERY')
}
def create_celery(app):
"""
Configures celery instance from application, using it's config
:para... |
#!/usr/bin/env python
import os
import sys
class Drone(object):
def __init__(self):
print "Starting account creation and buildup"
self.step = 0
from misc import Misc
from core.base import base
base = base()
if Misc.confirm(prompt="Are you sure you want to create an ... |
"""Metafeatures build for the Gridworld environment."""
import typing as t
import warnings
import numpy as np
import scipy.stats
import test_envs.gridworld
def ft_goal_dist_euclid(env):
start = np.asarray(list(env.start), dtype=float)
goals = np.asarray(list(env.goals), dtype=float)
dists = np.linalg.no... |
def juros_compostos():
lista = list()
x = int(input("Digite o Capital Inicial a ser investido: "))
taxa_mensal = float(input("Digite a Taxa Mensal de Juros: "))
Montante_posterior = x
n = 1
while n <=12:
Montante_posterior = Montante_posterior + Montante_posterior*taxa_mensal
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Dec 4 14:49:27 2020
@author: nerohmot
"""
import struct
from . import command_ABC
class SET_RAIL_STATUS(command_ABC):
'''
Description: set the desired status (on/off) of all rails
Input: the desired status of the rails
|... |
from lxml import html
import requests
import sqlite3
from time import sleep
base_url = 'http://stackoverflow.com'
conn = sqlite3.connect('morpheus11.db')
conn2 = sqlite3.connect('morpheus11.db')
keywords = ['cbind', 'rbind', 'filter', 'gather', 'group_by', 'inner_join', 'mutate', 'select', 'separate', 'spread', 'sum... |
print('Calcula o peso ideal')
altura = float(input('Informe sua altura: '))
peso_ideal = (72.7 * altura) - 58
print('Seu peso ideal é {:.2f} kg'.format(peso_ideal))
|
distancia = float(input('Qual a distância em km: '))
velocidade = float(input('Qual a velocidade média em km/h: '))
tempo = distancia / velocidade
print(f'O tempo de viagem será de: {tempo:.1f} horas ')
|
import sys
import json
import struct
import logging
from config import DAEMON_VERSION, ACTIONS
class Messenger:
"""
Handles the sending and receiving of messages to and from the addon using stdio.
:param version str: the current major python version
"""
def __init__(self, version):
self.s... |
/Users/daniel/anaconda/lib/python3.6/random.py |
from django.db import models
from authtools.models import AbstractNamedUser
from localflavor.us.models import PhoneNumberField
class User(AbstractNamedUser):
phone = PhoneNumberField()
def username():
return self.email
class Meta:
db_table = 'auth_user'
permissions = (
... |
# -*- coding: utf-8 -*-
class Solution:
def getMaximumGenerated(self, n: int) -> int:
nums, result = [0] * (n + 1), 0
for i in range(1, n + 1):
if i == 1:
nums[i] = 1
elif i % 2 == 0:
nums[i] = nums[i // 2]
elif i % 2 == 1:
... |
"""
compile & install FlyCap2 for windows and linux.
Directory should appear something like:
PyCapture2
|-doc
| |-FlyCap2 documentation.chm
| +-FlyCap2 documentation.pdf
|
|-src
| |-python2
| | +-PyCapture2.c
| |
| |-python3
| | +-PyCapture2.c
|
|-examples
| |-python2
| | + <python 2 examples>
| +... |
from wtforms import Form
from wtforms import StringField, PasswordField, BooleanField, TextAreaField
from wtforms.fields.html5 import EmailField
from wtforms import validators
from .models import User
def user_validator(form, field):
if field.data=='adsi' or field.data=='Adsi':
raise validators.Validatio... |
from PIL import Image
import serial
import time #from time import sleep
import winsound
bluetooth= serial.Serial('COM7',115200,timeout=1)
picSize = 120*184
camBuffer=b''
dataNum = 0
offset = 100
image = offset
receiveTime = time.process_time_ns()
data_time = time.process_time_ns()
while image < offset+1... |
# Generated by Django 2.2.1 on 2019-05-24 23:31
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('yb_app', '0002_board_iscomplete'),
]
operations = [
migrations.AlterField(
model_name='board',
name='content',
... |
import random
import pygame
class MyFaceClass(pygame.sprite.Sprite):
def __init__(self, image_file, location, width, height):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.image.load(image_file)
self.rect = self.image.get_rect()
self.rect.left, self.rect.top = location
... |
# remove comments
import numpy as np
import os
# rotate a vector by an angle theta around unit vector u
# u = []
def rotate3D(theta, unitVec, vector):
ux = unitVec[0]
uy = unitVec[1]
uz = unitVec[2]
c = np.cos(theta)
s = np.sin(theta)
# make rotation matrix
# see https://en... |
import requests
from bs4 import BeautifulSoup
import pandas as pd
url = 'https://www.swiggy.com/hyderabad/south-indian-collection'
resp1 = requests.get(url)
print(resp1)
resp = resp1.content
soup = BeautifulSoup(resp, 'html.parser')
soups = soup.find_all('div', class_='_3FR5S')
names = []
items = []
... |
import mysql.connector
conn = mysql.connector.connect(host='127.0.0.1', database='Test', user='root', password='gena')
mycursor = conn.cursor()
mycursor.execute('SELECT * FROM Test.Users')
result = mycursor.fetchall()
for (Id,Name,Email) in result:
print (Id)
print (Name + '/' + Email)
print (Email)
conn.cl... |
import rospkg
import subprocess
import os
# get an instance of RosPack with the default search paths
rospack = rospkg.RosPack()
print('\033[93mYOU NEED TO HAVE A ROSCORE RUNNING!\033[0m')
# Get the file path to the default pcd file created by smb_slam
mapPath = rospack.get_path('smb_slam') + '/compslam_map.pcd'
# G... |
import paho.mqtt.client as MQTTClient
import time
import sys
import os
client = MQTTClient.Client()
HOST = 'gateway-pi.local'
PORT = 1883
HB_TOPIC = '/heart_beat'
def main():
client.DEBUG = True
try:
client.connect(HOST, PORT)
except Exception:
print("Error while connecting to mqtt broker... |
lines = []
with open("inputData.txt", "r") as infile:
for line in infile:
lines.append(line.replace('\n', '').replace('\r', ''))
realLetters = 0
codeLetters = 0
for line in lines:
codeLetters += len(line)
lineWithoutQuotes = line[1:-1]
decodedString = bytes(lineWithoutQuotes, "utf-8").decod... |
"""
geopandas.clip
==============
A module to clip vector data using GeoPandas.
"""
import warnings
import numpy as np
import pandas as pd
from shapely.geometry import Polygon, MultiPolygon
from geopandas import GeoDataFrame, GeoSeries
from geopandas.array import _check_crs, _crs_mismatch_warn
def _clip_points(g... |
__all__ = [] # No root imports
|
# -*- coding: utf-8 -*-
# @Author: Safer
# @Date: 2016-08-18 21:12:14
# @Last Modified by: Safer
# @Last Modified time: 2016-08-26 00:22:03
import sys
from PyQt5.QtWidgets import QApplication
from PyQt5.QtCore import QEventLoop, QUrl, QByteArray
from PyQt5.QtNetwork import QNetworkAccessManager, QNetworkRequest
... |
# В римской системе счисления для обозначения чисел используются следующие символы (справа записаны числа, которым они соответствуют в десятичной системе счисления):
# I = 1
# V = 5
# X = 10
# L = 50
# C = 100
# D = 500
# M = 1000
# Будем использовать вариант, в котором числа 4, 9, 40, 90, 400 и 900 записываются как ... |
import os
import typing as typ
from pathlib import Path
from chaban.core.exceptions import ImproperlyConfiguredError
from chaban.utils import MetaSingleton
from . import global_settings
class Settings(metaclass=MetaSingleton):
TELEGRAM_TOKEN: str
BASE_DIR: typ.Union[str, Path]
PACKAGES: typ.List[str]
... |
import json
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
from django.views.generic import View
from rest_framework import generics
from clasificador.models import ClassifierModel
from clasificador.serializers import ClassifierModelSerializer
from documentos.helpers import cr... |
"""
Biblioteca criada com todas as funções criadas em Programação 2
"""
"""
Um n-grama é uma sequência de caracteres de tamanho n, por exemplo:
"goiaba" --> 1-grama: g, o, i, a, b, a
2-grama: go, oi, ia, ab, ba
3-grama: goi, oia, iab, aba
...
Construa a função ngrama(<texto>, <tam>) que retorna uma lista ... |
#!/usr/bin/env python3
# Import the ZMQ module
import zmq
# Import the Thread and Lock objects from the threading module
from threading import Thread, Lock, Event
# Import the uuid4 function from the UUID module
from uuid import uuid4
# Import the system method from the OS module
from os import system, name
# Import t... |
#!/usr/bin/env python
"""
Automatically generate release notes based on DRTVWR tickets
"""
import os, sys
import urllib, urllib2
import yaml, time
from argparse import ArgumentParser
from llbase import llrest
from llbuildutils.codeticket_data import CodeTicketData, CodeTicketDataError
from llbuildutils.sljira im... |
#!/usr/bin/python
#--------------------------------------
#
# Raspberry Pi HAT 8 Channel ADC V 1.1 - MCP3208 - SPI
#
# Microchip MCP3208 chip
#
# Author : V. R. Iglesias
# Date : 04/06/2017
#
# http://www.nationelectronics.com/
#
#
# Type the following to run the script:
#
# sudo python speedtest.py
#
#-----------... |
# Copyright (c) 2021 kamyu. All rights reserved.
#
# Google Code Jam 2021 Round 1B - Problem C. Digit Blocks
# https://codingcompetitions.withgoogle.com/codejam/round/0000000000435baf/00000000007ae37b
#
# Time: precompute: O(N^3 * B * D)
# runtime: O(N * B)
# Space: O(N^3 * B * D)
#
# Usage: python interacti... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Oct 19 10:03:15 2017
@author: dgratz
"""
import PyLongQt as pylqt
settings = pylqt.Misc.SettingsIO.getInstance()
proto = pylqt.Protocols.GridProtocol()
settings.readSettings(proto,'D:/synchrony-data/ela7x7NoConn.xml')
lastProto = settings.lastProto.cl... |
"""
single thread, single connection
"""
import mysql.connector
user_db = mysql.connector.connect(
host="localhost",
user="root",
passwd="123456",
database="users"
)
user_cursor = user_db.cursor()
def read_user_from_db():
"""
read user info from db
"""
user_cursor.e... |
#!/usr/bin/python
# -*- coding: UTF-8 -*-
"""
题目:利用递归函数调用方式,将所输入的5个字符,以相反顺序打印出来。
"""
def output(ss, ll):
if ll == 0:
return
print ss[ll - 1]
output(ss, ll - 1)
s = raw_input('Input a string:')
ls = len(s)
print ls, s
output(s, ls)
|
# JTSK-350112
# test_rational.py
# Taiyr Begeyev
# t.begeyev@jacobs-university.de
"""
a test program called that uses the class and
its methods to compute 1/2 + 1/8.
Print the result on the screen.
"""
from rational import Rational
# create two instances
r1 = Rational(1, 2)
r2 = Rational(1, 8)
# find t... |
import autodisc as ad
from autodisc.gui.gui import BaseFrame
try:
import tkinter as tk
except:
import Tkinter as tk
from tkinter import ttk
import importlib
import warnings
class ExplorationGUI(BaseFrame):
# TODO: ther seems to be a memory leak, altough a limit for the max_num_of_obs_in_memory is defined, ... |
# import the libs requises
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
import logging
from kalliope.core.NeuronModule import NeuronModule
# config
# logging
logging.basicConfig()
logger = logging.getLogger("kalliope")
# création de la class
class ... |
import time
exam_st_date = (11, 12, 2014)
print("Retrieving date for examination ...")
time.sleep(1)
print("The exmination will start from :",exam_st_date[0],"/",exam_st_date[1],"/",exam_st_date[2]) |
from braindecode.datasets.pylearn import DenseDesignMatrixWrapper
from braindecode.datahandling.batch_iteration import WindowsIterator
from braindecode.veganlasagne.monitors import WindowMisclassMonitor,\
MonitorManager, CntTrialMisclassMonitor
import numpy as np
import theano.tensor as T
def test_window_misclass_... |
# -*- coding=utf-8 -*-
from xlhelper import ExcelReader, fields
import pprint
field_descs = (
fields.Int(xl_name=u'加盟商ID', key='ops_org_id', required=True,
nullable=False),
fields.Str(xl_name=u'加盟商名称', key='org_name', required=True,
nullable=False),
fields.Float(xl_name=u'金额',... |
def fib(n):
if n == 0:
return 1
if n == 1:
return 1
else:
return fib(n-1)+fib(n-2)
for i in range(31):
print "the %s th term of the fibonacci sequence is %s" %(i,fib(i))
|
class Solution(object):
def findDuplicate(self, nums):
"""
learned floyd cycle detection. had no idea this can solved like this.
"""
tortoise = hare = nums[0]
while True:
tortoise = nums[tortoise]
hare = nums[nums[hare]]
if hare == tortoise... |
# Copyright 2010 Alon Zakai ('kripken'). All rights reserved.
# This file is part of Syntensity/the Intensity Engine, an open source project. See COPYING.txt for licensing.
"""
Handles authentication, both of the server instance to the master server,
and of clients to this server.
"""
from intensity.logging import *... |
import socket
import datetime
from dateutil import parser
from timeit import default_timer as timer
HOST = '127.0.0.1'
PORT = 8080
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
request_time = timer()
server_time = parser.parse(s.recv(1024).decode())
response_time = timer()
actual_t... |
import numpy as np
def softmax(x):
"""Compute softmax values for x."""
return(np.exp(x)/np.sum(np.exp(x), axis = 0))
scores = [3.0, 1.0,0.2]
print(softmax(scores))
# Plot softmax curves
import matplotlib.pyplot as plt
x = np.arange(-2.0, 6.0, 0.1)
scores = np.vstack([x, np.ones_like(x), 0.2 * np.ones_like(x)])
... |
# This file is part of beets.
# Copyright 2016, Adrian Sampson.
#
# 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, ... |
t = int(input())
for _ in range(t):
n = int(input())
s = 1
# div by 2 by skipping 2
for i in range(3, 2*n+1):
s = (s * i) % 1000000007
print(s)
|
#!/usr/bin/python
from bitstring import BitArray, BitStream
import hashlib
import Image
import sys
from util import getKey, getImageData
def getText(file):
text = open(file, "rb").read()
return text
def loadImage(input, output, text, key):
img = Image.open(input)
# TODO - assert RGB/RGBA
print img.mode
... |
import h5py
import numpy as np
def save_dict(elements, outputfile):
"""
Save the ADAS data to an HDF5 file.
"""
with h5py.File(outputfile, 'w') as f:
_save_internal(elements, f)
def _save_internal(dct, f, path=''):
"""
Internal function for saving data to HDF5.
"""
for k in ... |
# audio manipulation functions
from audiocore import RawSample
from audiopwmio import PWMAudioOut as AudioOut
class EAudio:
def __init__(self):
import array
self.audio = AudioOut(board.SPEAKER)
self.SAMPLE_RATE = 8000
self.sampleWave = array.array("H", [0] * self.SAMPLE_RATE)
... |
import numpy as np
import h5py
import os
import pickle
Targs = ['N0C0_CN', 'N0C1_CN', 'N0C2_CN', 'N1C0_CN', 'N1C1_CN', 'N1C2_CN',\
'N2C0_CN','N2C1_CN','N2C2_CN']
#Targs = ['Ca']
print('Targs[0]: ', Targs[0])
input_lm_files = ['_prerun_result.lm','_stimrun_result.lm']
input_lm_folder = 'lms'
input_... |
# Name: David Adams
# CMS cluster login name: dmadams
'''
final_players.py
This module contains code for various bots that play Connect4 at varying
degrees of sophistication.
'''
import random
from Connect4Simulator import *
class RandomPlayer:
'''
This player makes one of the possible moves on the game b... |
"""
helloworld.py
Author: xXxXxNimbleNavigatorxXxXx
Credit: kezarburgar
Assignment:Hello, world
Write and submit a Python program that prints the following:
Hello, world!
"""
print ("Hello, world!")
|
from _typeshed import Incomplete
from collections.abc import Generator
def bfs_beam_edges(
G, source, value, width: Incomplete | None = None
) -> Generator[Incomplete, Incomplete, Incomplete]: ...
|
#!/usr/bin/python
import struct
def p(x):
return struct.pack('<L',x)
PAYLOAD="jhh\x2f\x2f\x2fsh\x2fbin\x89\xe31\xc9j\x0bX\x99\xcd\x80"
BUFFER_ADDRESS=0xbffff730
BUFFER_ADDRESS_ALIGNED=0xbffff000
payload = ""
payload += PAYLOAD
while len(payload) < 32 + 4*3: # name size + arguments
payloa... |
# -*- coding: utf-8 -*-
"""
Created on Sun Mar 7 00:08:24 2021
@author: User
"""
import pandas as pd
data=pd.read_json('contacts.json')
data['email_len']=data['Email'].apply(lambda x:len(x))
data['phone_len']=data['Phone'].apply(lambda x:len(x))
data['order_len']=data['OrderId'].apply(lambda x:len(x))
email=data[data... |
"""
Definition of models.
"""
from django.db import models
class Place(models.Model):
name = models.CharField(max_length=200, null=True, blank=True)
position = models.CharField(max_length=200, null=True, blank=True)
def __str__(self):
return self.name + " " + self.position |
import logging
from typing import IO, Any, Dict
from urllib.parse import urlparse
_s3_client = None
log = logging.getLogger(__name__)
def get_s3_client() -> Any:
global _s3_client
if not _s3_client:
import boto3
_s3_client = boto3.client("s3")
return _s3_client
def s3_write(
url: s... |
#!/usr/bin/env python
import json
import logging
from marquee.formatter import MarqueeFormatter, MarqueeEventFormatter
from marquee.handler import CloudWatchEventsHandler
log = logging.getLogger(__name__)
log.setLevel(logging.DEBUG)
handler = CloudWatchEventsHandler(detail_type='new_type')
log.addHandler(handler)
f... |
"""pie
answers:
3
2
1
[3,1,4,1,5,9]
[1]
True
False
False
[3,1,4,1,5,9,2,6,5,3]
[4,1,5,9,1]
True
'ten',1,4,1,5,9,1]"""
numbers = [3, 1, 4, 1, 5, 9, 2]
print(numbers[0])
print(numbers[-1])
print(numbers[3])
print(numbers[:-1])
print(numbers[3:4])
print(5 in numbers)
print(7 in numbers)
print("3" in numbers)
print(number... |
import array
class ArrayList:
def __init__(self, capacity):
self.capacity = capacity
self.length = 0
self.array = array.array('l', [0]*capacity)
def is_empty(self):
return self.length == 0
def get_capacity(self):
self.capacity *= 2
new_arr = array.a... |
import urllib.request
import time
def get_price():
page= urllib.request.urlopen("https://www.taobao.com")
text=page.read().decode("utf8")
where=text.find('Fact%2F')
start=where+7
end=where+9
return(float(text[start:end]))
price=get_price()
ans=input("do you want the answer instan... |
'''
Created on Jun 24, 2015
@author: rebaca
'''
from robot.api import logger
import pexpect
import re
import os
import subprocess
def create_dirs_under_mount(password, mount_path, start, end):
# Remove existing folders
rmdir_out = subprocess.Popen('rm -rf ' + mount_path + '/{' + start + '..' \
... |
def function(reverse_list):
i=0
reverse_list.reverse()
print((reverse_list))
reverse_list = [6, 8, 4, 3, 9, 56, 0, 34, 7, 15]
function(reverse_list) |
#from __future__ import print_function
import httplib2
import os
from apiclient import discovery
from oauth2client import client
from oauth2client import tools
from oauth2client.file import Storage
SCOPES = 'https://www.googleapis.com/auth/drive'
CLIENT_SECRET_FILE = 'api/client_secret.json'
APPLICATION_NAME = 'MUMT-... |
from django.contrib import admin
from django.db import models
from .models import Topic, Course, Student, Order
class CourseAdmin(admin.ModelAdmin):
# list to display the fields of Course model
list_display = ['name', 'topic', 'price', 'hours', 'for_everyone']
actions = ['add_50_to_hours']
# action f... |
# while True:
# name= input("Nhap vao ten: ")
# if name.isalpha() == True:
# break
# while True:
# name= input("nhap ten: ")
# if name.isalpha() == False:
# break
# while True:
# name= input("nhap ten: ")
# if name.isalpha() == False:
# break
# ask = input("enter you... |
import pygame
import random
import json
from classes.classes import *
RES = (700, 600)
PASS_HEIGHT = 180
WALL_SPEED = 5
WALL_WIDTH = 60
WALL_HEIGHT = 60
FPS = 60
# non-main functions --- #
def generate_new_blocks(color:list, x_offset: int = 0, block_count: int=3) -> list:
blocks = []
total_height = 0
gap... |
from pox.core import core
from pox.lib.util import dpid_to_str
import pox.openflow.libopenflow_01 as of
import pox.lib.packet as pkt
from extensions.flow import Flow
from pox.lib.packet.ipv4 import ipv4
from pox.lib.packet.udp import udp
from pox.lib.packet.tcp import tcp
log = core.getLogger()
class SwitchController... |
#Copyright: (c) 2019, kristin barkardottir
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
# simple bool to verify base64 string
#!/usr/bin/python
from ansible.module_utils.basic import *
import base64
import binascii
def base_64_string_verify(data):
b64 = data['base64st... |
from __future__ import absolute_import
import mxnet as mx
import mxnet.symbol as sym
import json
from analysis.layers import *
import re
import ctypes
from mxnet.ndarray import NDArray
import mxnet.ndarray as nd
from mxnet.base import NDArrayHandle, py_str
blob_dict = []
tracked_layers = []
def tmpnet():
x = sy... |
# sum = 0
# for x in range(0, 101):
# sum += x
# print(sum)
sum = 0
n = 99
while n > 0:
sum += n
n = n -2
print(sum) |
import numpy as np
def entropy(x):
return np.sum(-x * np.log(np.clip(x, 1e-8, 1)), axis=-1)
def mean_entropy(sampled_probabilities):
return entropy(np.mean(sampled_probabilities, axis=1))
def bald(sampled_probabilities):
predictive_entropy = entropy(np.mean(sampled_probabilities, axis=1))
expected... |
from flask import Blueprint
from google.oauth2 import service_account
from google.auth.transport.requests import AuthorizedSession
from google.cloud import datastore
from google.cloud import bigquery
from google.cloud import storage
import datetime
import time
import dataflow_pipeline.massive as pipeline
import cloud_s... |
# The sum of the squares of the first ten natural numbers is,
#
# 12 + 22 + ... + 102 = 385
# The square of the sum of the first ten natural numbers is,
#
# (1 + 2 + ... + 10)2 = 552 = 3025
# Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is 3025 − 385 =... |
import tensorflow as tf
import tensorflow.contrib.slim as slim
from utct.common.functor import Functor
class MnistModel(Functor):
def __init__(self):
super(MnistModel, self).__init__()
#self.param_bounds = {
# #'mdl_conv1a_nf': (6, 128),
# #'mdl_conv1b_nf': (6, 128),
... |
import unittest
from katas.kyu_7.string_chunks import string_chunk
class StringChunkTestCase(unittest.TestCase):
def test_equal_1(self):
self.assertEqual(string_chunk('codewars', 2),
['co', 'de', 'wa', 'rs'])
def test_equal_2(self):
self.assertEqual(string_chunk('thi... |
import datetime
import json
import logging
import os
import pytz
import requests
from collectors.exceptions import DuplicateFound
from .generic import OAuthCollector
logger = logging.getLogger(__name__)
session = requests.session()
def get_timestamp_from_epoch(epoch_string):
epoch_time = int(epoch_string)
... |
# Copyright 2021 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 or agreed to in writing, ... |
from telnetlib import IAC, DO, WILL, SB, SE, TTYPE, ECHO, DONT, WONT, NAOFFD
import telnetlib
import socket
import time
import threading
import os
import matlab.engine
def clear_all():
"""Clears all the variables from the workspace of the spyder application."""
gl = globals().copy()
for var in... |
#!/usr/bin/env python
import os
import yaml
try:
from qutebrowser import qutebrowser, app
from qutebrowser.misc import ipc
except ImportError:
print("error: qutebrowser missing.")
exit(1)
def session_save():
"""Send config-source command to qutebrowsers ipc server."""
args = qutebrowser.get... |
class A:
def afun(self):
print(" I am A class Function")
class B:
def bfun(self):
print(" I am B class Function")
class C(A,B):
def cfun(self):
print(" I am C class Function")
#---------------------------------
c1 = C()
# by using c1 we can call C,A,B class Members
c1.afun()
c1.bfu... |
from theanify import Theanifiable, theanify
|
import os
import time
import shutil
import json
import hashlib
import datetime
import numpy as np
import torch
import torch.optim
import torch.utils.data
from model import add_video_db, add_report_db, Video, ReportList, DaycareCenter, Location, User
from flask_sqlalchemy import SQLAlchemy
from flask_ngrok import run_... |
# Copyright 2021 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import annotations
import textwrap
from typing import List, NewType
import pytest
from pants.backend.terraform import tool
from pants.backend.terraform.lint.tffmt import ... |
class NotMutable( AttributeError ):
pass
def not_mutable( *a, **kw ):
raise NotMutable()
|
from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
class NavigationManager():
def __init__(self, localDriverPath, chrome_options):
self.driver = webdriver.Chrome(executable_path=localDriverPath, chrome_options=chrome_options)
self.currentUrl =... |
#Main python script for the VEGAS analysis pipeline
import sys
import time
from plutils import *
inst_filename = sys.argv[1]
try:
f = open(inst_filename)
except OSError:
print("Instructions file ", inst_filename, " could not be opened.")
raise
else:
f.close()
print(inst_filename)
testmod.testmod()
#Test the d... |
# Exercício 5.26 - Livro
dividendo = int(input('Digite o dividendo: '))
divisor = int(input('Digite o divisor: '))
div = dividendo
cont = 0
while True:
div = div - divisor
cont = cont + 1
if div == 0:
resultado = cont
resto = 0
break
elif div < 0:
resultado = cont - 1
... |
age = 25
num = 0
while num < age:
if num == 0:
if num % 2 == 0:
print(num)
num+=1
|
#!/usr/bin/python3
import socket
host=''
port=5555
s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
try:
s.bind((host,port))
except Exception as e:
print(str(e))
s.listen()
conn,addr=s.accept()
print("connected to:", addr[0],addr[1]) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.