repo_name stringlengths 6 97 | path stringlengths 3 341 | text stringlengths 8 1.02M |
|---|---|---|
db434/nn-restrict | models/resnet.py | import torch.nn as nn
import math
import structured.fully_connected as fc
models = {"CIFAR-10": ["resnet20", "resnet32", "resnet44", "resnet56",
"resnet110"],
"ImageNet": ["resnet18", "resnet34", "resnet50", "resnet101",
"resnet152"]}
def conv3x3(in_planes, ou... |
db434/nn-restrict | modifiers/__init__.py | <reponame>db434/nn-restrict<filename>modifiers/__init__.py
from . import numbers
|
db434/nn-restrict | util/__init__.py | <gh_stars>0
__all__ = ["args", "checkpoint", "log", "stats"]
from . import args
from . import checkpoint
from . import log
from . import stats
|
db434/nn-restrict | models/squeezenet.py | <reponame>db434/nn-restrict<gh_stars>0
import torch
import torch.nn as nn
import torch.nn.init as init
import structured.fully_connected as fc
models = {"ImageNet": ["squeezenet1_0", "squeezenet1_1"]}
class Fire(nn.Module):
def __init__(self, inplanes, squeeze_planes,
expand1x1_planes, expand... |
db434/nn-restrict | training/lr_schedule.py | import abc
import math
# TODO: These classes are very similar (but perhaps more general) than those in
# torch.optim.lr_scheduler. Consider using those instead.
class LRSchedule(object):
"""Base class for all learning rate schedules. Not to be used directly."""
def __init__(self):
return
@abc.ab... |
db434/nn-restrict | models/mobilenet.py | <gh_stars>0
import torch.nn as nn
import structured.fully_connected as fc
models = {"ImageNet": "mobilenet"}
# Implementation based on https://github.com/marvis/pytorch-mobilenet
class MobileNet(nn.Module):
def __init__(self, input_channels=3, num_classes=1000, conv2d=fc.Conv2d,
args=None):
... |
db434/nn-restrict | tests/test_quantisers.py | from modifiers.numbers import *
def _check_equal(input_data, modifier, expected_result):
"""
Verify that modifier(input_tensor) == expected_result. Throws an assertion
error if not.
:param input_data: array of arbitrary dimensions.
:param modifier: function which takes a tensor and returns a tenso... |
db434/nn-restrict | datasets/ImageNet.py | import os
import torch.utils.data as data
import torchvision.datasets as datasets
import torchvision.transforms as transforms
import locations
# TODO subclass an abstract Dataset class.
class ImageNet(object):
_normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406],
s... |
db434/nn-restrict | graph.py | <reponame>db434/nn-restrict
import argparse
from collections import OrderedDict
import csv
import matplotlib.pyplot as plt
import structured
from util import log
def get_fields(csv_file, fields):
"""Return a dictionary mapping each name in `fields` to the sequence of
values seen for that field in the given f... |
db434/nn-restrict | models/alexnet.py | <filename>models/alexnet.py
import torch.nn as nn
import structured.fully_connected as fc
models = {"ImageNet": "alexnet"}
class AlexNet(nn.Module):
def __init__(self, input_channels=3, num_classes=1000, conv2d=fc.Conv2d,
args=None):
super(AlexNet, self).__init__()
self.width = ... |
db434/nn-restrict | training/distillation.py | <reponame>db434/nn-restrict
import os.path
import torch
import torch.nn.functional as F
import locations
import models
import structured
from util import checkpoint, log
from . import trainer
class Trainer(trainer.Trainer):
"""
Class which trains a model using an experienced teacher model.
"""
def _... |
db434/nn-restrict | cifar10.py | <filename>cifar10.py
import common
import datasets
def main():
dataset = datasets.Cifar10
common.process(dataset=dataset)
if __name__ == '__main__':
main()
|
db434/nn-restrict | util/log.py | import sys
def info(*args, **kwargs):
"""Report low-priority information. Has the same interface as `print`."""
print(*args, file=sys.stderr, **kwargs)
def error(*args, **kwargs):
"""Report high-priority information. Has the same interface as `print`."""
print(*args, file=sys.stderr, **kwargs)
|
db434/nn-restrict | modifiers/numbers.py | <filename>modifiers/numbers.py
"""
Module with various options for controlling number formats in the network.
"""
from collections.abc import Iterable
import torch.nn.functional
from .modules import *
def transform_gradients(model, transformation):
"""
Apply a transformation to all gradient computations in ... |
db434/nn-restrict | tests/test_shuffle.py | import random
import torch
from structured.shuffle import *
def _shuffle_test_run(in_data, groups, out_data):
"""Wrapper for a single shuffle."""
_, channels, _, _ = in_data.size()
shuffler = Conv2d(channels, channels, 1, groups=groups)
result = shuffler.shuffle(in_data, groups)
assert torch.eq... |
db434/nn-restrict | __init__.py | __all__ = ["models", "structured"]
|
db434/nn-restrict | structured/shift.py | import torch
import torch.nn as nn
import torch.nn.functional
from . import wrapped
from util import log
class Shift(nn.Module):
"""Shift all feature maps by a fixed amount in different directions. Feature
maps are split into a group for each kernel element and shifted so that the
kernel element ends up ... |
db434/nn-restrict | tests/test_hadamard.py | import random
from structured.hadamard import *
def _sublayer_test():
"""Test a single Hadamard sub-layer.
A single sub-layer doesn't do much. It:
* Splits data in two on the channel dimension
* Reorders one of these two segments (again on the channel dimension)
* Recombines the results
"... |
db434/nn-restrict | util/args.py | import argparse
import torch
import torch.distributed as dist
import models
import structured
def parse_args(dataset):
"""An argument parser with some behaviour common to all datasets."""
model_names = sorted(models.get_model_names(dataset=dataset))
conv_types = sorted(structured.conv2d_types.keys())
... |
n8henrie/cookiecutter-rust | cookiecutter_runner.py | from cookiecutter.main import cookiecutter
import datetime
import os.path
curdir = os.path.dirname(os.path.abspath(__file__))
today = datetime.datetime.today()
date = today.date().isoformat()
year = today.year
extra_context = {
'release_date': date,
'year': year
}
cookiecutter(curdir, extra_... |
alxpy/aiohttp-middlewares | aiohttp_middlewares/https.py | <reponame>alxpy/aiohttp-middlewares<filename>aiohttp_middlewares/https.py
"""
================
HTTPS Middleware
================
Change scheme for current request when aiohttp application deployed behind
reverse proxy with HTTPS enabled.
Usage
=====
.. code-block:: python
from aiohttp import web
from aiohtt... |
alxpy/aiohttp-middlewares | aiohttp_middlewares/cors.py | r"""
===============
CORS Middleware
===============
.. versionadded:: 0.2.0
Dealing with CORS headers for aiohttp applications.
**IMPORTANT:** There is a `aiohttp-cors
<https://pypi.org/project/aiohttp_cors/>`_ library, which handles CORS
headers by attaching additional handlers to aiohttp application for
OPTIONS (... |
alxpy/aiohttp-middlewares | aiohttp_middlewares/error.py | <reponame>alxpy/aiohttp-middlewares<filename>aiohttp_middlewares/error.py
r"""
================
Error Middleware
================
.. versionadded:: 0.2.0
Middleware to handle errors in aiohttp applications.
Usage
=====
.. code-block:: python
import re
from aiohttp import web
from aiohttp_middlewares i... |
alxpy/aiohttp-middlewares | tests/test_utils.py | <reponame>alxpy/aiohttp-middlewares
import re
import pytest
from aiohttp_middlewares import match_path
from aiohttp_middlewares.utils import match_request
URLS_COLLECTION = {
"/slow-url",
"/very-slow-url",
re.compile("/(very-very|very-very-very)-slow-url"),
}
URLS_DICT = {
"/slow-url": "POST",
"... |
alxpy/aiohttp-middlewares | aiohttp_middlewares/constants.py | <reponame>alxpy/aiohttp-middlewares
"""
=============================
aiohttp_middlewares.constants
=============================
Collection of constants for ``aiohttp_middlewares`` project.
"""
#: Tuple of idempotent HTTP methods
IDEMPOTENT_METHODS = ("GET", "HEAD", "OPTIONS", "TRACE")
#: Tuple of non-idempotent H... |
alxpy/aiohttp-middlewares | tests/test_error_middleware.py | <filename>tests/test_error_middleware.py<gh_stars>0
import re
import pytest
from aiohttp import web
from aiohttp_middlewares import error_context, error_middleware
class LegalException(Exception):
def __init__(self):
super().__init__("Not available for legal reasons")
self.status = 451
s... |
alxpy/aiohttp-middlewares | aiohttp_middlewares/utils.py | """
=========================
aiohttp_middlewares.utils
=========================
Various utility functions for ``aiohttp_middlewares`` library.
"""
from .annotations import Url, Urls
def match_path(item: Url, path: str) -> bool:
"""Check whether current path is equal to given URL str or regexp.
:param it... |
alxpy/aiohttp-middlewares | aiohttp_middlewares/annotations.py | """
===============================
aiohttp_middlewares.annotations
===============================
Type annotation shortcuts for ``aiohttp_middlewares`` library.
"""
from typing import Any, Dict, FrozenSet, List, Set, Tuple, Union
from typing.re import Pattern
DictStrAny = Dict[str, Any]
DictStrStr = Dict[str, st... |
alxpy/aiohttp-middlewares | tests/test_timeout_middleware.py | <reponame>alxpy/aiohttp-middlewares
import asyncio
import pytest
from aiohttp import web
from aiohttp_middlewares import timeout_middleware
HALF_A_SECOND = 0.5
SECOND = 1
def create_app(seconds, ignore=None):
app = web.Application(
middlewares=[timeout_middleware(seconds, ignore=ignore)]
)
app... |
alxpy/aiohttp-middlewares | tests/test_shield_middleware.py | import asyncio
import re
import pytest
from aiohttp import web
from aiohttp.test_utils import make_mocked_request
from aiohttp_middlewares import NON_IDEMPOTENT_METHODS, shield_middleware
def create_app(*, methods=None, urls=None, ignore=None):
app = web.Application(
middlewares=[
shield_mid... |
alxpy/aiohttp-middlewares | aiohttp_middlewares/timeout.py | """
==================
Timeout Middleware
==================
Middleware to ensure that request handling does not exceeds X seconds.
Usage
=====
.. code-block:: python
from aiohttp import web
from aiohttp_middlewares import error_middleware, timeout_middleware
# Basic usage
app = web.Application(
... |
alxpy/aiohttp-middlewares | tests/test_https_middleware.py | <filename>tests/test_https_middleware.py
import pytest
from aiohttp import web
from aiohttp_middlewares import https_middleware
def create_app(match_headers):
app = web.Application(middlewares=[https_middleware(match_headers)])
app.router.add_route("GET", "/", handler)
return app
async def handler(requ... |
lundgrenalex/mtrc | libs/tools/json.py | <filename>libs/tools/json.py<gh_stars>0
from functools import wraps
from flask import jsonify, request
from jsonschema import validate
from jsonschema.exceptions import ValidationError
from werkzeug.exceptions import BadRequest
from importlib import import_module
import logging
def validate_schema(schema_name: str):
... |
lundgrenalex/mtrc | libs/routes/exporter.py | import os
from flask import Blueprint, jsonify, request, Response
from libs.metric import exporter
import config
app = Blueprint('exporter', __name__, url_prefix='/metrics')
# Metrics page
@app.route('/', methods=['GET'])
def get_metrics():
return Response(exporter.get_metrics(), mimetype='text'), 200
@app.rou... |
lundgrenalex/mtrc | libs/tools/encoders.py | <gh_stars>0
import json
import datetime
import decimal
class FlaskEncoder(json.JSONEncoder):
'''Феншуйное преобразование обьектов в JSON'''
def default(self, obj):
if isinstance(obj, decimal.Decimal):
return str(obj)
elif isinstance(obj, datetime.datetime):
return obj.i... |
lundgrenalex/mtrc | libs/tools/utils.py | <reponame>lundgrenalex/mtrc<filename>libs/tools/utils.py<gh_stars>0
import os
def proj_path(project_root, *args):
'''Получить абсолютный путь к args в проекте'''
return os.path.realpath(os.path.join(project_root, *args))
|
lundgrenalex/mtrc | libs/metric/__init_.py | <gh_stars>0
from . import counter # noqa
from . import gauge # noqa
from . import average # noqa
|
lundgrenalex/mtrc | libs/routes/counter.py | <gh_stars>0
from flask import Blueprint, jsonify, request
from libs.tools.json import validate_schema
from libs.metric import counter
app = Blueprint('gateway-counter', __name__, url_prefix='/handler/counter')
@app.route('/', methods=['POST'])
@validate_schema('counter')
def get_counter():
result = counter.updat... |
lundgrenalex/mtrc | libs/storage/mongodb.py | <gh_stars>0
from pymongo import MongoClient
connection = None
def connect(conn_str='mongodb://mongodb:27017', pullSize=1024, **mongo_settings):
global connection
if not connection:
connection = MongoClient(
conn_str,
connect=False,
maxPoolSize=pullSize,
... |
lundgrenalex/mtrc | libs/routes/gauge.py | from flask import Blueprint, jsonify, request
from libs.tools.json import validate_schema
from libs.metric import gauge
app = Blueprint('gateway-gauge', __name__, url_prefix='/handler/gauge')
@app.route('/', methods=['POST'])
@validate_schema('gauge')
def get_gauge():
result = gauge.update(request.json)
retu... |
lundgrenalex/mtrc | application.py | <filename>application.py<gh_stars>0
import logging
from werkzeug.middleware.proxy_fix import ProxyFix
from libs.routes import create_app
import config
logging.basicConfig(
format='%(asctime)-15s %(levelname)-8s %(name)-1s: %(message)s',
level=logging.DEBUG,
filename='./logs/mrtc.log',
)
app = create_app... |
lundgrenalex/mtrc | libs/storage/redis.py | '''Connection pool with Redis'''
import redis
connections_pool = {}
def connect(**redis_settings):
'''Get Redis connection'''
conn_key = ';'.join(['{}:{}'.format(k, str(v)) for k, v in redis_settings.items()])
if conn_key not in connections_pool:
redis_settings = redis_settings.copy()
co... |
lundgrenalex/mtrc | libs/schemas/gauge.py | schema = {
"$schema": "http://json-schema.org/draft-04/schema#",
"title": "MetricItem",
"type": "object",
"properties": {
"name": {
"type": "string",
"pattern": "^[a-z_][a-z0-9_]*$",
},
"date": {"type": "integer"},
"value": {
"type": "n... |
lundgrenalex/mtrc | config.py | <reponame>lundgrenalex/mtrc<gh_stars>0
import logging
import logging.config
from werkzeug.security import generate_password_hash
import os
PROJECT_ROOT = os.path.realpath(os.path.dirname(__file__))
flask = {
'host': '127.0.0.1',
'port': '8087',
'debug': True,
'sentry_dsn': None,
}
# Overwrite confi... |
lundgrenalex/mtrc | libs/metric/average.py | from libs.storage import mongodb
import json
import time
def update(metric: dict) -> bool:
db = mongodb.connect()
current_time = int(time.time())
saved_metric = db.mtrc.metrics.find_one({
'type': 'average',
'name': metric['name'],
'labels': metric['labels'],
'average': me... |
lundgrenalex/mtrc | libs/routes/average.py | from flask import Blueprint, jsonify, request
from libs.tools.json import validate_schema
from libs.metric import average
app = Blueprint('gateway-average', __name__, url_prefix='/handler/average')
@app.route('/', methods=['POST'])
@validate_schema('average')
def get_average():
result = average.update(request.js... |
lundgrenalex/mtrc | tests/test_exporter/test_api.py | import json
import unittest
from application import app
class TestingExporter(unittest.TestCase):
def setUp(self):
self.app = app.test_client()
def test_exporter(self):
'''testing counter metric'''
response = self.app.get('/metrics', follow_redirects=True)
self.assertEqual(re... |
lundgrenalex/mtrc | libs/metric/exporter.py | <reponame>lundgrenalex/mtrc<filename>libs/metric/exporter.py
from libs.storage import mongodb
import json
'''
FORMAT: https://prometheus.io/docs/instrumenting/exposition_formats/#basic-info
metric_name [
"{" label_name "=" `"` label_value `"` { "," label_name "=" `"` label_value `"` } [ "," ] "}"
] value [ timestamp... |
lundgrenalex/mtrc | libs/routes/__init__.py | <reponame>lundgrenalex/mtrc
from flask import Flask, jsonify, g
from libs.tools.encoders import FlaskEncoder
import sentry_sdk
import config
from sentry_sdk.integrations.flask import FlaskIntegration
# incoming primitives
from .counter import app as counter_app
from .gauge import app as gauge_app
from .average import a... |
lundgrenalex/mtrc | tests/test_gauge/test_api.py | import json
import unittest
import requests
import time
from random import randrange
from application import app
class TestingGauge(unittest.TestCase):
def setUp(self):
self.app = app.test_client()
self.fixture = json.dumps({
"name": "example",
"labels":{
"... |
lundgrenalex/mtrc | libs/tools/statsd.py | import logging
def get_metric(metric_name: str, raw_metrics: str):
"""Grab selected metric from statsd list of metrcs"""
def __get_labels(raw_metrics):
# get labels: cut {, then }
try:
labels = {}
raw_labels = raw_metric.split('{')[-1:][0]
raw_labels = raw_... |
lundgrenalex/mtrc | libs/metric/counter.py | <reponame>lundgrenalex/mtrc<gh_stars>0
from libs.storage import mongodb
import time
def update(metric: dict) -> dict:
db = mongodb.connect()
current_time = int(time.time())
saved_metric = db.mtrc.metrics.find_one({
'type': 'counter',
'name': metric['name'],
'labels': metric['labe... |
gdebayancmu/espnet | espnet2/asr/frontend/wavelet_frontend.py | import copy
import os
from typing import Optional
from typing import Tuple
from typing import Union
from ssqueezepy import cwt
import humanfriendly
import numpy as np
import torch
from torch_complex.tensor import ComplexTensor
from typeguard import check_argument_types
from espnet.nets.pytorch_backend.frontends.fron... |
metricjar/atom-python | ironsource/atom/config.py | <reponame>metricjar/atom-python<gh_stars>0
# Atom Python SDK config file
SDK_VERSION = "1.5.4"
ATOM_ENDPOINT = "http://track.atom-data.io/"
# Tracker Config
BATCH_SIZE = 256
BATCH_SIZE_LIMIT = 2000
BATCH_BYTES_SIZE = 64 * 1024
BATCH_BYTES_SIZE_LIMIT = 512 * 1024
# Default flush interval in milliseconds
FLUSH_INTERVAL... |
metricjar/atom-python | ironsource/atom/ironsource_atom_tracker.py | import json
import signal
import Queue
from ironsource.atom.ironsource_atom import IronSourceAtom
from ironsource.atom.queue_event_storage import QueueEventStorage
from ironsource.atom.batch_event_pool import BatchEventPool
from ironsource.atom.event import Event
import ironsource.atom.atom_logger as logger
import iron... |
metricjar/atom-python | setup.py | <filename>setup.py
#!/usr/bin/env python
import sys
from setuptools import setup, find_packages
from pip.req import parse_requirements
from pip.download import PipSession
from ironsource import __version__
install_reqs = parse_requirements('requirements.txt', session=PipSession())
reqs = [str(ir.req) for ir in instal... |
metricjar/atom-python | ironsource/atom/event.py | class Event:
"""
Event object - Holds a single atom event (inside EventStorage)
:param stream: Atom stream name
:type stream: basestring
:param data: Payload data to send
:type data: object
"""
def __init__(self, stream, data):
self.stream = stream
s... |
metricjar/atom-python | ironsource_example/example.py | # -*- coding: utf-8 -*-
import json
import random
from ironsource.atom.ironsource_atom import IronSourceAtom
from ironsource.atom.ironsource_atom_tracker import IronSourceAtomTracker
import time
from threading import Thread
from threading import Lock
if __name__ == "__main__":
stream = "YOUR_TARGET.public.atom_d... |
metricjar/atom-python | ironsource/atom/batch_event_pool.py | <reponame>metricjar/atom-python<gh_stars>0
from threading import Thread
from Queue import Queue
class BatchEventPool:
"""
Batch Event Pool constructor
:param thread_count: Count of working threads
:type thread_count: int
:param max_events: Max count of events in queue
:typ... |
metricjar/atom-python | ironsource/atom/request.py | <filename>ironsource/atom/request.py
import base64
import requests.exceptions
from ironsource.atom.response import Response
class Request:
"""
Wrapper for HTTP requests to Atom API
"""
def __init__(self, endpoint, data, session, timeout):
"""
:param endpoint: Atom API endpoint
... |
metricjar/atom-python | ironsource/test/test_api.py | import responses
import json
import base64
import unittest
try:
# python 3
from urllib.parse import urlparse, quote
from unittest.mock import MagicMock
except ImportError:
# python 2
from urlparse import urlparse
from urllib import quote
from mock import MagicMock
from ironsource.atom impo... |
metricjar/atom-python | ironsource/atom/__init__.py | <filename>ironsource/atom/__init__.py
__author__ = 'Atom Core Team'
|
metricjar/atom-python | ironsource/atom/ironsource_atom.py | import json
import hmac
import datetime
import requests
import hashlib
import ironsource.atom.atom_logger as logger
from ironsource.atom.request import Request
import ironsource.atom.config as config
import uuid
import os
class IronSourceAtom:
"""
ironSource Atom low level API. supports put_event() and pu... |
metricjar/atom-python | ironsource/atom/atom_logger.py | import logging
import logging.handlers
def get_logger(name="AtomLogger", debug=False, file_name="atom-raw.json"):
"""
Atom Logger factory: If AtomRawLogger == name then it will return a rotating-file logger, else just logs to stdout.
:param name: logger name
:param debug: Disable/enable debug printing... |
metricjar/atom-python | ironsource/atom/event_storage.py | <reponame>metricjar/atom-python<filename>ironsource/atom/event_storage.py
import abc
class EventStorage:
"""
Abstract Base Class for providing a generic way of storing events in a backlog before they are sent to Atom.
"""
__metaclass__ = abc.ABCMeta
def __init__(self):
pass
@abc.... |
metricjar/atom-python | ironsource/atom/queue_event_storage.py | <reponame>metricjar/atom-python
from ironsource.atom.event_storage import EventStorage
from Queue import Queue
from threading import Lock
class QueueEventStorage(EventStorage):
"""
Queue event storage - in memory queue that implements ABC EventStorage
"""
def __init__(self, queue_size, block=True... |
metricjar/atom-python | ironsource/__init__.py | __author__ = 'Atom Core Team'
__version__ = '1.5.4'
__license__ = 'MIT'
__copyright__ = "ironSource"
|
metricjar/atom-python | ironsource/atom/response.py | class Response:
"""
Response information from Atom server
"""
def __init__(self, error, data, status, raw_response):
"""
:param error: Error information
:type error: object
:param data: Response information data
:type data: object
:param status: Respo... |
terapyon/minenohara-dic | gui.py | import json
import eel
from db.ejdic import found_word
LIMIT = 10
def words_means(word):
out = []
for i in range(4):
out.extend(list(found_word(word, i)))
if len(out) > LIMIT + 20:
break
return out
def results(word):
count = 0
text_list = set()
out = words_means... |
terapyon/minenohara-dic | db/ejdic.py | <reponame>terapyon/minenohara-dic<gh_stars>1-10
import os
import sqlite3
from db.automata import Matcher, find_all_matches
dataset_dir = os.path.dirname(os.path.abspath(__file__))
conn = sqlite3.connect(dataset_dir + "/ejdict.sqlite3")
def make_sorted_words():
c = conn.cursor()
# sql = '''SELECT * FROM items... |
jimmymkude/min_max_tic_tac_toe_bot | jimmy_bot_tic_tac_toe/tic_tac_toe.py | <gh_stars>0
########################################################################
#
# Created by: <NAME>
# Date Created: 6/15/2017
#
# Driver of the game
#
########################################################################
import sys
from bot import Bot
import library as game
def update_board(boa... |
jimmymkude/min_max_tic_tac_toe_bot | jimmy_bot_tic_tac_toe/library.py |
########################################################################
#
# Created by: <NAME>
# Date Created: 6/15/2017
#
# Tic Tac Toe Library functions to support game execution
#
########################################################################
def initialize_board(content_list):
board = []
ind... |
jimmymkude/min_max_tic_tac_toe_bot | jimmy_bot_tic_tac_toe/bot.py | <gh_stars>0
########################################################################
#
# Created by: <NAME>
# Date Created: 6/15/2017
#
# Represents a tic tac toe bot, uses min max
#
########################################################################
import library as game
import copy
class Bot:
de... |
EdgardoDev/django-store | djangostore/store/models.py | <filename>djangostore/store/models.py
from django.db import models
# Create your models here.
class Product(models.Model):
name = models.CharField(max_length=100)
stock_count = models.IntegerField()
price = models.DecimalField(max_digits=6, decimal_places=2)
|
Japanese-Visual-Media-Graph/utils | labels_for_elastic_search.py | import elasticsearch
from SPARQLWrapper import SPARQLWrapper, JSONLD
sparql = SPARQLWrapper("http://localhost:3030/public")
sparql.setReturnFormat(JSONLD)
es = elasticsearch.Elasticsearch()
es.indices.delete(index="jvmg_search", ignore=[400, 404])
settings = {
"settings": {
"number_of_shards": 6,
... |
PacktPublishing/Web-Development-Projects-with-Django | Chapter02/Activity2.01/juggler/projectm/migrations/0001_initial.py | <reponame>PacktPublishing/Web-Development-Projects-with-Django<gh_stars>10-100
# Generated by Django 3.0.2 on 2020-01-08 18:32
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
m... |
PacktPublishing/Web-Development-Projects-with-Django | Chapter01/Exercise1.04/bookr/reviews/tests.py | from django.test import TestCase
from django.test import Client
class Exercise4TestCase(TestCase):
def test_template_content(self):
"""Test that the index view returns the set names from the paramaters, or defaults to 'world'"""
c = Client()
response = c.get('/')
self.assertEqual(r... |
PacktPublishing/Web-Development-Projects-with-Django | Chapter12/Exercise12.03/bookr/reviews/serializers.py | <reponame>PacktPublishing/Web-Development-Projects-with-Django<gh_stars>10-100
from rest_framework import serializers
from .models import Book, Publisher
class PublisherSerializer(serializers.ModelSerializer):
class Meta:
model = Publisher
fields = ['name', 'website', 'email']
class BookSerial... |
PacktPublishing/Web-Development-Projects-with-Django | Chapter14/final/bookr/reviews/tests/test_views.py | <filename>Chapter14/final/bookr/reviews/tests/test_views.py
from django.test import TestCase, RequestFactory
from reviews.views import index
class TestIndexView(TestCase):
def setUp(self):
self.factory = RequestFactory()
def test_index_view(self):
request = self.factory.get('/index')
... |
PacktPublishing/Web-Development-Projects-with-Django | Chapter11/Exercise11.03/filter_demo/templatetags/simple_tag.py | from django import template
register = template.Library()
@register.simple_tag
def greet_user(message, username):
return "{greeting_message}, {user}!!!".format(greeting_message=message, user=username)
|
PacktPublishing/Web-Development-Projects-with-Django | Chapter14/Exercise14.01/reviews/tests.py | from django.test import TestCase
class TestSimpleComponent(TestCase):
def test_basic_sum(self):
assert 1+1 == 2
|
PacktPublishing/Web-Development-Projects-with-Django | Chapter08/final/media_project/media_example/forms.py | from django import forms
from .models import ExampleModel
class UploadForm(forms.ModelForm):
class Meta:
model = ExampleModel
fields = "__all__"
|
PacktPublishing/Web-Development-Projects-with-Django | Chapter13/Exercise13.06/bookr/bookr/utils.py | <filename>Chapter13/Exercise13.06/bookr/bookr/utils.py
import datetime
from django.db.models import Count
from reviews.models import Review
def get_books_read_by_month(username):
"""Get the books read by the user on per month basis.
:param: str The username for which the books needs to be returned
:ret... |
PacktPublishing/Web-Development-Projects-with-Django | Chapter14/Exercise14.05/bookr_test/tests.py | <gh_stars>10-100
from django.test import TestCase, Client, RequestFactory
from django.contrib.auth.models import AnonymousUser, User
from .models import Publisher
from .views import greeting_view_user
class TestPublisherModel(TestCase):
"""Test the publisher model."""
def setUp(self):
self.p = Publish... |
PacktPublishing/Web-Development-Projects-with-Django | Chapter10/Exercise10.02/bookr_admin/admin.py | from django.contrib import admin
class BookrAdmin(admin.AdminSite):
site_header = "Bookr Administration"
|
PacktPublishing/Web-Development-Projects-with-Django | Chapter10/final/bookr/reviews/admin.py | <gh_stars>10-100
from django.contrib import admin
from reviews.models import (Publisher, Contributor, Book,
BookContributor, Review)
class BookAdmin(admin.ModelAdmin):
model = Book
list_display = ('title', 'isbn', 'get_publisher', 'publication_date')
search_fields = ['title', 'publisher__name']
def g... |
PacktPublishing/Web-Development-Projects-with-Django | Chapter13/final/bookr/reviews/tests.py | <filename>Chapter13/final/bookr/reviews/tests.py
import os
from django.conf import settings
from django.test import TestCase, Client
from django.utils import timezone
from reviews.models import Book, Publisher
class Activity2Test(TestCase):
@classmethod
def setUpTestData(cls):
p = Publisher.objects.... |
PacktPublishing/Web-Development-Projects-with-Django | Chapter12/Exercise12.01/bookr/reviews/api_views.py | <filename>Chapter12/Exercise12.01/bookr/reviews/api_views.py<gh_stars>10-100
from rest_framework.decorators import api_view
from rest_framework.response import Response
from .models import Book
@api_view()
def first_api_view(request):
num_books = Book.objects.count()
return Response({"num_books": num_books})
|
PacktPublishing/Web-Development-Projects-with-Django | Chapter02/Activity2.01/juggler/projectm/apps.py | <filename>Chapter02/Activity2.01/juggler/projectm/apps.py
from django.apps import AppConfig
class ProjectmConfig(AppConfig):
name = 'projectm'
|
PacktPublishing/Web-Development-Projects-with-Django | Chapter01/Activity1.01/reviews/tests.py | <filename>Chapter01/Activity1.01/reviews/tests.py
from django.test import TestCase
from django.test import Client
class Activity1Test(TestCase):
def test_index_page(self):
"""Test the Bookr welcome screen"""
c = Client()
response = c.get('/')
self.assertIn(b'<title>Welcome to Bookr... |
PacktPublishing/Web-Development-Projects-with-Django | Chapter10/Exercise10.03/bookr_admin/admin.py | from django.contrib import admin
class BookrAdmin(admin.AdminSite):
site_header = "Bookr Administration"
logout_template = "admin/logout.html"
|
PacktPublishing/Web-Development-Projects-with-Django | Chapter16/Exercise16.01/bookr/reviews/tests.py | <reponame>PacktPublishing/Web-Development-Projects-with-Django
import os
from django.conf import settings
from django.test import TestCase, Client
class Exercise1Test(TestCase):
def test_view_and_template(self):
"""Test that the view, URLs and template are set up properly by checking the contents of the ... |
PacktPublishing/Web-Development-Projects-with-Django | Chapter15/Exercise15.02/bookr/reviews/tests.py | from configurations import values
from django.test import TestCase
from bookr import settings as direct_settings
class Exercise2Test(TestCase):
def test_dj_database_url(self):
"""Test that the DATABASES is being set with a URL."""
# since we are running in DEBUG mode we can check how the values w... |
PacktPublishing/Web-Development-Projects-with-Django | Chapter18/final/bookr/reviews/templatetags/profile_tags.py | <filename>Chapter18/final/bookr/reviews/templatetags/profile_tags.py<gh_stars>10-100
from django import template
from reviews.models import Review
register = template.Library()
@register.inclusion_tag('book_list.html')
def book_list(username):
"""Render the list of books read by a user.
:param: str username The ... |
PacktPublishing/Web-Development-Projects-with-Django | Chapter07/Exercise7.03/bookr/reviews/tests.py | <filename>Chapter07/Exercise7.03/bookr/reviews/tests.py
import re
from django.test import Client
from django.test import TestCase
from reviews.models import Publisher
class Exercise3Test(TestCase):
def test_fields_in_view(self):
""""
Test that fields exist in the rendered template.
"""
... |
PacktPublishing/Web-Development-Projects-with-Django | Chapter01/Exercise1.08/bookr/reviews/tests.py | from django.test import TestCase
from django.test import Client
class Exercise8TestCase(TestCase):
def test_exception(self):
"""The view should raise a NameError exception"""
c = Client()
with self.assertRaises(NameError):
c.get('/')
|
PacktPublishing/Web-Development-Projects-with-Django | Chapter11/Exercise11.01/filter_demo/templatetags/explode_filter.py | from django import template
register = template.Library()
@register.filter
def explode(value, separator):
return value.split(separator)
|
PacktPublishing/Web-Development-Projects-with-Django | Chapter14/final/bookr/reviews/tests/test_models.py | <filename>Chapter14/final/bookr/reviews/tests/test_models.py
from django.test import TestCase
from reviews.models import Book, Publisher, Contributor
class TestPublisherModel(TestCase):
def test_create_publisher(self):
publisher = Publisher.objects.create(name='Packt', website='www.packt.com', email='<EM... |
PacktPublishing/Web-Development-Projects-with-Django | Chapter09/Exercise09.02/bookr/bookr/views.py | <filename>Chapter09/Exercise09.02/bookr/bookr/views.py
from django.shortcuts import render
def profile(request):
return render(request, 'profile.html')
|
PacktPublishing/Web-Development-Projects-with-Django | Chapter08/Exercise8.06/media_project/media_example/forms.py | from django import forms
class UploadForm(forms.Form):
image_upload = forms.ImageField()
file_upload = forms.FileField()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.