text string | size int64 | token_count int64 |
|---|---|---|
# coding=utf-8
from django.conf.urls import url
from reptile.api_views.reptile_collection_record import (
ReptileCollectionList,
ReptileCollectionDetail,
)
from django.contrib.auth.decorators import login_required
from reptile.views.csv_upload import CsvUploadView
api_urls = [
url(r'^api/reptile-collecti... | 637 | 223 |
#!/usr/bin/env python
# coding=UTF-8
"""
@Author: Tao Hang
@LastEditors: Tao Hang
@Description:
@Date: 2019-03-29 10:41:16
@LastEditTime: 2019-04-15 09:25:43
"""
import numpy as np
import torch
from torch.autograd import Variable
from EvalBox.Attack.AdvAttack.attack import Attack
class BLB(Attack):
def __init__... | 5,359 | 1,702 |
a, b = map(int, input().split())
if b * 2 >= a:
print(0)
else:
print(a-b*2)
| 85 | 43 |
## Script (Python) "pwreset_constructURL.py"
##bind container=container
##bind context=context
##bind namespace=
##bind script=script
##bind subpath=traverse_subpath
##title=Create the URL where passwords are reset
##parameters=randomstring
host = container.absolute_url().replace('http:','https:')
return "%s/passwordre... | 351 | 102 |
#!/usr/bin/python
# wsd project main script
# hardware: ws2801 led strips + raspberry pi + internet adapter
# software pulls twits from an 'admin' (twits and retwits) and
# displays the last result through the led strip
# Written by Pratipo.org, hightly based on Adafruit's IoT Pinter. MIT license.
# MUST BE RUN AS... | 1,144 | 466 |
# Cem GURESCI 200201027
from __future__ import print_function
from collections import deque # you will use it for breadth-first search
class State:
def __init__(self, name):
self.name = name
self.actions = []
self.is_goal = False
def add_action(self, action):
self... | 7,252 | 2,229 |
__author__ = 'talluri'
#!/usr/bin/env python
# by carlcarl
import getopt
import sys
import hmac
import hashlib
import base64
import urllib
def formattedCmd(api, cmd):
s = 'apiKey=' + api + '&' + cmd
return s
def encypt(string, key):
h = hmac.new(key, string, hashlib.sha1)
return base64.b64encode(... | 1,170 | 423 |
# Generated by Django 4.0 on 2021-12-31 22:28
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('observe', '0011_observinglocation_time_zone'),
]
operations = [
migrations.AlterField(
model_name='observinglocation',
... | 511 | 174 |
import os
import pytest
import sys
import datetime
import time
import ctypes.util
from typing import Union
# scopes (broader to narrower): session, module, class, function (default)
@pytest.fixture(scope="session")
def chrome_driver():
"""
Prepare Chrome driver, visible or headless
:return:
"""
... | 1,304 | 404 |
import sys
import torch
import datasets
import json
import logging
import os
from pathlib import Path
from transformers import AutoTokenizer, HfArgumentParser, set_seed
from transformers.trainer_utils import EvaluationStrategy
from hyperformer.third_party.models import T5Config, T5ForConditionalGeneration
from hyperf... | 15,495 | 4,557 |
# -*- coding: utf-8 -*-
"""
downloader services module.
"""
from pyrin.application.services import get_component
from charma.downloader import DownloaderPackage
def download(url, target, **options):
"""
downloads the file from given url and saves it to target path.
it returns a tuple of two items. firs... | 1,422 | 374 |
#!/Users/albalbaloo/Desktop/woid-master/venv/bin/python
from django.core import management
if __name__ == "__main__":
management.execute_from_command_line()
| 162 | 54 |
import cv2
import numpy as np
from __utils__.general import show_image
img = cv2.imread('../../asserts/images/zigzac.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
sift = cv2.xfeatures2d.SIFT_create()
kp = sift.detect(gray, None)
cv2.drawKeypoints(gray, kp, img)
show_image(img)
| 286 | 120 |
import numpy as np
np.ones((3,4))
# film demo
list = [(3,104),(2,100),(1,81),(101,10),(99,5),(98,2),(18,90)]
print(list)
for key , value in list:
a = (key-18)**2+(value-90)**2
print(np.sqrt(a)) | 203 | 107 |
from rest_framework import generics
from rest_framework import mixins
from . import models
from . import serializers
# Create your views here.
# class JobCandidateView(
# mixins.CreateModelMixin,
# mixins.RetrieveModelMixin,
# mixins.ListModelMixin,
# mixins.UpdateModelMixin,
# mixins.DestroyModel... | 858 | 294 |
from django.dispatch import receiver
from django.core.mail import send_mail
from django.contrib.auth import get_user_model
from django.conf import settings
from .models import Profile
from django.db.models.signals import post_save
@receiver(post_save, sender=get_user_model())
def create_profile(sender, instance, crea... | 841 | 231 |
# Generated by Django 2.0.6 on 2018-06-14 06:53
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('home', '0009_auto_201806... | 931 | 305 |
fobj = open("mini_project_data_set_with_time_only.txt")
f = open("mini_project_dynamic_graph_data_set_without_time.txt", "w")
for line in fobj:
a,b,c = map(int,line.rstrip().split())
e = [b,c]
d1 = e[0]
d2 = e[1]
final = str(d1) + ' ' + str(d2) + '\n'
f.write(final)
#print e
fobj... | 330 | 156 |
import os
import sys
import pygit2
import util
def clone_github_repository(username, repository, clone_dir_path=None):
if clone_dir_path == None:
clone_dir_path = '%s/%s' % (util.get_gesso_dir(), 'components')
remote_repository_uri = 'https://github.com/%s/%s' % (username, repository)
local_repository_clone_pa... | 1,313 | 460 |
"""
Get CAP data and MRIQ of the current sample.
Only need to be ran once for tidying things up, but keep it here for book keeping.
"""
import json
import os
import numpy as np
import pandas as pd
from scipy import io
from nkicap import get_project_path, read_tsv
SOURCE_MAT = "sourcedata/CAP_results_organized_toHaoT... | 5,723 | 2,226 |
from ...exceptions import BadRequestException
from ...utils import get_temp_dir, make_validation_report
from biosimulators_utils.combine.data_model import CombineArchiveContentFormat
from biosimulators_utils.combine.io import CombineArchiveReader
from biosimulators_utils.combine.validation import validate
from biosimul... | 4,770 | 1,329 |
from django.db import models
from dc17.models.attendee import Attendee
class Meal(models.Model):
date = models.DateField(db_index=True)
meal = models.CharField(max_length=16)
@property
def form_name(self):
return '{}_{}'.format(self.meal, self.date.isoformat())
def __str__(self):
... | 748 | 262 |
"""
Blueprint of error handler module
It's possible to defie template_folder='templates' as argument to the Blueprint() constructor.
Default is keeping html files in template subfolder.
"""
from flask import Blueprint
bp = Blueprint('errors', __name__, template_folder='templates')
from app.errors import handlers
| 316 | 80 |
# coding: utf-8
import matplotlib.pyplot as plt
"""
@brief: 计算n阶差商 f[x0, x1, x2 ... xn]
@param: xi 所有插值节点的横坐标集合 o
@param: fi 所有插值节点的纵坐标集合 / \
@return: 返回xi的i阶差商(i为xi长度减1) ... | 2,433 | 1,228 |
import lief
path_benign_exe = 'good.exe'
path_strings_exe = 'good.txt'
path_bad_exe = 'jigsaw_compress.exe'
path_angel_exe = 'angel.exe'
with open(path_bad_exe, 'rb') as f:
bytez = f.read()
# AGGIUNGI BINARIO
with open(path_benign_exe, 'rb') as f:
good_binary = f.read()
bytez += good_binary
#AGGIUNGI STRIN... | 687 | 285 |
import argparse
import json
import torch
import torchaudio
import models as module_arch
from utils.utils import get_instance
from inference import *
def main(config, ckpt, infile, outfile, T, amp, deterministic):
device = torch.device('cuda')
trainer_config = config['trainer']
ckpt_dict = torch.load(ckp... | 2,657 | 974 |
from __future__ import print_function
from future.standard_library import install_aliases
install_aliases()
from urllib.parse import urlparse, urlencode
from urllib.request import urlopen, Request
from urllib.error import HTTPError
import json
import random
import os
from flask import Flask
from flask import request... | 5,471 | 1,615 |
import requests
class HttpClient():
config = None
headers = {}
def __init__(self, config):
self.config = config
self.headers = {
"X-Kalasearch-Id": self.config.appId,
"X-Kalasearch-Key": self.config.apiKey,
"Content-Type": "application/json"
}
... | 999 | 299 |
"""Tests for Micropel Connector."""
| 36 | 13 |
import asyncio
from src.moodle_session import MoodleSession
import src.session_manager as session_manager
import src.data_manager as data_manager
import aioconsole
async def terminal_loop():
print_command_list(None)
while True:
command_args = (await aioconsole.ainput("> ")).split()
if len(comm... | 2,309 | 741 |
from cilantropy.cilantropy import app
if __name__ == '__main__':
app.run()
| 80 | 31 |
# For simplicity, these values are shared among both threads and comments.
MAX_THREADS = 1000
MAX_NAME = 50
MAX_DESCRIPTION = 3000
MAX_ADMINS = 2
# status
DEAD = 0
ALIVE = 1
STATUS = {
DEAD: 'dead',
ALIVE: 'alive',
}
| 228 | 101 |
# test pyb module on F405 MCUs
import os, pyb
if not "STM32F405" in os.uname().machine:
print("SKIP")
raise SystemExit
print(pyb.freq())
print(type(pyb.rng()))
| 171 | 76 |
#!/bin/usr/env python
"""Primary script for testing"""
from graphs.orderly import *
import sys
import argparse
def setupArgs():
"""Set up command line arguments"""
parser = argparse.ArgumentParser(description='Program for generating unlabeled graphs over n vertices')
parser.add_argument('--vertices', '-... | 676 | 197 |
#!/usr/bin/env python
"""
Script to build an sqlite database from a dbsnp or 1000 genomes vcf file.
The script ignores all sample information and only processes those INFO fields
that are described in the meta INFO section of the vcf file. Additionally
QUAL and FILTER fields are also ignored since these tend to be sup... | 7,544 | 2,238 |
import sys, getopt
import fff2_input_models as fim
def main(argv):
inargs1 = 'ht:c:o:i:n:s:l:'
snargs1 = inargs1[1:].split(':')
inargs2 = ['time','cmsdir','outdir','ifile',"nproc","minmod","maxmod"]
helpinfo = "create_model_files_wrapper.py is a command line utility which calls the class create_mod... | 2,829 | 983 |
from django.contrib import admin
from dates import models
class GroupKeyDateExceptionInline(admin.StackedInline):
model = models.GroupKeyDateException
extra = 0
autocomplete_fields = ('group',)
class UserKeyDateExceptionInline(admin.StackedInline):
model = models.UserKeyDateException
extra = 0
... | 689 | 209 |
#coding=utf-8
__author__ = 'archer'
from functools import wraps
from flask import request, redirect, current_app
def ssl_required(fn):
@wraps(fn)
def decorated_view(*args, **kwargs):
if current_app.config.get("SSL"):
if request.is_secure:
return fn(*args, **kwargs)
... | 470 | 144 |
from __future__ import division
from __future__ import print_function
import argparse
from datetime import datetime
import json
import os
import numpy as np
import tensorflow as tf
import scipy.io as sio
from wavenet_skeleton import WaveNetModel
SAMPLES = 16000
LOGDIR = './logdir'
WINDOW = 25 #1 second of past samp... | 7,652 | 2,281 |
#!/usr/bin/python
from fg_constants import *
import cross_validation as cv
import matplotlib.pyplot as plt
import numpy as np
from scipy.linalg import svd
def load_regressor(name, num):
lags = cv.REGRESSORS[name](num)
return lags[:, :(lags.shape[1]/3)]
def trunc_svd(x, d):
u, s, _ = svd(x, full_matric... | 711 | 309 |
# AUTOR: JHONAT HEBERSON AVELINO DE SOUZA
#
# SCRIPT: servidor com metodo GET (python 3)
#
# importacao das bibliotecas
import socket
# definicao do host e da porta do servidor
HOST = '' # ip do servidor (em branco)
PORT = 8081 # porta do servidor
# cria o socket com IPv4 (AF_INET) usando TCP (SOCK_STREAM)
listen_so... | 2,475 | 842 |
import logging
from math import pi
from typing import Tuple, List
import cv2
import numpy as np
from pathfinding.domain.angle import Angle
from vision.domain.iGoalFinder import IGoalFinder
from vision.domain.image import Image
from vision.domain.rectangle import Rectangle
from vision.domain.visionError import VisionE... | 4,870 | 1,586 |
#!/usr/bin/env python3
import os
import sys
sys.path.append(os.path.join(os.getcwd(), "MAgent/python"))
import magent
from magent.builtin.rule_model import RandomActor
MAP_SIZE = 64
if __name__ == "__main__":
env = magent.GridWorld("forest", map_size=MAP_SIZE)
env.set_render_dir("render")
# two groups ... | 1,980 | 782 |
def swap(vet, i, j):
aux = vet[i]
vet[i] = vet[j]
vet[j] = aux
def partition(vet, left, right):
i = left + 1
j = right
pivot = vet[left]
while i <= j:
if vet[i] <= pivot:
i += 1
else:
if vet[j] >= pivot:
j -= 1
else:
... | 809 | 321 |
import logging
import sys
from aiohttp import web
import aiohttp_jinja2
import jinja2
import config
from routes.api import routes_api
from routes.ui import routes_ui
def make_app():
app = web.Application()
aiohttp_jinja2.setup(app, loader=jinja2.FileSystemLoader('templates'))
handlers = [
loggi... | 635 | 218 |
import torch
import torch.nn as nn
from torch.nn.parameter import Parameter
import math
class GCN(nn.Module):
# 初始化层:输入feature,输出feature,权重,偏移
def __init__(self, in_features, out_features, bias=True):
super(GCN, self).__init__()
self.in_features = in_features
self.out_feat... | 2,124 | 1,148 |
from django import forms
from django.forms import widgets
from django.utils.safestring import mark_safe
from decimal import Decimal
from bootstrap_modal_forms.forms import BSModalForm
from .models import SmartLinks, Earnings, Payments, SupportManager, Balance
from profiles.models import User
TYPE_CHOICES = [
... | 3,887 | 1,274 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
" Train from the replay .pt files through pytorch tensor"
import os
USED_DEVICES = "7"
import os
os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID"
os.environ["CUDA_VISIBLE_DEVICES"] = USED_DEVICES
os.environ["CUDA_LAUNCH_BLOCKING"] = "1"
import sys
import time
import trace... | 5,316 | 1,882 |
from eventsourcing.infrastructure.event_sourced_repo import EventSourcedRepository
from quantdsl.domain.model.simulated_price_requirements import SimulatedPriceRequirements, SimulatedPriceRequirementsRepository
class SimulatedPriceRequirementsRepo(SimulatedPriceRequirementsRepository, EventSourcedRepository):
d... | 360 | 96 |
import os
import numpy as np
import pytest
import torch
from adjoint_test import check_adjoint_test_tight
use_cuda = 'USE_CUDA' in os.environ
adjoint_parametrizations = []
# Main functionality
adjoint_parametrizations.append(
pytest.param(
np.arange(4, 8), [4, 1], # P_x_ranks, P_x_shape
np.aran... | 21,544 | 7,885 |
"""Add confirmed status to transaction
Revision ID: ae8f4b63876a
Revises: 7c1927c937af
Create Date: 2019-05-31 18:08:19.462983
"""
from alembic import op
import sqlalchemy as sa
import pycroft
# revision identifiers, used by Alembic.
revision = 'ae8f4b63876a'
down_revision = '7c1927c937af'
branch_labels = None
depe... | 1,265 | 451 |
"""
class TempoFinder
"""
from time import time, perf_counter, sleep
import logging
import numpy
import sounddevice
from aubio import tempo, pitch, sink
WRITE_WAV = False
WAV_NAME = "out.wav"
class TempoFinder(object):
MAX_LISTEN_PER_RECORD_MS = 20. * 1000.
def __init__(self, win_size=512, samplerate=44100... | 4,592 | 1,518 |
"""Ceaser Cipher Implementation"""
def encrypt(text, k):
cipher = []
for character in text:
# convert character to ascii and add k
temp = ord(character) - 96 # Assuming message is in lowercases, assign 1 to 26
# encipher the character
temp = (temp + k) % 26
# conver... | 1,116 | 357 |
import os
import errno
import time
import docker
from grpc4bmi.bmi_grpc_client import BmiClient
from grpc4bmi.utils import stage_config_file
class LogsException(Exception):
pass
class DeadDockerContainerException(ChildProcessError):
"""
Exception for when a Docker container has died.
Args:
... | 5,294 | 1,391 |
#params aaaaa
import numpy as np
from copy import copy , deepcopy
from collections import Iterable, Collection
import pandas as pd
import random
DEBUG = False
class InvalidArguments(Exception) :
def __init__(self, err="invalid arguments") :
self.err = err
def __str__(self) :
return self.err
c... | 13,023 | 4,141 |
from scorechive._version import __version__
from setuptools import setup
with open("README.md", "r") as fh:
long_description = fh.read()
setup(
name="scorechive",
version=__version__,
author="Garon Fok",
author_email="fokgaron@gmail.com",
packages=["example_pkg"],
description="Scorechive i... | 652 | 212 |
# This file is Copyright 2019 Volatility Foundation and licensed under the Volatility Software License 1.0
# which is available at https://www.volatilityfoundation.org/license/vsl-v1.0
#
import collections
import collections.abc
import enum
import logging
from typing import Any, Dict, Iterable, Iterator, TypeVar, List... | 12,071 | 3,246 |
"""
Blog models
"""
from django.contrib.auth import get_user_model
from django.db import models
from django.utils.text import slugify
from markdown2 import markdown
class Tag(models.Model):
"""
Blog tag model
"""
name = models.CharField(max_length=256)
def __str__(self) -> str:
"""
... | 1,962 | 600 |
# Adapted from https://github.com/sorki/python-mnist/blob/master/mnist/loader.py
import os
import struct
from array import array
import numpy as np
from matplotlib import pyplot as plt
class MNIST(object):
def __init__(self, path=os.path.join('..', 'DataSets')):
self.path = path
self.test... | 2,578 | 825 |
# Copyright (c) 2018, MD2K Center of Excellence
# - Md Shiplu Hawlader <shiplu.cse.du@gmail.com; mhwlader@memphis.edu>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of sour... | 29,678 | 8,531 |
import argparse
import numpy as np
import configparser
from .dune_topo import DuneTopo
def main(color, k, n, f, r, t, w, erosion, d, *infiles):
c = configparser.ConfigParser()
for file in infiles:
with open(file) as src:
c.read_file(src)
config = c.defaults()
make_movie(col... | 2,477 | 926 |
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
# mean false error by Wang+16, IJCNN.
class MFE_Loss(nn.Module):
def __init__(self, orig_loss):
super().__init__()
self.set_orig_loss(self, orig_loss)
print("using MFE_Loss")
def set_orig_loss(self, o... | 3,854 | 1,235 |
#!/usr/bin/env python
# coding: utf-8
# toutes les chaines sont en unicode (même les docstrings)
from __future__ import unicode_literals
"""
tableau.py
Création de tableau simple pour Inkscape
Codé par Frank SAURET - http://www.electropol.fr -
License : Public Domain
"""
import inkex
__version__ = '2020.2'
#... | 4,155 | 1,839 |
import cv2
from os import listdir
import os
import dlib
import time
import pickle
detector = dlib.get_frontal_face_detector()
sp = dlib.shape_predictor('model_image/shape_predictor_68_face_landmarks.dat')
model = dlib.face_recognition_model_v1('model_image/dlib_face_recognition_resnet_model_v1.dat')
path = 'datasets/... | 2,196 | 785 |
import os
import cv2
import numpy as np
import random
from moviepy.editor import *
import mxnet as mx
from detect.detector import Detector
class video_generator:
def __init__(self,video_path,fps,output_path='./result.mp4'):
self.clip = VideoFileClip(video_path)
self.output_path = output_... | 3,614 | 1,432 |
#!/usr/bin/env python3
# Very simple tool to add A or AAAA records in a route53 hosted zone from the command line.
import boto3
import click
import os
import logging
import ipaddress
logger = logging.getLogger('route53_tool')
logger.setLevel(logging.ERROR)
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
format... | 3,135 | 1,081 |
import argparse
import os
def run_command(command: str):
ret = os.system(command)
if ret != 0:
raise RuntimeError(f"Command returned {ret}")
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument("url", type=str, help="tarball url")
parser.add_argument("dest", ty... | 860 | 280 |
def main():
print "iot-firmware-loader is a python tool that interfaces with CMSIS-DAP and ST-LINK ARM debuggers."
if __name__ == '__main__':
main()
| 163 | 57 |
from django.contrib import admin
from .models import PlaneEvent, SeatingPlan, Seat, PlaneTicket
admin.site.register(PlaneEvent)
admin.site.register(SeatingPlan)
admin.site.register(Seat)
admin.site.register(PlaneTicket)
| 222 | 74 |
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
# ******************************************************
# @author: Haifeng CHEN - optical.dlz@gmail.com
# @date (created): 2019-10-22 21:27
# @file: mpl.py
# @brief: Matplotlib utilities
# @internal:
# revision: 2
# last modifie... | 3,130 | 1,095 |
from .xy_connect import XY_Stage
| 33 | 12 |
import json
import os
import shutil
from pathlib import Path
from typing import Callable, Optional
import aqt
import aqt.utils
import yaml
from ..representation import deck_initializer
from ..utils.constants import DECK_FILE_NAME, DECK_FILE_EXTENSION, MEDIA_SUBDIRECTORY_NAME, IMPORT_CONFIG_NAME
from ..importer.import... | 4,526 | 1,279 |
import kivy
kivy.require('1.11.1')
import sqlite3
from kivy.config import Config
from kivy.app import App
from kivy.properties import ObjectProperty
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.lang import Builder
from kivy.uix.popup import Popup
from kivy.uix.floatlayout import FloatLayout
fro... | 3,501 | 1,217 |
# REST API call to Prism Central to list all available VM snapshots
# setup common variables
uri = 'localhost:9440'
cluster_uuid = '@@{platform.status.cluster_reference.uuid}@@'
vm_uuid = '@@{id}@@'
hostname = '@@{calm_application_name}@@'
remote_cluster = '@@{remote_protection_domain_cluster}@@'
# setup credentials
... | 2,230 | 687 |
#Script must have these three parts:
# prepare_data()
# make_experiment()
# collect_result()
import logging
import pathlib
import shutil
import subprocess
import sys
from saxs_experiment import Colors
from saxs_experiment import LogPipe
def prepare_data(all_files, tmpdir, mydirvariable):
pathlib.Path(f'{tmpdir}... | 2,885 | 1,129 |
# Copyright 2018 ETH Zurich
#
# 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, sof... | 6,138 | 2,201 |
import matplotlib.pyplot as plt
import numpy as np
import tensorflow as tf
datasets = tf.keras.datasets.fashion_mnist
(train_images, train_labels), (test_images, test_labels) = datasets.load_data()
print(train_images.shape) # (60000, 28, 28)
print(len(train_labels)) # 60000
print(train_labels) # ([9, 0, 0, ..., 3,... | 475 | 214 |
# coding: utf-8
"""
GraphHopper Directions API
You use the GraphHopper Directions API to add route planning, navigation and route optimization to your software. E.g. the Routing API has turn instructions and elevation data and the Route Optimization API solves your logistic problems and supports various const... | 9,994 | 3,123 |
# 1. Elabore uma estrutura para representar um produto (código, nome, preço). Aplique 10% de aumento no preço do produto e apresente.
class TipoProduto:
codigo = 0
nome = ''
preco = 0.0
def main():
p1 = TipoProduto()
p1.codigo = int ( input('Cadastre o código do produto: '))
p1.nome = input('C... | 1,029 | 485 |
from neupy import algorithms
from data import simple_classification
from base import BaseTestCase
class AdamaxTestCase(BaseTestCase):
def test_simple_adamax(self):
x_train, _, y_train, _ = simple_classification()
mnet = algorithms.Adamax(
(10, 20, 1),
step=.01,
... | 568 | 194 |
from src.app import socketio, app
from src.master.config import MPCI_ENVIRONMENT, PORT
if __name__ == "__main__":
isDevelopment = MPCI_ENVIRONMENT != 'production' and MPCI_ENVIRONMENT != 'staging'
port = PORT
if port is None:
port = 5000
socketio.run(app, host="0.0.0.0", port=port, debug=isDev... | 330 | 123 |
from ..core import Source, log, utils
import re
import json
import requests
re_extract_ids = re.compile(
'onclick="Frm\(\'([0-9]+)\'\)"',
re.IGNORECASE
)
# 'a'..'z'
catalogue_index = [chr(i) for i in range(ord('a'), ord('z') + 1)]
re_extract_attr = re.compile(
'<div class="(title|ftr-hdr|ftr-txt|ftr-cpy)... | 5,363 | 1,768 |
###########################################################################
#
## @file communicate.py
#
###########################################################################
import os, sys, textwrap, subprocess, queue
from . import communicate_pb2_grpc
#from collections.abc import Iterable
from ..canonical.c... | 7,543 | 2,439 |
from app import db
from app.models.dog import Dog
from flask import Blueprint, jsonify, make_response, request, abort
import random
dog_bp = Blueprint("dog", __name__, url_prefix="/dogs")
# Helper Functions
def valid_int(number, parameter_type):
try:
number = int(number)
except:
# abort(make_... | 3,335 | 1,215 |
APP = "pomodoro-timer"
APP_NAME = "Pomodoro Timer"
APP_INDICATOR_ID = "pomodoro-timer"
APP_DBUS_NAME = "com.github.Pomodoro"
APP_VERSION = 0.1
| 145 | 70 |
# Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 2, the first 10 terms will be:
#
# 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
#
# By considering the terms in the Fibonacci sequence whose values do not exceed four million, find the sum of the even-valued terms.... | 519 | 202 |
from libpebble2.communication.transports.serial import SerialTransport
from libpebble2.communication import PebbleConnection
class PebbleConnectionFactory():
@staticmethod
def produceSerial(name):
return PebbleConnection(SerialTransport("/dev/tty." + name + "-SerialPortSe")) | 293 | 80 |
def bubble_sort(A, compare_func):
if len(A) <= 1:
return
swapoccurred = True
while swapoccurred:
swapoccurred = False
for i in range(len(A) - 1):
if compare_func(A[i], A[i+1]):
A[i], A[i+1] = A[i+1], A[i]
swapoccurred = True
if __name__ ==... | 403 | 166 |
"""Main OGM API classes and constructors"""
import asyncio
import collections
import logging
import weakref
import aiogremlin
from aiogremlin.driver.protocol import Message
from aiogremlin.driver.resultset import ResultSet
from aiogremlin.process.graph_traversal import __
from gremlin_python.process.traversal import ... | 16,863 | 4,729 |
# @crzypatchwork
from flask import Blueprint, request, session
from pytezos import Contract
from pytezos import pytezos
from pytezos.operation.result import OperationResult
from flask import Flask
from flask_restx import fields, Resource, Api, Namespace
from controllers.validate import Validate
import distutils.util... | 8,108 | 2,521 |
import re
from requests import get
from requests.exceptions import MissingSchema, ConnectionError
import pandas as pd
class Extractor:
def __init__(self, regular_expression):
self.regular_expression = regular_expression
self.elements = set()
def find_elements(self, text):
new_eleme... | 1,987 | 691 |
# F3AT - Flumotion Asynchronous Autonomous Agent Toolkit
# Copyright (C) 2010,2011 Flumotion Services, S.A.
# All rights reserved.
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version... | 7,760 | 2,373 |
import numpy as np
class Boore2003(object):
"""
Implements the correlation model proposed in the appendix of Boore et al.
(2003).
To do
- Inherit from SpatialCorrelation class.
References:
Boore, D. M., Gibbs, J. F., Joyner, W. B., Tinsley, J. C., & Ponti, D.
J. (2003). E... | 1,376 | 430 |
# -*- coding: utf-8 -*-
"""
==========================================
GammaEyes Version 1.0.1 ==
Created at: 2021.07.19 ==
Author@Aiyun Sun ==
Email say@insmea.cn ==
==========================================
GammaEyes is an open sourc... | 98,320 | 32,341 |
from paho.mqtt import client as mqtt
import ssl
from brew_thermometer.errors import ReporterError
import json
class AwsIotReporter:
def __init__(self, config_hash, logger):
self._logger = logger.getChild("AwsIotReporter")
self._broker_host = config_hash["host"]
self._broker_port = config_h... | 2,138 | 671 |
import pytest
from pyriemann_qiskit.utils.hyper_params_factory import (gen_zz_feature_map,
gen_two_local, gates,
get_spsa)
class TestGenZZFeatureMapParams:
@pytest.mark.parametrize(
'entanglem... | 4,905 | 1,530 |
# Python imports.
import random
from collections import defaultdict
class RewardFuncDict(object):
def __init__(self, reward_func_lambda, state_space, action_space, sample_rate=10):
'''
Args:
reward_func_lambda (lambda : simple_rl.State x str --> float)
state_space (list)
... | 1,409 | 426 |
#!/bin/python
"""
Kernel Probability Density Estimator Self-Organizing Map
"""
# python
import re
import os
import sys
import glob
import time
import numpy
import shutil
import subprocess
# appion
from appionlib import appionScript
from appionlib import apXmipp
from appionlib import apDisplay
from appionlib import app... | 13,344 | 5,267 |
# 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, sof... | 1,941 | 595 |
from nbviewer.nbmanager.api.scheduler_provider import SchedulerProvider
# TODO - https://www.quartz-scheduler.net/documentation
class QuartzSchedulerProvider(SchedulerProvider):
def __init__(self, log: any, url: str):
super().__init__(log)
self.url = url
def add_notebook_job(self, notebook):... | 508 | 166 |