text stringlengths 2 999k |
|---|
import numpy as np
import shutil, sys, os, pickle
sys.path.append("..")
from SwitchVAE import *
from utils import save_volume, data_IO, arg_parser, model
from utils import model
from tensorflow.keras.models import Model
from tensorflow.keras.layers import Input
from sklearn.utils import shuffle
import time
os.envir... |
from manim_imports_ext import *
import scipy.integrate
OUTPUT_DIRECTORY = "bayes/part1"
HYPOTHESIS_COLOR = YELLOW
NOT_HYPOTHESIS_COLOR = GREY
EVIDENCE_COLOR1 = BLUE_C
EVIDENCE_COLOR2 = BLUE_E
NOT_EVIDENCE_COLOR1 = GREY
NOT_EVIDENCE_COLOR2 = GREY_D
#
def get_bayes_formula(expand_denominator=False):
t2c = {
... |
"""Calculate student grades by combining data from many sources.
Using Pandas, this script combines data from the:
* Roster
* Homework & Exam grades
* Quiz grades
to calculate final grades for a class.
"""
from pathlib import Path
import pandas as pd
import numpy as np
HERE = Path(__file__).parent
DATA_FOLDER = HER... |
from django.forms import ModelForm
from django.contrib.auth.models import User
from django import forms
#from django.contrib.admin.widgets import AdminDateWidget
class usernameForm(forms.Form):
username=forms.CharField(max_length=30)
class DateForm(forms.Form):
date=forms.DateField(widget = forms.SelectDateWidget... |
# -----------------------------------------------------------------------------------------------------------------
# format_strings
# this code will help you to print variables in text so easy
# اهلاً هذا السطر كذا و السطر التالى كذا و السطر السابق كذا
# -------------------------------------------------Version 1------... |
# -*- coding: utf-8 -*-
"""
@description: ;列表推导式
@author:XuMing
"""
from __future__ import print_function
from __future__ import unicode_literals
import time
# 循环可以用来生成列表:
values = [2, 2, 3]
squares = []
for x in values:
squares.append(x ** 2)
print(squares) # [4, 4, 9]
# 列表推导式可以使用更简单的方法来创建这个列表:
values = [3, 8,... |
# !/usr/bin/python3
# -*- coding:utf-8 -*-
# Author:WeiFeng Liu
# @Time: 2021/11/9 下午4:57
import torchvision
import torch.nn as nn
class my_densenet(nn.Module):
def __init__(self):
super(my_densenet, self).__init__()
self.backbone = torchvision.models.densenet121(pretrained=False)
self.f... |
import numpy, pylab, matplotlib
import random, os, bisect, re
class Variables(object):
"""variables specifying the particulars of the trace and the preferences of the user."""
def __init__(self, F, dt,
x=None, #stimulus (zeros vector of length T that has 1s in the frames that have high spi... |
import math
from multiprocessing import Process, Queue
import os
import os.path
import re
import sys
import time
try:
# Python 3
from queue import Empty as EmptyQueueException
from queue import Full as FullQueueException
except ImportError:
# Python 2
from Queue import Empty as EmptyQueueException
... |
#!/usr/bin/env python3
from cereal import car
from common.conversions import Conversions as CV
from selfdrive.car.toyota.tunes import LatTunes, LongTunes, set_long_tune, set_lat_tune
from selfdrive.car.toyota.values import Ecu, CAR, ToyotaFlags, TSS2_CAR, NO_DSU_CAR, MIN_ACC_SPEED, EPS_SCALE, EV_HYBRID_CAR, CarControll... |
# -*- coding: utf-8 -*-
"""
Created on Sun Nov 5 00:30:18 2017
"""
@author: DELL1
#intial model training code
import multiprocessing
#from gensim.corpora.wikicorpus import WikiCorpus
from gensim.models.word2vec import Word2Vec
#from gensim.models import TfidfModel
#from gensim.models.word2vec import LineSentence
imp... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.2 on 2017-07-17 13:31
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('alerts', '0006_remove_muzzle_hash_null'),
]
operations = [
migrations.RenameField(
... |
"""LogDict class with JSON log storage format and simple versioning."""
import json, os
from collections.abc import MutableMapping
from typing import Any, Tuple
class LogDict(MutableMapping):
"""Map-like object with append-only-file logging for persistence.
All set and delete operations are written to append... |
from ...utilities import db, moocdb_utils
from common import *
def GetContentSections(vars):
resource_type_id = moocdb_utils.GetResourceTypeMap(vars)['content_section']
src_sections = [x for x in vars["resource_list"] if x["_id"]["category"] == 'chapter']
section_index = 1
output_items = []
... |
class Node():
def __init__(self, val):
self.val = val
self.left = None
self.right = None
def insert(root, val):
new_node = Node(val)
parent = None
curr = root
while curr:
parent = curr
if curr.val <= val:
curr = curr.right
else:
... |
def f():
try:
call()
try:
nested()
except Exception:
return 1
except:
return 2
try:
call2()
except Exception:
return 2
try:
call3a()
finally:
call3b() |
import os
import structlog
if os.getenv("LOG_RENDER_JSON"):
renderer = structlog.processors.JSONRenderer()
else:
try:
import colorama # noqa
renderer = structlog.dev.ConsoleRenderer()
except ImportError:
renderer = structlog.dev.ConsoleRenderer(colors=False)
structlog.configure(... |
"""
Weak optimal ransport solvers
"""
# Author: Remi Flamary <remi.flamary@polytehnique.edu>
#
# License: MIT License
from .backend import get_backend
from .optim import cg
import numpy as np
__all__ = ['weak_optimal_transport']
def weak_optimal_transport(Xa, Xb, a=None, b=None, verbose=False, log=False, G0=None, ... |
# Generated by Django 3.0 on 2020-01-05 15:01
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Author',
fields=[
... |
import logging
from thespian.actors import *
from thespian.system.utilis import (thesplog, checkActorCapabilities,
foldl, join, fmap, AssocList,
actualActorClass)
from thespian.system.timing import ExpirationTimer, currentTime
from thespian.system.... |
###Titulo: Leitor de string
###Função: Este programa lê duas string e gera uma terceira com caracteres da primeira
###Autor: Valmor Mantelli Jr.
###Data: 08/01/2019
###Versão: 0.0.1
# Declaração de variáveis
f = ""
s = ""
t = ""
x = 0
#Entrada de dados
f = input("Digite a primeira sequência de letras: ")
s = ... |
#!/bin/bash
# This script has moved.
management/cli.py "$@"
|
import typing as T
from enum import Enum
from pydantic import BaseModel
from ..entities import Friend, Member, Anonymous, File, OfflineFile, Device
from ..misc import CQParser
parser = CQParser()
class MessageItemType(Enum):
FriendMessage = "FriendMessage"
GroupMessage = "GroupMessage"
BotMessage = "Bot... |
#!/usr/bin/env python
#
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#
# Michael A.G. Aivazis
# California Institute of Technology
# (C) 1998-2003 All Rights Reserved
#
# <LicenseText>
#
# ~~~~~~~~~~~~~~... |
""" Implementation of Inverse Reinforcement Learning algorithm for Time series"""
import torch
class MultiModelIRL(torch.nn.Module):
def __init__(self, *model_hyperparameters, **kwargs):
super(MultiModelIRL, self).__init__()
for dictionary in model_hyperparameters:
for key in dictiona... |
# -*-coding: utf-8 -*-
def array_slip(start, end, clip_length):
"""
将步长为1的数轴按照 clip_length 的长度切分为 n 个段,返回 N个左闭右开区间[x, y),
最后一个片段的右边界为 end + 1。所以,最好当做 左闭右开区间处理使用,[x, y)。
----------------------------------[ DEMO ]----------------------------------
def demo():
# ls = [1, 2, 3, 4, 5, 6, 7, 8, 9, ... |
from abc import abstractmethod, ABC
from domain.failure_monitor import ControllerFailureMonitor
from utils.constants import UserAction
class IGeneiApp(ABC):
@abstractmethod
def run(self, **config):
pass
class GeneiAppSelenium(IGeneiApp):
def __init__(self, controller):
self.controller ... |
from flask import Flask, render_template, send_file, url_for
app = Flask(__name__)
@app.route('/', methods=['GET', 'POST'])
def main():
return render_template("items.html")
@app.route('/download')
def download():
return send_file('dummy.pdf')
|
# Copyright 2011 OpenStack Foundation
# 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 requ... |
from app.clients import (Client, ClientException)
class SmsClientResponseException(ClientException):
'''
Base Exception for SmsClientsResponses
'''
def __init__(self, message):
self.message = message
def __str__(self):
return "Message {}".format(self.message)
class SmsClient(Cl... |
# Copyright (c) The PyAMF Project.
# See LICENSE.txt for details.
"""
Tests pyamf.util.imports
@since: 0.3.1
"""
import unittest
import sys
import os.path
from pyamf.util import imports
class InstalledTestCase(unittest.TestCase):
"""
Tests to ensure that L{imports.finder} is installed in L{sys.meta_path}
... |
import argparse
import cv2
import numpy as np
import sys
import mxnet as mx
import datetime
from skimage import transform as trans
import sklearn
from sklearn import preprocessing
class Embedding:
def __init__(self, prefix, epoch, ctx_ids=None):
if ctx_ids is None:
ctx_ids = [0]
print('loading',prefix,... |
# -*- coding: UTF-8 -*-
from math import e
import os
from typing import final
from numpy.lib.type_check import _imag_dispatcher
import pandas as pd
import shutil
import numpy as np
import cv2
import random
from tqdm import tqdm
import pyfastcopy
import json,sklearn
from sklearn.model_selection import train_test_split
... |
def createMatrix() :
print('***TO CREATE MATRIX***')
rows = int(input('Enter number of rows: '))
cols = int(input('Enter number of columns: '))
matrix = []
for i in range(rows) :
a = []
for j in range(cols) :
a.append(int(input()))
matrix.append(a)
return matrix
matrix1 = createMatrix()
print('mat... |
'''Michael Lange <klappnase (at) freakmail (dot) de>
The ToolTip class provides a flexible tooltip widget for Tkinter; it is based on IDLE's ToolTip
module which unfortunately seems to be broken (at least the version I saw).
INITIALIZATION OPTIONS:
anchor : where the text should be positioned inside the widget, ... |
class Solution:
def subtractProductAndSum(self, n: int) -> int:
p = 1
s = 0
while n :
d = n%10
p *= d
s += d
n = n //10
return p - s
|
import argparse
import tensorflow as tf
import numpy as np
import os
from dispnet import DispNet
from util import get_var_to_restore_list
from matplotlib import pyplot as plt
import cv2
# INPUT_SIZE = (384, 768, 3)
# INPUT_SIZE = (540, 960, 3)
DOWNGRADE_FACTOR = 64
def pad_image(immy,down_factor = DOWNGRADE_FACTOR):
... |
#!/usr/bin/env python
import os
import vtk
def main():
colors = vtk.vtkNamedColors()
fileNames, useRibbons = get_program_parameters()
useTubes = not useRibbons
# Set up the stocks
renderers = list()
topRenderer = vtk.vtkRenderer()
bottomRenderer = vtk.vtkRenderer()
renderers.appen... |
import io
import pathlib
import uuid
import numpy as np
import skimage.io
import skimage.color
import skimage.filters
import skimage.metrics
import skimage.morphology
import skimage.segmentation
import skimage.transform
from PIL import Image as PILImage
from sklearn.cluster import KMeans
class Image:
small_ra... |
#!/usr/bin/env python
import base_filters
COPY_GOOGLE_DOC_KEY = '1PoDrRRPufsx5vayiNE8J6Ya0GuzKZma5YHfCBRRGED4'
USE_ASSETS = False
# Use these variables to override the default cache timeouts for this graphic
# DEFAULT_MAX_AGE = 20
# ASSETS_MAX_AGE = 300
JINJA_FILTER_FUNCTIONS = base_filters.FILTERS
|
# Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
class SeedGenerator:
def __init__(self, seed):
self.seed = seed
self.counters = dict()
def next(self, key='default'):
if self.seed == None:
return None
if... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
import logging
import pymongo
import string
import random
from django.core.cache import cache
from contextlib import contextmanager
from dbaas_credentials.models import CredentialType
from . import BaseDriver
from . import DatabaseInfraSta... |
import telegram
from . import start
from . import add_feed
from . import remove_feed
def register_commands(dispatcher: telegram.ext.Dispatcher):
def add_all(handlers):
for handler in handlers:
dispatcher.add_handler(handler)
add_all(start.get_handlers())
add_all(add_feed.get_handlers())
add_all(remove_fee... |
from django.shortcuts import render
def faq(request):
return render(request, 'faq/faq.html') |
from django import forms
from mayan.apps.views.forms import DetailForm
from .models import Theme, UserThemeSetting
class ThemeForm(forms.ModelForm):
class Meta:
fields = ('label', 'logo','stylesheet','navbarcolor','menucolor')
model = Theme
class UserThemeSettingForm(forms.ModelForm):
clas... |
#MenuTitle: Add Extremes to Selection
# -*- coding: utf-8 -*-
from __future__ import division, print_function, unicode_literals
__doc__="""
Adds extreme points to selected paths.
"""
thisFont = Glyphs.font
thisLayer = thisFont.selectedLayers[0]
for path in thisLayer.paths:
if path.selected:
path.addNodesAtExtremes... |
from .. utils import TranspileTestCase, BuiltinFunctionTestCase
class BytearrayTests(TranspileTestCase):
pass
class BuiltinBytearrayFunctionTests(BuiltinFunctionTestCase, TranspileTestCase):
function = "bytearray"
is_flakey = [
'test_set',
'test_frozenset',
]
|
"""
Django settings for diehard project.
Generated by 'django-admin startproject' using Django 3.0.3.
For more information on this file, see
https://docs.djangoproject.com/en/3.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.0/ref/settings/
"""
import os
im... |
# -*- coding: utf-8 -*-
# @Time : 2018/1/9 15:09
# @Author : HLin
# @Email : linhua2017@ia.ac.cn
# @File : __init__.py.py
# @Software: PyCharm |
load(
"@io_bazel_rules_scala//scala/private:rule_impls.bzl",
_scala_library_impl = "scala_library_impl",
_scala_library_for_plugin_bootstrapping_impl =
"scala_library_for_plugin_bootstrapping_impl",
_scala_macro_library_impl = "scala_macro_library_impl",
_scala_binary_impl = "scala_binary_impl",... |
#!/usr/bin/env python
#
# this script generate supervisord configs for running a test network on loopback
#
from argparse import ArgumentParser as AP
from configparser import ConfigParser as CP
import os
def svcNodeName(id): return 'svc-node-%03d' % id
def clientNodeName(id): return 'client-node-%03d' % id
def... |
""" Split BatchNorm
A PyTorch BatchNorm layer that splits input batch into N equal parts and passes each through
a separate BN layer. The first split is passed through the parent BN layers with weight/bias
keys the same as the original BN. All other splits pass through BN sub-layers under the '.aux_bn'
namespace.
Thi... |
from setuptools import setup
setup(
name = 'search_kwic',
packages = ['search_kwic'],
version = '0.2',
description = 'Tool for KWIC representation of paralleltext. Find a word in the parallel text corresponding to query in the original text.',
author = 'Maria Terekhina',
author_email = 'maria.myslina@gmail... |
from signal import pause
from bluedot import BlueDot
bd = BlueDot()
def double_pressed():
print("double pressed")
bd.when_double_pressed = double_pressed
pause() |
# Generated by Django 2.0.8 on 2018-08-22 14:03
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('partners', '0001_initial'),
('chatty_users', '0001_initial'),
]
operations = [
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (c) 2016 Red Hat, Inc.
#
# This file is part of Ansible
#
# Ansible 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 3 of the License, ... |
import pdf_to_json as p2j
import json
url = "file:data/multilingual/Latn.KTU/Sans_12/udhr_Latn.KTU_Sans_12.pdf"
lConverter = p2j.pdf_to_json.pdf_to_json_converter()
lConverter.mImageHashOnly = True
lDict = lConverter.convert(url)
print(json.dumps(lDict, indent=4, ensure_ascii=False, sort_keys=True))
|
# -*- coding: utf-8 -*-
"""
Created on Mon Dec 7 17:38:20 2020
@author: Admin
This is to generate the illustration of stimulations
"""
import matplotlib.pyplot as plt
import numpy as np
import MotionClouds as mc
import matplotlib
matplotlib.rcParams['pdf.fonttype'] = 42
matplotlib.rcParams['ps.fonttype'] = 42
B_t... |
from click.testing import CliRunner
import pytest
from pgbedrock import cli
from conftest import Q_GET_ROLE_ATTRIBUTE, NEW_USER
@pytest.mark.usefixtures('drop_users_and_objects')
def test_configure_defaults_to_check_mode(cursor, tiny_spec, db_config):
# Assert that we start without the role we are trying to add
... |
# ---------------------------------------------------------
# IOU Tracker
# Copyright (c) 2017 TU Berlin, Communication Systems Group
# Licensed under The MIT License [see LICENSE for details]
# Written by Erik Bochinski
# ---------------------------------------------------------
import numpy as np
import csv
def lo... |
###############################################################################
#
# Tests for XlsxWriter.
#
# Copyright (c), 2013-2015, John McNamara, jmcnamara@cpan.org
#
import unittest
from ...compatibility import StringIO
from ...styles import Styles
class TestWriteStyleXf(unittest.TestCase):
"""
Test th... |
try:
a=3
if a<4:
b=a/(a-3)
print(b)
except(ZeroDivisionError):
print("dividing num by 0: " )
|
#!/opt/anaconda3/bin/python3
""" Class definitions and a main routine to simulate traffic """
import os
import subprocess
import glob
import numpy as np
import matplotlib.pyplot as plt
class Car:
""" A class for modeling cars in traffic """
def __init__(self, aggression=1.0, ahead=None):
""" Construc... |
"""
Copyright (c) 2017 Red Hat, Inc
All rights reserved.
This software may be modified and distributed under the terms
of the BSD license. See the LICENSE file for details.
"""
from __future__ import unicode_literals, absolute_import
import fnmatch
import hashlib
import koji
import os
from atomic_reactor import util... |
# Copyright 2020 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from setuptools import setup, find_packages
version = '0.1.0'
setup(
author="seekplum",
author_email='1131909224m@sina.cn',
classifiers=[
'Programming Language :: Python :: 2.7',
],
description="leetcode",
install_requires=[
],
scr... |
import json
from lib import node
from lib.generator import predicate_function
from lib.generator import predicate_function_declaration
with open("json/adlam.json", "r") as stream:
data = json.load(stream)
nd = node.RootNode()
for dat in data:
nd.extend(dat, True)
with open("dist/is_adlam_unicos.h", "w") as st... |
from typing import List, Optional, Union
import numpy as np
from scvi import REGISTRY_KEYS
from scvi.data import AnnDataManager
from scvi.data._utils import get_anndata_attribute
from ._concat_dataloader import ConcatDataLoader
class SemiSupervisedDataLoader(ConcatDataLoader):
"""
DataLoader that supports ... |
# Escreve todos os números pares de 1 a 50.
#print('Números pares de 1 a 50.')
#for i in range(1,51,1):
# if i % 2 ==0: # Se for par, o resto da dívisão com 2 é igual a 0.
# print(i, end=' ')
print('Números pares de 1 a 50.')
for i in range(2, 51, 2):
print(i, end=' ')
# end-for
|
# coding: utf-8
"""
Url2Src APIs
Url to Image src urls.<BR />[Endpoint] https://api.apitore.com/api/15 # noqa: E501
OpenAPI spec version: 0.0.1
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_import
import unittest
import swagger_client
f... |
import math
import os
import sys
import tempfile
from datetime import date, datetime, time, timedelta
from decimal import Decimal
from enum import Enum, IntEnum
from ipaddress import IPv4Address, IPv4Interface, IPv4Network, IPv6Address, IPv6Interface, IPv6Network
from pathlib import Path
from typing import (
Any,
... |
"""
Wolfram|Alpha Adapter is an adapter which is used to
fetch results from the Wolfram ALpha server
MARKS LICENSE AND ATTRIBUTION"Wolfram|Alpha Marks" means the trade names, trademarks,
service marks, logos, domain names and other distinctive marks of
Wolfram|Alpha. Wolfram|Alpha grants You a non-exclusive license to... |
def findDecision(obj): #obj[0]: Passanger, obj[1]: Weather, obj[2]: Time, obj[3]: Coupon, obj[4]: Coupon_validity, obj[5]: Gender, obj[6]: Age, obj[7]: Maritalstatus, obj[8]: Children, obj[9]: Education, obj[10]: Occupation, obj[11]: Income, obj[12]: Bar, obj[13]: Coffeehouse, obj[14]: Restaurant20to50, obj[15]: Direct... |
import os
from pyspedas.utilities.dailynames import dailynames
from pyspedas.utilities.download import download
from pyspedas.analysis.time_clip import time_clip as tclip
from pytplot import cdf_to_tplot
from .config import CONFIG
def load(trange=['2013-11-5', '2013-11-6'],
instrument='mgf',
dataty... |
"""
Every email consists of a local name and a domain name, separated by the @ sign.
For example, in alice@leetcode.com, alice is the local name, and leetcode.com is the domain name.
Besides lowercase letters, these emails may contain '.'s or '+'s.
If you add periods ('.') between some characters in the local name ... |
from card import Card
class Deck:
def __init__(self):
"""
Encapsulates a list of Card objects
:return: None
"""
self.cards = []
# initialize deck
suits = ['Clubs', 'Diamonds', 'Hearts','Spades']
ranks = ['Ace','2','3','4','5','6','7','8','9',... |
"""XKCD Search
Syntax: .xkcd <search>"""
from telethon import events
import asyncio
import json
import requests
from urllib.parse import quote
from userbot.utils import admin_cmd
@borg.on(admin_cmd(pattern="xkcd ?(.*)"))
async def _(event):
if event.fwd_from:
return
input_str = event.pattern_match.gro... |
"""AyudaEnPython: https://www.facebook.com/groups/ayudapython
# ------------------------ Enunciado Original -------------------------
Pedir al usuario la cantidad de números de la secuencia de Fibonacci
que desea ver.
Por ejemplo si el usuario digita 10, deberá mostrarse en pantalla la
secuencia:
1, 1, 2, 3, 5, 8, 13... |
import ev3dev.ev3 as ev3
class Sounds:
def __init__(self):
self.sounds = ev3.Sound
def say_red(self):
self.sounds.speak("red").wait()
def say_blue(self):
self.sounds.speak("blue").wait()
def say_white(self):
self.sounds.speak("white").wait()
def say_black(self)... |
# coding: utf-8
"""
Kubernetes
No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
OpenAPI spec version: v1.12.1
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_import
import os
import sys
i... |
from PyQt4 import QtCore, QtGui
class MessageCompose(QtGui.QTextEdit):
def __init__(self, parent = 0):
super(MessageCompose, self).__init__(parent)
self.setAcceptRichText(False) # we'll deal with this later when we have a new message format
self.defaultFontPointSize = self.currentFont(... |
# flake8: noqa
from .utils import json_encoder_default
from collections import defaultdict
from future.builtins import zip
import json
import logging
log = logging.getLogger(__name__)
def decode(value):
if isinstance(value, DatastoreList):
return value
elif isinstance(value, DatastoreDict):
... |
import requests
dbc_username = "username here" # deathbycaptcha username
dbc_password = "password here" # deathbycaptcha password
target_site_link = "https://link to the login/form that contains captcha"
def submitCaptcha(site_key):
link = "http://api.dbcapi.me/api/captcha"
headers = {
'Expect': '',... |
#from org.openrdf.model import *
#from org.openrdf.query import *
#from org.openrdf.repository import *
#from org.openrdf.rio import *
#from org.openrdf.repository.sail import *
#from org.openrdf.repository.manager import RemoteRepositoryManager
#from org.openrdf.query.resultio import *
##from org.openrdf.repository.sa... |
# Copyright Amazon.com, Inc. or its affiliates. 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. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file accompan... |
import sys
sys.path.append("../")
from settings import (NES_PALETTE_HEX, animation_settings)
from core import sprite
ArthurArmoredRunRight01 = sprite(
palette = {
"b":NES_PALETTE_HEX[0, 13],
"w":NES_PALETTE_HEX[3, 0],
"r":NES_PALETTE_HEX[0, 6],
"o":NES_PALETTE_HEX[1, 8],
"s"... |
import torch
from d2l import torch as d2l
if __name__ == "__main__":
x = torch.arange(-8.0, 8.0, 0.1, requires_grad=True)
sigmoid = 2 * torch.sigmoid(2 * x)
tanh = torch.tanh(x) + 1
d2l.plot(x.detach(), tanh.detach(), "x", "tanh(x) + 1", figsize=(5, 2.5))
d2l.plot(
x.detach(), sigmoid.detac... |
# Copyright 2017 The TensorFlow 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 applicab... |
# Linear Regression: L1 vs L2
#----------------------------------
#
# This function shows how to use TensorFlow to
# solve linear regression via the matrix inverse.
import matplotlib.pyplot as plt
import numpy as np
import tensorflow as tf
from sklearn import datasets
from tensorflow.python.framework import ops
ops.re... |
from fusearch.index import Index
from fusearch.tokenizer import Tokenizer, tokfreq
from pony.orm import *
from fusearch.model import Document
from nose.tools import *
from fusearch.util import compose
class NaiveTokenizer(Tokenizer):
def tokenize(self, x):
return x.split()
def test_query():
index = ... |
import os
no_images = 600
noise_epsilons = [0.5, 1.0]
os.system(f'ipython AdversarialImageNet.py -- --command measure_accuracy --no_images 50000')
#os.system(f'ipython AdversarialImageNet.py -- --command generate_conventional_from_validation --no_images {no_images}')
#os.system(f'ipython AdversarialImageNet.py -- --c... |
from django.forms import ModelForm
from django.contrib.auth.forms import UserCreationForm
from django import forms
from django.contrib.auth.models import User
from .models import *
class naive_userForm(ModelForm):
class Meta:
model = naive_user
fields = '__all__'
class createuserform(UserCreationForm):
class M... |
# -*- coding: utf-8 -*-
"""
flask_caching.backends.simple
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
The simple cache backend.
:copyright: (c) 2018 by Peter Justin.
:copyright: (c) 2010 by Thadeus Burgess.
:license: BSD, see LICENSE for more details.
"""
import logging
from time import time
from flask_cac... |
import scdrs
import os
import subprocess
import pandas as pd
import numpy as np
import tempfile
from .test_method_score_cell_main import compare_score_file
def test_score_cell_cli():
"""
Test CLI `scdrs compute-score`
"""
# Load toy data
ROOT_DIR = scdrs.__path__[0]
H5AD_FILE = os.path.join(RO... |
"""
The MIT License (MIT)
Copyright (c) 2020 James
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, publis... |
# code was heavily based on https://github.com/clovaai/stargan-v2
# Users should be careful about adopting these functions in any commercial matters.
# https://github.com/clovaai/stargan-v2#license
from paddle.fluid.layers.nn import soft_relu
from .base_model import BaseModel
from paddle import nn
import paddle
impor... |
#!/usr/bin/env python
from setuptools import setup, find_packages
import os
__doc__ = """
App for Django featuring improved form base classes.
"""
version = '1.2.1.dev0'
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name='django-betterforms',
version=versio... |
from kivy.metrics import dp
from kivy.uix.widget import Widget
from kivymd.uix.button import MDRaisedButton
from kivymd.uix.datatables import MDDataTable
from kivymd.uix.screen import MDScreen
class KitchenSinkDataTables(MDScreen):
def open_table(self, use_checkbox_state, use_pagination_state):
data_tabl... |
"""
Purpose: For use in the Reinforcement Learning course, Fall 2018,
University of Alberta.
Gambler's problem environment using RLGlue.
"""
from rl_glue import BaseEnvironment
import numpy as np
class Environment(BaseEnvironment):
def __init__(self):
"""Declare environment variables."""
def e... |
from azureml.pipeline.core import PipelineEndpoint
from azureml.core import Workspace
from azureml.core.authentication import ServicePrincipalAuthentication
from azureml.core.authentication import AzureCliAuthentication
import os
from azureml.core import Run
run = Run.get_context()
ws = run.experiment.workspace
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.