content
stringlengths
0
894k
type
stringclasses
2 values
#py_gui.py "gui basics" from tkinter import * class Application(Frame): pass root = Tk() app = Application(master=root) app.mainloop()
python
''' There are a total of numCourses courses you have to take, labeled from 0 to numCourses-1. Some courses may have prerequisites, for example to take course 0 you have to first take course 1, which is expressed as a pair: [0,1] Given the total number of courses and a list of prerequisite pairs, is it possible for yo...
python
"""This acts as a kind of middleware - which has now been whittled down to only providing logging information""" import logging import platform from .constants import NameSpace from .config import CLIInputs, ParsedArgs from .utils import read_sdk_version logger = logging.getLogger("validate-cli-args") class Validat...
python
# unet.py # from __future__ import division import torch.nn as nn import torch.nn.functional as F import torch from numpy.linalg import svd from numpy.random import normal from math import sqrt class UNet(nn.Module): def __init__(self, colordim = 1): super(UNet, self).__init__() self.conv1_1 = nn.Conv2d(colord...
python
# First, we import a tool to allow text to pop up on a plot when the cursor # hovers over it. Also, we import a data structure used to store arguments # of what to plot in Bokeh. Finally, we will use numpy for this section as well! from bokeh.models import HoverTool, ColumnDataSource from bokeh.plotting import figur...
python
from typing import Literal, Optional, Union class Trust_Region_Options: border_abstol: float = 1e-10 tol_step: float = 1.0e-10 tol_grad: float = 1.0e-6 abstol_fval: Optional[float] = None max_stall_iter: Optional[int] = None init_delta: float = 1.0 max_iter: int check_rel: float = 1.0e...
python
import sqlite3 import os import MLBProjections.MLBProjections.DB.MLB as MLB import MLBProjections.MLBProjections.Environ as ENV from pprint import pprint ################################################################################ ################################################################################ ...
python
# # Functional Python: The Lambda Lambada (Recursion) # Python Techdegree # # Created by Dulio Denis on 3/22/19. # Copyright (c) 2019 ddApps. All rights reserved. # ------------------------------------------------ # Recursion Challenge # ------------------------------------------------ # Challenge Task 1 of 1 # ...
python
#!/usr/bin/env python import os import random import requests import subprocess import argparse import datetime import time import sys """Based off https://github.com/fogleman/primitive/blob/master/bot/main.py """ with open(os.path.expanduser('~/.flickr_api_key'), 'r') as key_file: FLICKR_API_KEY = key_file.read...
python
import multiprocessing as mp import time def foo_pool(taskQ, x): print(x) taskQ.put(x) return x*x result_list = [] def log_result(result): # This is called whenever foo_pool(i) returns a result. # result_list is modified only by the main process, not the pool workers. result_list.append(result...
python
# Crie um script Python que leia o nome de uma pessoa e mostre uma mensagem de boas-vindas de acordo com o valor digitado msg = 'Olá Mundo!' print(msg)
python
import ldap import json import socket from urllib.parse import urlparse def create_from_env(): import os auth = LdapAuth(os.environ.get('LDAP_ADDRESS')) auth.base_dn = os.environ.get('LDAP_BASE_DN') auth.bind_dn = os.environ.get('LDAP_BIND_DN') auth.bind_pass = os.environ.get('LDAP_BIND_PASS') ...
python
# %% coding=utf-8 import pandas as pd from atm import ATM from sklearn.model_selection import train_test_split beauty_data = pd.read_csv('/data/face/df_input.csv') select_cols = ['Image', 'label', '0_10_x', '0_10_y', '0_11_x', '0_11_y', '0_12_x', '0_12_y', '0_13_x', '0_13_y', '0_14_x', '0_14_y', '0_15_x...
python
from .descriptor import DescriptorType from .object_type import ObjectDict __all__ = ["ObjectDict", "DescriptorType"]
python
from typing import List class Solution: # 141, 逆波兰表达式求值, Medium def evalRPN(self, tokens: List[str]) -> int: stack = [] for token in tokens: if token == "+": oprand2 = stack.pop() oprand1 = stack.pop() stack.append(oprand1 +...
python
# we are here to get weighted-5-node-subgraph, # given edge-count/bi-edge-count/strong-tie-count/weak-tie-count only to distinguish # to leverage on weighte 4 node subgraphs(edge_count, biedge_count, strong_count, weak_count, subNo) # next to share not edge import re,sys,random, os def subg(edges,s4,lf,sf,sfv,ror): ...
python
#!/usr/bin/env python from distutils.core import setup setup(name="Eng Phys Office Space Tools", description="A set of scripts to work with the Eng Phys office space committee", version="0.1dev", author="Tim van Boxtel", author_email="vanboxtj@mcmaster.ca", py_modules=['parse-grad-studen...
python
import tweepy #https://github.com/tweepy/tweepy import csv import pandas as pd # Used for progress bar import time import sys #Twitter API credentials consumer_key = "NBNgPGCBeGv80PcsYU3QWU94d" consumer_secret = "lvAaoSInlF9mPonoMMldFq5ZE96oAAl30TLh6ynVwK2tauvOQC" access_key = "1311728151265832961-AaFHXfZtozEgfoVZoFnN...
python
#Pygments Tk Text from http://code.google.com/p/pygments-tk-text/ #Original Developer: Jonathon Eunice: jonathan.eunice@gmail.com __author__ = 'Robert Cope' __original__author__ = 'Jonathan Eunice'
python
import random def generatePassword(pwlength): alphabet = "abcdefghijklmnopqrstuvwxyz" passwords = [] for i in pwlength: password = "" for j in range(i): next_letter_index = random.randrange(len(alphabet)) password = password + alphabet[next...
python
GAME_SIZE = 4 SCORE_TO_WIN1 = 512 SCORE_TO_WIN2 = 1024 SCORE_TO_WIN3 = 2048 SCORE_TO_WIN0 = 256 from game2048.game import Game from game2048.agents import ExpectiMaxAgent # save the dataset f1 = open("dataset_256_3.txt", "w") f2 = open("dataset_512_3.txt", "w") f3 = open("dataset_1024_3.txt", "w") # for i in range(1...
python
""" #################################################################################################### # Copyright Info : Copyright (c) Davar Lab @ Hikvision Research Institute. All rights reserved. # Filename : embedding.py # Abstract : torch.nn.Embedding function encapsulation. # Current Versi...
python
from tweepy import Stream from stream_tweets import StockListener import get_old_tweets import logging logger = logging.getLogger(__name__) logging.basicConfig(level=logging.DEBUG) def getTweets(stock_name): twitter_stream = Stream(get_old_tweets.auth, StockListener(stock_name)) twitter_stream.filter(track=[...
python
from painter.config import NAME, PATH, SHELVES from templates import app # Painter base PAINTER = app.App(NAME, PATH, SHELVES)
python
"""Various lower-level functions to support the computation of steady states""" import warnings import numpy as np import scipy.optimize as opt from numbers import Real from functools import partial from ...utilities import misc, solvers def instantiate_steady_state_mutable_kwargs(dissolve, block_kwargs, solver_kwa...
python
from django.db import models from .book import Book from .language import Language class BookLanguage(models.Model): id = models.AutoField( primary_key=True, editable=False) book = models.ForeignKey( Book, db_column='book_id', blank=False, null=False, on_delet...
python
from __future__ import absolute_import, unicode_literals from appearance.classes import Icon icon_acl_list = Icon(driver_name='fontawesome', symbol='lock')
python
#!/usr/bin/env/python3 import os import sys import typing THIS_SCRIPT_DIR = sys.path[0] INCLUDE_DIR = THIS_SCRIPT_DIR + "/../src/include/cleantype/" ALL_IN_ONE_FILE = THIS_SCRIPT_DIR + "/include/cleantype/cleantype.hpp" MAIN_TITLE = """ // CleanType : amalgamated version // // This file is part of CleanType: Clean T...
python
import datetime from bs4 import BeautifulSoup from kik_unofficial.utilities.cryptographic_utilities import CryptographicUtils from kik_unofficial.datatypes.xmpp.base_elements import XMPPElement, XMPPResponse class GetMyProfileRequest(XMPPElement): def __init__(self): super().__init__() def seriali...
python
import sys sys.path.append('../../../') import unittest import numpy as np from spiketag.base import ProbeFactory class TestProbe(unittest.TestCase): def test_linear_probe(self): linear_probe = ProbeFactory.genLinearProbe(25e3, 32) expected_type = 'linear' expected_n_group = ...
python
"""{{cookiecutter.project_description}}""" import logging from {{cookiecutter.package_name}}.wsgi import ApplicationLoader from {{cookiecutter.package_name}}.version import __version__ # noqa: F401 # initialize logging log = logging.getLogger(__name__) log.addHandler(logging.NullHandler())
python
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # @Date : Mar-27-21 01:06 # @Author : Kan HUANG (kan.huang@connect.ust.hk) # @RefLink : https://pytorch.org/tutorials/intermediate/char_rnn_classification_tutorial.html from __future__ import unicode_literals, print_function, division import os import random import s...
python
from . import db from flask.ext.login import UserMixin, AnonymousUserMixin from datetime import datetime class ScrapeCount(db.Model): __tablename__ = 'scrapecounts' id = db.Column(db.Integer, primary_key=True) websitename = db.Column(db.String(200)) count = db.Column(db.Integer) date = db.Column(d...
python
import json import torchvision import data as data_module from examples.NIPS.generate_data_utils import gather_examples import pandas as pd preprocessable = pd.read_pickle('/home/roigvilamalam/projects/Urban-Sound-Classification/preprocessable.pkl') preprocessable = preprocessable[preprocessable['preprocessable']] ...
python
from flask import Flask, render_template, url_for, request, redirect, g, jsonify, flash, session, Markup from bs4 import BeautifulSoup from pymongo import * from functools import wraps from datetime import datetime import requests import csv import boto3 import ckapi import validation from settings import * # FLASK CO...
python
# @Author: Leeroy P. Williams # @Date: 29/09/19 # @Problem: If we list all the natural numbers below 10 that are # multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. # Find the sum of all the multiples of 3 or 5 below 1000 # @Solution: Correct def multi(a, b, array): ...
python
# -*- coding: utf-8 -*- """ =============================================================================== Trajectory class for MD simulations (:mod:`sknano.core.atoms._trajectory`) =============================================================================== Classes for analyzing the atom trajectories of molecular...
python
from django.http import HttpResponse, HttpResponseRedirect from django.contrib.auth import authenticate, login, logout from django.shortcuts import redirect, render, get_object_or_404 from django.urls import reverse from django.contrib.auth.decorators import login_required from ranbo.forms import * from django.core.exc...
python
import nltk, re, pprint from urllib.request import urlopen url = "http://nrs-projects.humboldt.edu/~st10/s20cs328/328lect15-1/328lect15-1-projected_txt.html" raw = urlopen(url).read() print(type(raw)) print(len(raw)) #natural language string nls = nltk.clean_html(raw) tokens = nltk.word_tokenize(raw) print(tokens)
python
import os from setuptools import ( setup, find_packages ) curr_dir = os.path.dirname(os.path.abspath(__file__)) install_requirements = [ "pydantic>=1.8", "cryptography>=3.4" ] setup( name="restless", version="0.0.1-dev", description="Just an easy-to-use cryptographic Python module", long_description=...
python
from django.apps import apps from rest_framework import serializers from common.constants import models Profile = apps.get_model(models.PROFILE_MODEL) User = apps.get_model(models.USER_MODEL) class ProfileSerializer(serializers.ModelSerializer): """ API serializer for :class:`Profile`. """ class Me...
python
# -*- coding: UTF-8 -*- # @Author : Chenyang Wang # @Email : THUwangcy@gmail.com """ Caser Reference: "Personalized Top-N Sequential Recommendation via Convolutional Sequence Embedding" Jiaxi Tang et al., WSDM'2018. Reference code: https://github.com/graytowne/caser_pytorch Note: We use a maximum of...
python
from pseudo_python.builtin_typed_api import builtin_type_check from pseudo_python.errors import PseudoPythonTypeCheckError class Standard: ''' Standard classes should respond to expand and to return valid nodes on expand ''' pass class StandardCall(Standard): ''' converts to a standard cal...
python
import tensorflow as tf def MaxAvgPooling2D(m,n, model): max = tf.keras.layers.MaxPool2D(pool_size=(2,2), strides=1, padding='SAME')(model) avg = tf.keras.layers.AveragePooling2D(pool_size=(2,2), strides=1, padding='SAME')(model) model = (max*m + avg*n)/(m+n) return model
python
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Preprocessing ZTF database to be saved as a samplesx21x21x3 numpy array in a pickle TODO: clean_NaN once cropped TODO: unit tests ToDo: instead of cascade implement as pipeline, in order to have single call and definition ToDo: smart way to shut down nans @author: as...
python
import base64 import random from django.conf import settings from django.core.cache import caches from django.core.mail import send_mail from apps.user.models import User from libs.yuntongxun.sms import CCP from meiduoshop.celery import app @app.task def async_send_sms(to, datas, template_id): """异步发送短信验证码 注意结果...
python
import os from typing import Dict, List, Optional, Union, Callable from tinydb.storages import MemoryStorage, JSONStorage from ..custom_typings import DataDict, PathType class BaseDB(JSONStorage, MemoryStorage): """Base storage class that reads which extensions are available to feed the path handling functio...
python
# Licensed to Elasticsearch B.V. under one or more contributor # license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright # ownership. Elasticsearch B.V. licenses this file to you under # the Apache License, Version 2.0 (the "License"); you may # not use ...
python
""" utility functions """ import collections def flatten(d, parent_key="", sep="_"): """ flatten nested dictionary, preserving lists Arguments: parent_key (str): sep (str): """ items = [] for k, v in d.items(): new_key = parent_key + sep + k if parent_key else k ...
python
import tensorflow as tf import datetime as dt import pandas as pd import os def load_data(): col_names = [ 'id', 'event_timestamp', 'course_over_ground', 'machine_id', 'vehicle_weight_type', 'speed_gps_kph', 'latitude', 'longitude'] data = pd.DataFrame(columns=col_names) files = os.listd...
python
from jenkinsapi.jenkins import Jenkins import xml.etree.ElementTree as ET J = Jenkins('http://localhost:8080') EMPTY_JOB_CONFIG = ''' <?xml version='1.0' encoding='UTF-8'?> <project> <actions>jkkjjk</actions> <description></description> <keepDependencies>false</keepDependencies> <properties/> <scm class="hud...
python
import os from typing import List, Optional from uuid import uuid4 import PIL import pytest import arcade import arcade.gui from arcade.gui import UIClickable, UIManager from arcade.gui.ui_style import UIStyle class TestUIManager(UIManager): def __init__(self, *args, **kwargs): super().__init__(*args, *...
python
class Solution(object): def deleteDuplicates(self, head): ht = {} it = head while head: if head.val in ht: ht[head.val] += 1 else: ht[head.val] = 1 head = head.next headRef = None last = None whi...
python
#!/usr/bin/env python import sys from os.path import exists as path_exists from pyscaffold.api import create_project from pyscaffold.cli import run from pyscaffold.extensions.github_actions import GithubActions def test_create_project_with_github_actions(tmpfolder): # Given options with the GithubActions extensi...
python
import glob from os.path import join import numpy as n import astropy.io.fits as fits import lib_functions_1pt as lib import os import sys #Quantity studied version = 'v4' qty = "mvir" # one point function lists fileC = n.array(glob.glob( join(os.environ['MD_DIR'], "MD_*Gpc*", version, qty,"out_*_Central_JKresampli...
python
# -*- Mode:Python; indent-tabs-mode:nil; tab-width:4 -*- # # Copyright 2002 Ben Escoto <ben@emerose.org> # Copyright 2007 Kenneth Loafman <kenneth@loafman.com> # # This file is part of duplicity. # # Duplicity is free software; you can redistribute it and/or modify it # under the terms of the GNU General Public License...
python
from django.test import TestCase from rest_framework.test import APIClient from teams.models import Team class TeamTestCase(TestCase): """ Test set for Team CRD (there is no update here) """ client = APIClient() trainer_id = 0 team_id = 0 def setUp(self): """ Set up case. ...
python
import os import sqlite3 from datetime import datetime from flask import g DATABASE = 'test.db' def get_db(): if not os.path.isfile(DATABASE): create_database() db = getattr(g, '_database', None) if db is None: db = g._database = sqlite3.connect(DATABASE) return db def save_msg(msg...
python
__author__ = "Hangi,Kim" __copyright__ = "Copyright 2012-2013, The SAGA Project" __license__ = "MIT" """ IBM LoadLeveler job adaptor implementation reference for pbs job adaptor & sge job adaptor implementation Hangi, Kim hgkim@kisti.re.kr """ import os import re import time from urllib.parse impor...
python
# Privacy Policy Browser # Credit: Josiah Baldwin, Eric Dale, Ethan Fleming, Jacob Hilt, # Darian Hutchinson, Joshua Lund, Bennett Wright # # The alexa skill is implemented as a collection of handlers for certain types of user input. # This is paired with a S3 bucket that is holding data about location & acce...
python
from sklearn.preprocessing import StandardScaler from scipy import ndimage import nilearn from sklearn.preprocessing import MinMaxScaler from sklearn.preprocessing import RobustScaler from sklearn.preprocessing import PowerTransformer from scipy.stats import variation import numpy as np from densratio import densratio ...
python
class Player(object): def __init__(self, name, connection): self.connection = connection self.name = name self.score = 0
python
import json from typing import List, Tuple import boto3 from botocore.client import BaseClient from logger.decorator import lambda_auto_logging from logger.my_logger import MyLogger from utils.lambda_tool import get_environ_values from utils.s3_tool import ( create_key_of_eorzea_database_merged_item, create_k...
python
#!/usr/bin/python """ `yap_ipython.external.mathjax` is deprecated with yap_ipython 4.0+ mathjax is now install by default with the notebook package """ import sys if __name__ == '__main__' : sys.exit("yap_ipython.external.mathjax is deprecated, Mathjax is now installed by default with the notebook package")
python
from random import random from player import Player from pokerUtils import PokerUtils from board import Board def decide(playerdecision, player, callamount, raiseamount=0): # fold if playerdecision == 2: print(player.getname() + " loses") players.remove(player) # raise if...
python
# # # This script compiles and runs all examples in /examples # by mpifort and mpirun on four processors. # # # Glob: https://docs.python.org/2/library/glob.html import glob # OS: https://docs.python.org/2/library/os.html import os for ftest in glob.glob('examples/*.f90'): print("compile "+ftest) os.system('mpifor...
python
from django_unicorn.components import UnicornView import requests from bs4 import BeautifulSoup class ContcompView(UnicornView): url = "https://example.com" headers = { 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Methods': 'GET', 'Access-Control-Allow-Headers': 'Content-Type', 'Ac...
python
from flask import Blueprint, render_template, jsonify, app from edinet import edinet_methods from eve_docs.config import get_cfg def edinet_docs(): blueprints = [edinet_methods.edinet_methods] eve_docs = Blueprint('eve_docs', __name__, template_folder='templates') @eve_docs.route...
python
from app.dao.permissions_dao import permission_dao from tests.app.db import create_service def test_get_permissions_by_user_id_returns_all_permissions(sample_service): permissions = permission_dao.get_permissions_by_user_id(user_id=sample_service.users[0].id) assert len(permissions) == 8 assert sorted(["m...
python
from django.urls import path from .views import * from .import views app_name = 'offers' urlpatterns = [ # Renda Fixa # ------------------------------------------------------------------------------------------------------------------ # Listar path('rf/listar/', OfferRfListView.as_view(), name="lista...
python
from ..legend import Legend def size_continuous_legend(title=None, description=None, footer=None, prop='size', variable='size_value', dynamic=True, ascending=False, format=None): """Helper function for quickly creating a size continuous legend. Args: prop (str, optional): A...
python
import unittest from app.models import Role class RoleModelTest(unittest.TestCase): def setUp(self): self.new_role = Role('1','admin') if __name__ =='__main__': unittest.main()
python
""" dotfiles ~~~~~~~~ Dotfiles is a tool to make managing your dotfile symlinks in $HOME easy, allowing you to keep all your dotfiles in a single directory. :copyright: (c) 2011-2016 by Jon Bernard. :license: ISC, see LICENSE.rst for more details. """ __version__ = '0.9.dev0'
python
""" """ import sys sys.path.append("..") # import one subdirectory up in files import numpy as np from networks.networks import IsoMPS #%% XXZ Tenpy MPO from tenpy.models.model import CouplingMPOModel, NearestNeighborModel from tenpy.tools.params import asConfig from tenpy.networks.site import SpinHalfSite #__all__...
python
#!/usr/bin/env python """booleanRules.py: Infers network from pseudotime and binary expression. To run type python booleanRules.py gene expressionFile step orderFile maxAct maxRep networkFile threshold thresholdStep gene: name of gene e.g. Gata1. This should match gene names in expression and network files. expressionF...
python
"""Ekea for EAM model""" import os, subprocess, json, shutil from ekea.e3smapp import E3SMApp, here from ekea.utils import xmlquery # EAM app class EAMKernel(E3SMApp): _name_ = "eam" _version_ = "0.1.0" # main entry def perform(self, args): self.generate(args, "exclude_e3sm_eam.ini")
python
import os import sys from pathlib import Path from data_pipeline.config import settings from data_pipeline.utils import ( download_file_from_url, get_module_logger, ) logger = get_module_logger(__name__) def check_score_data_source( score_csv_data_path: Path, score_data_source: str, ) -> None: "...
python
""" This file contains the implementation of the class GameObject. Author: Alejandro Mujica (aledrums@gmail.com) Date: 07/22/20 """ from src.mixins import DrawableMixin, CollisionMixin class GameObject(DrawableMixin, CollisionMixin): # Object sides TOP = 'top' RIGHT = 'right' BOTTOM = 'bottom' LE...
python
#!/usr/bin/env python2 # Fill in checksum/size of an option rom, and pad it to proper length. # # Copyright (C) 2009 Kevin O'Connor <kevin@koconnor.net> # # This file may be distributed under the terms of the GNU GPLv3 license. import sys def alignpos(pos, alignbytes): mask = alignbytes - 1 return (pos + mas...
python
# We start by importing all the modules we will need, as well as the helper document with all our functions import argparse import torch import numpy as np from torch import nn from torch import optim import torch.nn.functional as F import os from torchvision import datasets, transforms, models from collections import ...
python
from django.contrib import admin from django.urls import path, include from django.contrib.sitemaps.views import sitemap from website.sitemaps import PostSitemap sitemaps = { 'posts': PostSitemap } urlpatterns = [ path('mkubwa/', admin.site.urls), path('accounts/', include('accounts.urls', namespace='acco...
python
import multiprocessing import time from multiprocessing.connection import Listener, Client from typing import Dict, Any, List import tqdm from autopandas_v2.ml.inference.interfaces import RelGraphInterface class ModelStore: def __init__(self, path_map: Dict[Any, str]): self.path_map = path_map s...
python
# -*- coding: utf-8 -*- """This module populates the tables of bio2bel_reactome.""" import logging from collections import defaultdict from typing import Dict, List, Mapping, Optional, Set import pandas as pd from tqdm import tqdm from bio2bel.compath import CompathManager from pyobo import get_name_id_mapping from...
python
from collections import namedtuple from sqlalchemy.orm.exc import NoResultFound from parks.models import DBSession from parks.models import Park from parks.models import StampCollection from parks.models import User from parks.models import UserEmail def get_user_by_id(user_id): return DBSession.query( U...
python
from tkinter import * from tkinter.ttk import * from cep_price_console.cntr_upload.CntrUploadTab import CntrUploadTab from cep_price_console.utils.log_utils import CustomAdapter, debug from cep_price_console.cntr_upload.Treeview import TreeviewConstructor, TreeColumn, TreeRow import logging class Step5ReviewUpload(Cn...
python
# start_chrome -> input_date -> scroll_down-> find_cards_info -> save -> find_next (goto) from selenium import webdriver from selenium.webdriver.common.keys import Keys import time import csv import os def start_chrome(): driver = webdriver.Chrome(executable_path='./chromedriver.exe') driver.start_client() ...
python
import client import get_plant import time import RPi.GPIO as GPIO import picamera import math import numpy as np import argparse import cv2 import json import MPU9250 # GPIO setup GPIO.setmode(GPIO.BCM) GPIO.setup(17, GPIO.OUT) GPIO.setup(25, GPIO.OUT) servo=GPIO.PWM(17, 100) # Connect to the server and take possess...
python
from marshmallow_sqlalchemy import SQLAlchemyAutoSchema from variance.models.muscle import MuscleModel, MuscleGroupModel class MuscleSchema(SQLAlchemyAutoSchema): class Meta: model = MuscleModel load_instance = False class MuscleGroupSchema(SQLAlchemyAutoSchema): class Meta: model = ...
python
from django.contrib import admin from .models import PageCheckResult @admin.register(PageCheckResult) class PageCheckResultAdmin(admin.ModelAdmin): list_display = ('buschenschank', 'created', 'tag_name', 'website', 'return_code') list_filter = ('created', 'return_code', 'tag_name') se...
python
from player import Player class Human(Player): def __init__(self, symbol: str, name: str = "You"): super().__init__(name, symbol) def move(self, state: list[str]): print(f"{self.name} is to move!") while True: inp = input("Enter an integer between 1 and 9 representing an e...
python
import mnist_loader import network2 from task_gen import TaskGen import numpy as np training_data2, validation_data2, test_data2 = mnist_loader.load_data_wrapper() task_gen = TaskGen() training_data = task_gen.generate(1000) validation_data = task_gen.generate(1000, False) ''' print training_data2[0][1] print training...
python
# -*- coding: utf-8 -*- import hashlib import unicodedata from collections import Counter, defaultdict from six import text_type from hayes.analysis import builtin_simple_analyzer from hayes.ext.stopwords import ( english_stopwords, finnish_stopwords, russian_stopwords, swedish_stopwords, unicode_punctuation_...
python
from app import db from datetime import datetime from werkzeug.security import generate_password_hash,check_password_hash from flask_login import UserMixin from app import login class User(UserMixin,db.Model): id=db.Column(db.Integer,primary_key=True) username = db.Column(db.String(64),index=True,unique=True...
python
from dataclasses import dataclass from typing import Sequence from .phrase import Phrase from .translation_sources import TranslationSources from .word_alignment_matrix import WordAlignmentMatrix @dataclass(frozen=True) class TranslationResult: source_segment: Sequence[str] target_segment: Sequence[str] ...
python
#!/usr/bin/env python from collections import defaultdict # 000000000111111111122222222222333333333344444444 # 123456789012345678901234567890123456789012345678 # Step G must be finished before step X can begin. def parse_line(input_line): return input_line[5], input_line[36] def parse_input(content): retur...
python
from lxml.builder import E from sciencebeam_lab.lxml_to_svg import ( iter_svg_pages_for_lxml, SVG_TEXT, SVG_G, SVG_DOC ) SOME_TEXT = "some text" SOME_X = "10" SOME_Y = "20" SOME_BASE = "25" SOME_HEIGHT = "30" SOME_FONT_SIZE = "40" SOME_FONT_FAMILY = "Fontastic" SOME_FONT_COLOR = '#123' class LXML(object): ...
python
# coding: utf8 from __future__ import print_function import os, sys, re from xml.dom import minidom class HamshahriReader(): """ interfaces [Hamshahri Corpus](http://ece.ut.ac.ir/dbrg/hamshahri/files/HAM2/Corpus.zip) that you must download and extract it. >>> hamshahri = HamshahriReader(root='corpora/hamshahri')...
python
# -*- coding: utf-8 -*- # # michael a.g. aïvázis # orthologue # (c) 1998-2019 all rights reserved # # class declaration class Mapping: """ Mix-in class that forms the basis of the representation of mappings Mappings are dictionaries with arbitrary keys whose values are nodes """ # types fro...
python
import streamlit as st st.title('titulo') st.button('cl') st.sidebar.radio('radio',[1,2,3]) for i in range(10): st.write('holla')
python
#!python from __future__ import print_function import time from arduino_device import findArduinoDevicePorts from arduino_olfactometer import ArduinoOlfactometers from arduino_olfactometer import isOlfactometerPortInfo from faa_actuation import PwmController from faa_actuation import CurrentController from faa_actuati...
python