text
string
size
int64
token_count
int64
from app.sensor import Sensor from app.uploader import Uploader from app.offline import Offline import time, logging, argparse, sys, random, datetime logging.basicConfig(filename='airquality.log', level=logging.DEBUG, filemode='a', format='%(asctime)s - %(name)s - %(levelname)s - %(message)s') sen...
1,688
622
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # License: BSD # https://raw.githubusercontent.com/splintered-reality/py_trees_ros/devel/LICENSE # ############################################################################## # Documentation ###########################################################################...
3,364
951
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'Friday_Blueprint.ui' # # Created by: PyQt5 UI code generator 5.15.4 # # WARNING: Any manual changes made to this file will be lost when pyuic5 is # run again. Do not edit this file unless you know what you are doing. from PyQt5 import QtC...
11,394
4,070
# # Logistic toy model. # # This file is part of PINTS. # Copyright (c) 2017-2019, University of Oxford. # For licensing information, see the LICENSE file distributed with the PINTS # software package. # from __future__ import absolute_import, division from __future__ import print_function, unicode_literals import n...
3,201
1,082
class Bank: def __init__(self): self.__agencies = [1111, 2222, 3333] self.__costumers = [] self.__accounts = [] def insert_costumers(self, costumer): self.__costumers.append(costumer) def insert_accounts(self, account): self.__accounts.append(account) def authe...
414
136
# Copyright 2013 Philip N. Klein from vec import Vec def list2vec(L): """Given a list L of field elements, return a Vec with domain {0...len(L)-1} whose entry i is L[i] >>> list2vec([10, 20, 30]) Vec({0, 1, 2},{0: 10, 1: 20, 2: 30}) """ return Vec(set(range(len(L))), {k:L[k] for k in range(len...
426
182
from __future__ import annotations from copy import copy, deepcopy from types import MappingProxyType from typing import ( Any, Union, Mapping, TypeVar, Callable, Iterable, Iterator, Sequence, TYPE_CHECKING, ) from pathlib import Path from functools import partial from itertools imp...
59,998
18,452
from django import forms from django.contrib.auth.forms import UserCreationForm from crispy_bootstrap5.bootstrap5 import FloatingField from crispy_forms.layout import Layout from crispy_forms.helper import FormHelper class CustomUserCreationForm(UserCreationForm): email = forms.EmailField() class Meta(UserCr...
397
112
import json import requests import config assignedIdList = list() def __getList(): HEADERS = { 'Cookie': config.tutorzzzCookie, 'Content-Type': 'application/json' } res = requests.post(config.tutorzzzURL, headers = HEADERS, json = config.tutorzzzReqBody) if res.status_code == 200: ...
1,214
410
from invoicing.crud.base_crud import BaseCrud from invoicing.latex.latex_invoice import LatexInvoice from invoicing.models.invoice_model import InvoiceModel from invoicing.repository.invoice_repository import InvoiceRepository from invoicing.repository.job_repository import JobRepository from invoicing.ui.date import D...
3,315
963
from ds3225 import DS3225 import dbus import dbus.mainloop.glib import dbus.service from gi.repository import GObject, GLib UNLOCKED_DEG = 175 dbus.mainloop.glib.DBusGMainLoop(set_as_default=True) BUS_NAME = 'jp.kimura.DS3225Service' OBJECT_PATH = '/jp/kimura/DS3225Server' INTERFACE = 'jp.kimura.DS3225' class DS3225...
946
390
import openpyxl wb= openpyxl.load_workbook('Farmen.xlsx') # sheet= wb.active # print(wb.get_sheet_names()) # Deltagar_sheet= wb.get_sheet_by_name('Deltagare') # artists=[{"Namn":sheet.cell(row=i, column=2).value, # "Sång":sheet.cell(row=i, column=3).value, # "Poäng":sheet.cell(row=i, column=6)....
437
190
from os import access import torch import torch.nn as nn import torch.optim as optim import torch.nn.functional as F from torch.utils.data import DataLoader from torchvision import datasets, transforms import numpy as np import matplotlib.pyplot as plt # Create fully connected neural network class NN(nn.Module): d...
3,437
1,231
import matplotlib.pyplot as plt def plot_loss_mae(history): plt.plot(history.history['loss']) plt.plot(history.history['val_loss']) plt.title('Model loss') plt.ylabel('Loss') plt.xlabel('Epoch') plt.legend(['Train', 'Validation'], loc='best') plt.show() plt.plot(history.history['mae']...
998
360
# -*- coding: utf-8 -*- import os from os.path import dirname, join, normpath import sys from sys import platform from config import config if platform == 'darwin': import objc from AppKit import NSApplication, NSWorkspace, NSBeep, NSSound, NSEvent, NSKeyDown, NSKeyUp, NSFlagsChanged, NSKeyDownMask, NSFlag...
18,695
6,351
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created Nov 2020 @author: hassi """ from qiskit import Aer, IBMQ # Do the necessary import for our program from qiskit.aqua.algorithms import Grover from qiskit.aqua.components.oracles import LogicalExpressionOracle, TruthTableOracle # Import basic plot tools from ...
3,530
1,098
import sys import os import subprocess from subprocess import PIPE, STDOUT from pathlib import Path proc_arg = { 'shell': True, 'stdout': PIPE, 'text': True } def _run(*cmd): proc = subprocess.run(cmd, **proc_arg, stderr=PIPE) return proc.stdout.replace('\n', '') def _popen(...
1,428
617
""" CRUD de SQLite3 con Python 3 """ import sqlite3 try: bd = sqlite3.connect("libros.db") cursor = bd.cursor() busqueda = input("Escribe tu búsqueda: ") if not busqueda: print("Búsqueda inválida") exit() sentencia = "SELECT * FROM libros WHERE titulo LIKE ?;" cursor.execute(sentencia, ...
889
411
import datetime import os import random import sys sys.path = [os.path.abspath(os.path.dirname(__file__))] + sys.path from auto_ml import Predictor from auto_ml.utils_models import load_ml_model import dill from nose.tools import assert_equal, assert_not_equal, with_setup import numpy as np from sklearn.model_selecti...
4,686
1,598
from itm import ITM __all__ = ['ITM']
39
18
import pandas as pd import numpy as np import csv # import synapses divided across hemispheres hemisphere_data = pd.read_csv('left_right_hemisphere_data/brain_hemisphere_membership.csv', header = 0) #print(hemisphere_data) # import pair list CSV, manually generated #pairs = pd.read_csv('data/bp-pairs-2020-01-28.csv',...
2,827
1,072
''' Python program to determine which triples sum to zero from a given list of lists. Input: [[1343532, -2920635, 332], [-27, 18, 9], [4, 0, -4], [2, 2, 2], [-20, 16, 4]] Output: [False, True, True, False, True] Input: [[1, 2, -3], [-4, 0, 4], [0, 1, -5], [1, 1, 1], [-2, 4, -1]] Output: [True, True, False, False, False...
777
398
import torch.nn as nn class Lstm(nn.Module): """ LSTM module Args: input_size : input size hidden_size : hidden size num_layers : number of hidden layers. Default: 1 dropout : dropout rate. Default: 0.5 bidirectional : If True, becomes a bidirectional RNN. Default: False. """ ...
701
240
from django.db.models.signals import pre_save,post_save from django.dispatch import receiver import geoLocApp.models import geoLocApp.distance # @receiver(post_save,sender=geoLocApp.models.Position,dispatch_uid="only_before_registered") # def setDistance(sender, **kwargs): # position = kwargs["instance"] ...
838
279
# Copyright 2018 The Shabda Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable...
2,198
617
import django_filters from app.models import Company class CompanyFilter(django_filters.FilterSet): min_cost = django_filters.NumberFilter(field_name='companyproduct__cost', lookup_expr='gte') max_cost = django_filters.NumberFilter(field_name='companyproduct__cost', lookup_expr='lte') class Meta: ...
441
129
from typing import List import asyncio import inspect import logging import uuid import aio_pika import aio_pika.exceptions from .base import BaseRPC from .common import RPCError, RPCHandler, RPCRequest, RPCResponse class RPC(BaseRPC): HEARTBEAT_INTERVAL = 300 def __init__( self, url: str =...
6,598
1,855
# Generated by Django 3.0.5 on 2020-09-06 19:51 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('api', '0004_auto_20200906_1752'), ] operations = [ migrations.AlterModelOptions( name='category...
2,069
625
import pytz from django.db import models # Create your models here. def _get_time_zones(): """ Function to get all the timezones """ timezone_choices = [(tz, tz) for tz in pytz.all_timezones] return timezone_choices # Model for user class User(models.Model): """ User model: attri...
1,104
344
import pandas as pd # pandas provides us lots of data frame and functions that we can quickly use # to analyze data. """ output """ # This file contains notes of basic data analyzing strategies using Python. # I will introduce two ways to read a csv file: pathway and URL. # Also, I will introduce how to output data ...
1,992
645
import config class InvoiceItemModel(object): def __init__(self, itemType, quantity): self.itemType = itemType self.quantity = int(quantity) self.unitPrice = 0 if itemType == 'Portraiture': self.unitPrice = config.PORTRAIT_RATE else: self.unitPrice ...
768
216
import json import boto3 import os def lambda_handler(event, context): # TODO implement dynamodb = boto3.resource('dynamodb') customerTable = os.environ['customerTable'] table1 = dynamodb.Table(customerTable) policiesTable = os.environ['policiesTable'] table2 = dynamodb.Table(policiesTabl...
1,725
499
from .api import HeapAPI as Heap from .api import HeapType
59
20
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Slixmpp: The Slick XMPP Library Copyright (C) 2015 Emmanuel Gil Peyrot This file is part of Slixmpp. See the file LICENSE for copying permission. """ import asyncio import logging from getpass import getpass from argparse import ArgumentParser impo...
2,849
900
""" Routers for weather_models. """ import logging from fastapi import APIRouter, Depends from app.auth import authentication_required, audit from app.weather_models import ModelEnum from app.schemas.weather_models import ( WeatherModelPredictionSummaryResponse, WeatherStationsModelRunsPredictionsResponse) from...
2,170
604
# # @lc app=leetcode.cn id=155 lang=python3 # # [155] 最小栈 # # https://leetcode-cn.com/problems/min-stack/description/ # # algorithms # Easy (47.45%) # Total Accepted: 19.4K # Total Submissions: 40.3K # Testcase Example: '["MinStack","push","push","push","getMin","pop","top","getMin"]\n[[],[-2],[0],[-3],[],[],[],[]]...
1,529
654
# coding: utf-8 """ Demisto API This is the public REST API to integrate with the demisto server. HTTP request can be sent using any HTTP-client. For an example dedicated client take a look at: https://github.com/demisto/demisto-py. Requests must include API-key that can be generated in the Demisto web clie...
48,845
14,930
# -*- coding: utf-8 -*- # python3 make.py -loc "data/lines/1.csv" -width 3840 -height 2160 -overwrite # python3 make.py -loc "data/lines/1.csv" -width 3840 -height 2160 -rtl -overwrite # python3 combine.py # python3 make.py -data "data/lines/A_LEF.csv" -width 3840 -height 2160 -loc "data/lines/C.csv" -img "img/A.png" ...
36,274
13,083
# ##### BEGIN GPL LICENSE BLOCK ##### # # 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 2 # of the License, or (at your option) any later version. # # This program is distrib...
15,487
5,001
""" OpenVINO DL Workbench Class for create setup bundle job Copyright (c) 2020 Intel Corporation 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...
6,151
1,659
#!/usr/bin/env python3 import logging from os.path import expanduser from typing import Any, Dict from uuid import uuid4 import rospy from awsiotclient import mqtt, pubsub from ros_awsiot_agent import set_module_logger from rosbridge_library.internal.message_conversion import populate_instance from rosbridge_library....
2,365
837
import sys import re from PyQt4 import QtGui, QtCore from polynomial import Polynomial from rational import Rational class Window(QtGui.QMainWindow): width, height = 420, 130 def __init__(self): super().__init__() self.setFixedSize(Window.width, Window.height) self.setWindowTitle('...
5,031
1,722
from secrets import token_hex import pytest class Object: pass class FakeContext(dict): def __init__(self): req_obj = Object() req_obj.cookies = {} req_obj.client = Object() req_obj.client.host = token_hex(5) req_obj.headers = { 'origin': 'some_origin...
493
164
# Copyright (c) 2020 Julian Bernhard, # Klemens Esterle, Patrick Hart, Tobias Kessler # # This software is released under the MIT License. # https://opensource.org/licenses/MIT from bark.benchmark.benchmark_result import BenchmarkConfig from bark_ml.library_wrappers.lib_fqf_iqn_qrdqn.agent import TrainingBenchmark fro...
4,552
1,335
"""Unit tests for /tenants/<id>/cloud endpoints.""" # Copyright 2015 Solinea, Inc. # # 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 # # Unles...
27,023
8,115
# Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. import os import sys import shutil import onnx import onnxruntime import json from google.protobuf.json_format import MessageToJson import predict_pb2 import onnx_ml_pb2 # Current models only have one input and one output...
4,750
1,767
from revscoring.datasources.revision_oriented import revision from revscoring.dependencies import solve from .. import enwiki revision_text = revision.text def test_cite_templates(): text = """ This is some text with a citation.<ref>{{cite lol|title=Made up}}</ref> This is some more text. {{foo}} {{{cit...
2,484
808
# -*- coding: utf-8 -*- """ Created on Mon Aug 10 14:31:17 2015 @author: Kevin M. Description: This script does CPU and GPU matrix element time complexity profiling. It has a function which applies the matrix element analysis for a given set of parameters, profiles the code and ...
6,984
2,556
import Sofa import SofaTest import SofaPython.Tools OBJ = SofaPython.Tools.localPath( __file__, "beam.obj" ) RAW = SofaPython.Tools.localPath( __file__, "beam.raw" ) ##Check if calling Mapping::init() change anything # #The trick is to know that if the option evaluateShapeFunction is activated #in the ImageGaussPoint...
7,714
2,467
# Copyright 2020 Huawei Technologies Co., Ltd # # 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...
1,688
455
# 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 unde...
11,496
3,667
from django.db import models from django import forms # Create your models here. class User(models.Model): username = models.CharField(max_length=30) password = models.TextField() email = models.EmailField(unique=True) objects = models.Manager() def __str__(self): return self.username clas...
493
149
def do_twice(f): f() f() def print_spam(): print('spam') do_twice(print_spam) def do_twice(f, a): f(a) f(a) def print_spam(a): print(a) print(a) do_twice(print_spam, 'spamm') def do_four(f, a): do_twice(f,a) do_twice(f,a) do_four(print_spam, "SPAM") def hor_line(): print(...
2,970
1,354
from django.apps import AppConfig class EmailLogConfig(AppConfig): name = 'email_log' verbose_name = "Email log"
123
39
import pytest from gawain.numerics import Clock, SolutionVector, MHDSolutionVector
83
26
""" utility for project 9 :author: Seongsu Yoon <sople1@snooey.net> :license: CC0 """ def clear(): """ clear cmd/term :return: void """ import os import sys if sys.platform == 'win32': os.system('cls') # on windows else: os.system('clear') # on linux / os x if __...
384
143
from rest_framework.views import APIView from .models import User, Event from .serializer import UserSerializer, EventSerializer from rest_framework.permissions import AllowAny, IsAuthenticated from rest_framework.authentication import TokenAuthentication from rest_framework import status, mixins, generics from rest_f...
2,383
737
# LC 462 #from statistics import median from random import randrange from math import floor class Solution: #Quick Select Algorithm def partition(self,x, pivot_index = 0): i = 0 if pivot_index !=0: x[0],x[pivot_index] = x[pivot_index],x[0] for j in range(len(x)-1): if x[j+1] ...
1,582
567
__version__ = "0.3.9" __author__ = "C. W."
43
23
import imgurpython from Environment_Handlers.configs import get_config import random client_id = get_config("client_id") client_secret = get_config("client_secret") client_refresh_token = get_config("client_refresh") client_access_token = get_config("client_access_token") username = 'antipoliticsrick' client = imgur...
666
220
# flake8: noqa from .base import BaseExperiment from .config import ConfigExperiment from .supervised import SupervisedExperiment
131
36
import os import argparse import subprocess from workflow import Workflow def get_kubectl_cmd_path(): wf = Workflow() return wf.settings.get("KUBECTL_CMD_PATH") or os.environ.get("KUBECTL_CMD_PATH", '/usr/local/bin/kubectl') class KService: def __init__(self, type, name, age, status): self.type =...
3,217
1,145
""" Tk2 Tk2 is a convenience library for extending the functionality of Tkinter, to make it easier and more flexible to create GUI applications. """ from .basics import * from .scrollwidgets import * from .texteditor import Text, MultiTextSearch from .variables import * # Later from .multiwidgets import * from .pr...
528
146
def test_nonop(): assert 1 == 1
37
18
import os import time import torch import torch.nn as nn class BasicModule(nn.Module): ''' 封装nn.Module, 提供 save 和 load 方法 ''' def __init__(self): super(BasicModule, self).__init__() def load(self, path, device): ''' 加载指定路径的模型 ''' self.loa...
803
337
class AliasNotFound(Exception): def __init__(self, alias): self.alias = alias class AliasAlreadyExists(Exception): def __init__(self, alias): self.alias = alias class UnexpectedServerResponse(Exception): def __init__(self, response): self.response = response
310
93
#********************************************************************* # content = init Nuke # version = 0.1.0 # date = 2019-12-01 # # license = MIT <https://github.com/alexanderrichtertd> # author = Alexander Richter <alexanderrichtertd.com> #**************************************************************...
3,135
1,024
# -*- coding: utf-8 -*- # Created at 03/10/2020 __author__ = 'raniys' import pytest if __name__ == '__main__': # -v: verbose; -s: shortcut for --capture=no; # -m: only run tests matching given mark expression. example: -m 'mark1 and not mark2'; # --html=path: create html report file at given path. # ...
589
231
#!/usr/bin/env python import os, sys import subprocess import re import glob errlog = [] def run(f): cmd = "../../lslc" p = subprocess.Popen([cmd, f], stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True) outs = [l for l in p.stdout] errs = [l for l in p.stderr] errline = re.compile...
863
318
from torch import Tensor, nn from ...base import VisionModule class ClassificationModule(VisionModule): """Base Classification Module class""" def __init__( self, encoder: nn.Module, head: nn.Module, in_channels: int = 3, n_classes: int = 1000, **kwargs ):...
657
216
# -*- coding: utf-8 -*- import os import numpy as np import sys import logging import csv # Setup logging logger = logging.getLogger(__name__) console_handle = logging.StreamHandler() console_handle.setLevel(logging.INFO) formatter = logging.Formatter('%(asctime)s: %(message)s', datefmt='%m-%d %H:%M') cons...
3,202
1,079
#!/usr/bin/env python from iris_sdk.models.base_resource import BaseData from iris_sdk.models.maps.tn_status import TnStatusMap class TnStatus(TnStatusMap, BaseData): pass
177
61
#!/usr/bin/python # -*- coding: utf-8 -*- # # Copyright: (c) 2017, F5 Networks Inc. # GNU General Public License v3.0 (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import absolute_import, division, print_function __metaclass__ = type DOCUMENTATION = r''' --- module: bigip_device_group_memb...
8,437
2,500
from elasticsearch import TransportError from sanic import Blueprint from sanic.request import Request from sanic.response import HTTPResponse, json from ..connections import get_client rest_bp = Blueprint('rest') def format_es_exception(e: TransportError): return json({"status_code": e.status_code, ...
793
227
from datetime import datetime from pytz import timezone, utc from pytest import mark from pyexchange.utils import convert_datetime_to_utc def test_converting_none_returns_none(): assert convert_datetime_to_utc(None) is None def test_converting_non_tz_aware_date_returns_tz_aware(): utc_time = datetime(year=2014,...
1,081
401
import argparse from .upload_video import upload_video from .generate_playlist import generate_playlist def parse_args(argv): parser = argparse.ArgumentParser() parser.add_argument( "-u", "--upload", action="store_true", help="Upload videos to YouTube channel" ) parser.add_argument( "...
786
240
# MIT License # # Copyright (c) 2020 Brett Graves # # 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, modify, merge,...
3,275
1,074
from argo_dataflow import pipeline, kafka def handler(msg, context): return ("hi! " + msg.decode("UTF-8")).encode("UTF-8") if __name__ == '__main__': (pipeline("104-python3-9") .owner('argoproj-labs') .describe("""This example is of the Python 3.9 handler. [Learn about handlers](../docs/HANDLERS....
460
166
import asyncio import discord from commands import Commands, Guild_Instance, leave, play_search import os from pymongo import MongoClient from dotenv import load_dotenv load_dotenv() CONNECTION_STRING = f"mongodb+srv://{os.environ['mongo_user']}:{os.environ['mongo_pass']}@djangur.erogd.mongodb.net/djangur?retryWrites...
2,195
743
# -*- coding: utf-8 -*- from datetime import datetime, timedelta from decimal import Decimal import logging from django.core.files.storage import FileSystemStorage from membership.billing.pdf_utils import get_bill_pdf, create_reminder_pdf from membership.reference_numbers import barcode_4, group_right,\ generate_...
44,236
12,949
from .imaxt import ImaxtFileReader from .mcd import McdFileReader from .txt import TxtFileReader __all__ = [ 'ImaxtFileReader', 'McdFileReader', 'TxtFileReader', ]
177
65
import torch from torch.utils.data import Dataset import numpy as np import os import pickle from madmom.features import DBNBeatTrackingProcessor import torch from model import BeatTrackingNet from utils import init_single_spec from mir_eval.beat import evaluate from data import BallroomDataset from beat_tracker im...
2,449
726
# coding=utf-8 """ Script to generate city object. """ from __future__ import division import os import numpy as np import pickle import warnings import random import datetime import shapely.geometry.point as point import pycity_base.classes.Weather as weath import pycity_base.classes.demand.SpaceHeating as SpaceHeati...
130,468
35,422
# Basile Van Hoorick, March 2020 # Common code for PyTorch implementation of Copy-Pasting GAN import copy import itertools import matplotlib.pyplot as plt import numpy as np import os, platform, time import torch import torch.nn as nn import torch.nn.functional as F import torchvision import torchvision.transforms as ...
14,092
4,635
# -*- coding: utf-8 -*- # Copyright: (c) 2018, Ansible Project # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) from __future__ import (absolute_import, division, print_function) __metaclass__ = type DOCUMENTATION = """ become: dzdo short_description: Centrify's Dire...
3,207
951
import unittest import os if __name__ == '__main__' and __package__ is None: from os import sys, path sys.path.append(path.abspath(path.join(__file__, "..", ".."))) sys.path.append(path.abspath(path.join(__file__, "..", "..", "..", "classes_and_tests"))) from php.functions import * from src.mocking.MockFi...
3,078
981
import sys import numpy as np import matplotlib.pyplot as plt from PIL import Image import efficientnet.keras as efn import streamlit as st import SessionState from skimage.transform import resize import skimage import skimage.filters import reportgenerator import style from keras.models import Model, load_model st.set...
5,629
1,746
# -*- coding: utf-8 -*- """Richardson-Extrapolation.ipynb Automatically generated by Colaboratory. Original file is located at https://colab.research.google.com/drive/1oNlSL2Vztk9Fc7tMBgPcL82WGaUuCY-A Before you turn this problem in, make sure everything runs as expected. First, **restart the kernel** (in the me...
7,129
2,933
"""The :mod:`mlshell.pipeline.steps` contains unified pipeline steps.""" import inspect import mlshell import numpy as np import pandas as pd import sklearn import sklearn.impute import sklearn.compose __all__ = ['Steps'] class Steps(object): """Unified pipeline steps. Parameters ---------- estim...
9,050
2,567
from datetime import datetime import peewee from paste import domain from . import db class AbstractRepository(domain.IRepository): _model = NotImplemented _entity = NotImplemented def count(self): return self._model.count() def save(self, entity): model = _entity_to_model(entity...
2,283
730
# Dataset https://archive.ics.uci.edu/ml/datasets/Nursery import numpy as np import pandas as pd from collections import Counter from sklearn.model_selection import train_test_split, GridSearchCV, StratifiedKFold from imblearn.metrics import geometric_mean_score from sklearn.metrics import mean_squared_error, make_s...
3,278
1,280
# -*- coding: utf-8 -*- # StreamOnDemand Community Edition - Kodi Addon # ------------------------------------------------------------ # streamondemand.- XBMC Plugin # Canale piratestreaming # http://www.mimediacenter.info/foro/viewforum.php?f=36 # ------------------------------------------------------------ import re ...
8,187
2,619
########################################################################## # # Copyright (c) 2008-2010, Image Engine Design Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redis...
5,259
2,502
def makePic(): file = pickAFile() return makePicture(file) def decreaseRed(picture): for pixel in getPixels(picture): setRed(pixel, getRed(pixel) * 0.2) repaint(picture) def decreaseRed2(picture): pixels = getPixels(picture) for i in range(len(pixels)): pixel = pixels[i] setRe...
1,161
494
from __future__ import annotations import abc from typing import Any, Dict class BoxInterface(abc.ABC): """ Interface for box. """ @property # type: ignore @abc.abstractmethod def label(self) -> int: """ Label id. :return: Label id. """ pass @label.sett...
1,425
395
import torch import prifair as pf N_SAMPLES = 10000 VAL_SAMPLES = 1000 STUDENT_SAMPLES = 5000 INPUTS = 1000 OUTPUTS = 5 BATCH_SIZE = 256 MAX_PHYSICAL_BATCH_SIZE = 128 EPSILON = 2.0 DELTA = 1e-5 MAX_GRAD_NORM = 1.0 N_TEACHERS = 4 N_GROUPS = 10 EPOCHS = 2 class MockModel(torch.nn.Module): def __init__(self): ...
4,627
1,722
from collections import deque n,x=int(input()),deque() for i in range(1,n+1): x.append(i) while len(x)>1: x.popleft() if len(x)==1: break x.append(x.popleft()) print(x.pop())
177
77
import re _TIMEZONE_REGEX = re.compile(r"^([+-](2[0-3]|[01][0-9])(:?[0-5][0-9])?|Z)$") TIMEZONES = { "UTC": "+00:00", "GMT": "+00:00", "BST": "+01:00", "IST": "+01:00", "WET": "+00:00", "WEST": "+01:00", "CET": "+01:00", "CEST": "+02:00", "EET": "+02:00", "EEST": "+03:00", ...
2,430
1,020
# # General-purpose Photovoltaic Device Model - a drift diffusion base/Shockley-Read-Hall # model for 1st, 2nd and 3rd generation solar cells. # Copyright (C) 2008-2022 Roderick C. I. MacKenzie r.c.i.mackenzie at googlemail.com # # https://www.gpvdm.com # # This program is free software; you can redist...
2,066
811
from . import BasePlugin from gru.config import settings class Host(object): def __init__(self, host_id, host_data=None): self.host_id = host_id if host_data: self.host_data = host_data else: self.host_data = {} def __repr__(self): return 'Host(host_...
4,637
1,280