repo_name
stringlengths
6
97
path
stringlengths
3
341
text
stringlengths
8
1.02M
CornellLenard/Deep-Learning-Course-Exercises
Exercise 06/exercise_code/networks/loss.py
<gh_stars>0 import numpy as np class Loss(object): def __init__(self): self.grad_history = [] def forward(self, y_out, y_truth): return NotImplementedError def backward(self, y_out, y_truth, upstream_grad=1.): return NotImplementedError def __call__(self, y_out, y_truth): ...
CornellLenard/Deep-Learning-Course-Exercises
Exercise 08/exercise_code/Util.py
<reponame>CornellLenard/Deep-Learning-Course-Exercises import os import torch import pickle from exercise_code.models import Encoder, Classifier PARAM_LIMIT = 5e6 SIZE_LIMIT_MB = 20 ACC_THRESHOLD = 0.5 def checkParams(model): n_params = sum(p.numel() for p in model.parameters()) if n_params > PARAM_LIMIT: ...
CornellLenard/Deep-Learning-Course-Exercises
Exercise 10/exercise_code/networks/segmentation_nn.py
<gh_stars>0 """SegmentationNN""" import torch import torch.nn as nn from torchvision import models class SegmentationNN(nn.Module): def __init__(self, num_classes=23, hparams=None): super().__init__() self.hparams = hparams self.num_classes = num_classes ##########################...
CornellLenard/Deep-Learning-Course-Exercises
Exercise 10/exercise_code/util/__init__.py
"""Util functions""" from .vis_utils import visualizer from .save_model import save_model from .Util import checkParams, checkSize, test
CornellLenard/Deep-Learning-Course-Exercises
Exercise 08/exercise_code/tests/eval_utils.py
<gh_stars>1-10 import pickle import os import numpy as np def evaluate(x): sum_exp = np.sum(x) if sum_exp > 4.53: print('Hurray, you passed!! Now save your model and submit it!') return 75 else: print('I think you can do better...') return 0 def save_pickle(data_dict, fi...
CornellLenard/Deep-Learning-Course-Exercises
Exercise 09/exercise_code/tests/__init__.py
<gh_stars>0 """Unit tests and evaluation tools""" from .keypoint_nn_tests import test_keypoint_nn
CornellLenard/Deep-Learning-Course-Exercises
Exercise 09/exercise_code/util/vis_utils.py
<reponame>CornellLenard/Deep-Learning-Course-Exercises """Utils for visualizations in notebooks""" import matplotlib.pyplot as plt def show_all_keypoints(image, keypoints, pred_kpts=None): """Show image with predicted keypoints""" image = (image.clone() * 255).view(96, 96) plt.imshow(image, cmap='gray') ...
CornellLenard/Deep-Learning-Course-Exercises
Exercise 09/exercise_code/tests/spatial_batchnorm_tests.py
import numpy as np from .base_tests import UnitTest, CompositeTest from .. import layers from .gradient_check import ( eval_numerical_gradient_array, eval_numerical_gradient, rel_error, ) class SpatialBatchnormForwardTest(UnitTest): def __init__(self, shape, mean, scale, beta, gamma, mode, test_name)...
CornellLenard/Deep-Learning-Course-Exercises
Exercise 10/exercise_code/tests/eval_utils.py
<reponame>CornellLenard/Deep-Learning-Course-Exercises import pickle import os def save_pickle(data_dict, file_name): """Save given data dict to pickle file file_name in models/""" directory = 'models' if not os.path.exists(directory): os.makedirs(directory) pickle.dump(data_dict, open(os.path...
CornellLenard/Deep-Learning-Course-Exercises
Exercise 09/exercise_code/networks/SpatialBatchNormModel.py
<gh_stars>0 import pytorch_lightning as pl import torch import torch.nn as nn import torch.nn.functional as F from torch.utils.data import DataLoader import torchvision import torchvision.transforms as transforms import numpy as np class AbstractNetwork(pl.LightningModule): def general_step(self, batch, batch_id...
CornellLenard/Deep-Learning-Course-Exercises
Exercise 08/exercise_code/tests/grad_tests.py
<filename>Exercise 08/exercise_code/tests/grad_tests.py import numpy as np from .base_tests import UnitTest, CompositeTest, test_results_to_score import math from .gradient_check_utils import eval_numerical_gradient_array epsilon = 1e-7 class TestForwardPass(UnitTest): """Test whether Sigmoid of 0 is correct""" ...
CornellLenard/Deep-Learning-Course-Exercises
Exercise 09/exercise_code/tests/keypoint_nn_tests.py
<gh_stars>0 """Tests for facial keypoint detection models""" import os import torch from exercise_code.tests.base_tests import UnitTest, CompositeTest from exercise_code.util.save_model import save_model class KeypointShapeTest(UnitTest): """Test whether model returns correct keypoint shape""" def __init__...
CornellLenard/Deep-Learning-Course-Exercises
Exercise 08/exercise_code/image_folder_dataset.py
<reponame>CornellLenard/Deep-Learning-Course-Exercises """ Definition of ImageFolderDataset dataset class """ # pylint: disable=too-few-public-methods import os import torch from .base_dataset import Dataset class ImageFolderDataset(Dataset): """CIFAR-10 dataset class""" def __init__(self, *args, ...
CornellLenard/Deep-Learning-Course-Exercises
Exercise 06/exercise_code/networks/__init__.py
"""Definition of all datasets""" from .classification_net import MyOwnNetwork, ClassificationNet from .loss import L1, MSE, BCE, CrossEntropyFromLogits
CornellLenard/Deep-Learning-Course-Exercises
Exercise 10/exercise_code/tests/__init__.py
<reponame>CornellLenard/Deep-Learning-Course-Exercises<filename>Exercise 10/exercise_code/tests/__init__.py """Unit tests and evaluation tools""" from .segmentation_nn_tests import test_seg_nn
CornellLenard/Deep-Learning-Course-Exercises
Exercise 07/exercise_code/lightning_models.py
<gh_stars>0 import matplotlib.pyplot as plt import pytorch_lightning as pl import torch import torch.nn.functional as F import torch.nn as nn import torchvision from torchvision import transforms from torch.utils.data import DataLoader, random_split class TwoLayerNet(pl.LightningModule): def __init__(self, hpar...
CornellLenard/Deep-Learning-Course-Exercises
Exercise 08/exercise_code/models.py
<reponame>CornellLenard/Deep-Learning-Course-Exercises import pytorch_lightning as pl import torch import torch.nn as nn import torch.nn.functional as F from torch.utils.data import DataLoader import numpy as np class Encoder(nn.Module): def __init__(self, hparams, input_size=28 * 28, latent_dim=24): sup...
CornellLenard/Deep-Learning-Course-Exercises
Exercise 09/exercise_code/networks/keypoint_nn.py
<gh_stars>0 """Models for facial keypoint detection""" import torch import torch.nn as nn from torch.nn import functional as F import pytorch_lightning as pl class ResidualBlock(nn.Module): def __init__(self, in_channel_num, out_channel_num, use_11conv=False, stride=1): super(ResidualBlock, self).__init...
CornellLenard/Deep-Learning-Course-Exercises
Exercise 09/exercise_code/layers.py
import numpy as np def batchnorm_forward(x, gamma, beta, bn_param): """ Forward pass for batch normalization. During training the sample mean and (uncorrected) sample variance are computed from mini-batch statistics and used to normalize the incoming data. During training we also keep an ex...
CornellLenard/Deep-Learning-Course-Exercises
Exercise 08/exercise_code/tests/__init__.py
"""Define tests, sanity checks, and evaluation""" from .grad_tests import *
CornellLenard/Deep-Learning-Course-Exercises
Exercise 09/exercise_code/networks/__init__.py
"""Neural network definitions""" from .keypoint_nn import ( KeypointModel, DummyKeypointModel )
CornellLenard/Deep-Learning-Course-Exercises
Exercise 07/exercise_code/MyPytorchModel.py
<reponame>CornellLenard/Deep-Learning-Course-Exercises import pytorch_lightning as pl import torch import torch.nn as nn import torch.nn.functional as F from torch.utils.data import DataLoader from torch.utils.data.sampler import SubsetRandomSampler import torchvision import torchvision.transforms as transforms import ...
CornellLenard/Deep-Learning-Course-Exercises
Exercise 07/exercise_code/data/base_dataset.py
<filename>Exercise 07/exercise_code/data/base_dataset.py """Dataset Base Class""" from abc import ABC, abstractmethod from .download_utils import download_dataset class Dataset(ABC): """ Abstract Dataset Base Class All subclasses must define __getitem__() and __len__() """ def __init__(self, roo...
CornellLenard/Deep-Learning-Course-Exercises
Exercise 09/exercise_code/data/facial_keypoints_dataset.py
"""Dataset for facial keypoint detection""" import os import pandas as pd import numpy as np import torch from .base_dataset import BaseDataset class FacialKeypointsDataset(BaseDataset): """Dataset for facial keypoint detection""" def __init__(self, *args, train=True, transform=None, **kwargs): sup...
CornellLenard/Deep-Learning-Course-Exercises
Exercise 10/exercise_code/util/vis_utils.py
<reponame>CornellLenard/Deep-Learning-Course-Exercises """Utils for visualizations in notebooks""" import matplotlib.pyplot as plt import torch from math import sqrt, ceil import numpy as np from exercise_code.data.segmentation_dataset import label_img_to_rgb device = torch.device("cuda:0" if torch.cuda.is_available()...
CornellLenard/Deep-Learning-Course-Exercises
Exercise 10/exercise_code/tests/segmentation_nn_tests.py
"""Tests for facial keypoint detection models""" import os import torch from exercise_code.tests.base_tests import UnitTest, CompositeTest from exercise_code.util.save_model import save_model class ParamCountTest(UnitTest): """Test whether number of model params smaller than limit""" def __init__(self, mo...
CornellLenard/Deep-Learning-Course-Exercises
Exercise 10/exercise_code/util/save_model.py
<filename>Exercise 10/exercise_code/util/save_model.py """Utils for model saving""" import os import pickle import torch def save_model(model, file_name, directory="models"): """Save model as pickle""" model = model.cpu() if not os.path.exists(directory): os.makedirs(directory) model_path = os...
CornellLenard/Deep-Learning-Course-Exercises
Exercise 07/exercise_code/data_class.py
import pytorch_lightning as pl import torch import torchvision from torchvision import transforms from torch.utils.data import DataLoader, random_split class FashionMNISTDataModule(pl.LightningDataModule): def __init__(self, batch_size=4): super().__init__() self.batch_size = batch_size def ...
CornellLenard/Deep-Learning-Course-Exercises
Exercise 07/exercise_code/data/csv_dataset.py
<gh_stars>0 from .base_dataset import Dataset import numpy as np import pandas as pd import os.path class CSVDataset(Dataset): """ CSVDataset class. Provide access to the Boston Housing Prices dataset. """ def __init__(self, target_column, transform=None, mode="train", input_data=None, *args, **k...
CornellLenard/Deep-Learning-Course-Exercises
Exercise 06/exercise_code/tests/__init__.py
<filename>Exercise 06/exercise_code/tests/__init__.py """Define tests, sanity checks, and evaluation""" from .eval_utils import save_pickle
CornellLenard/Deep-Learning-Course-Exercises
Exercise 09/exercise_code/util/__init__.py
<reponame>CornellLenard/Deep-Learning-Course-Exercises """Util functions""" from .vis_utils import show_all_keypoints from .save_model import save_model
Callifrey/ACGAN-Paddle
dataset.py
import paddle.vision.transforms as tran from paddle.io import Dataset, DataLoader from PIL import Image import os import os.path IMG_EXTENSIONS = ['.jpg', '.jpeg', '.png', '.ppm', '.bmp', '.pgm'] def is_image_file(filename): filename_lower = filename.lower() return any(filename_lower.endswith(ext) for ext in...
Callifrey/ACGAN-Paddle
test.py
<reponame>Callifrey/ACGAN-Paddle<gh_stars>0 import argparse from utils import * from network import Generator parser = argparse.ArgumentParser() parser.add_argument('--dataroot', type=str, default='/media/gallifrey/DJW/Dataset/Imagenet/train', help='path to dataset') parser.add_argument('--batchSize', type=int, defaul...
Callifrey/ACGAN-Paddle
network.py
<gh_stars>0 import paddle import paddle.nn as nn class Generator(nn.Layer): def __init__(self, nz): super(Generator, self).__init__() self.nz = nz # first linear layer self.fc1 = nn.Linear(110, 768) # Transposed Convolution 2 self.tconv2 = nn.Sequential( ...
Callifrey/ACGAN-Paddle
utils.py
<filename>utils.py<gh_stars>0 import paddle import numpy as np from PIL import Image import os # 计算当前分类准确率 def compute_acc(preds, labels): correct = 0 preds_ = paddle.argmax(preds, axis=1) correct = paddle.to_tensor(np.sum(np.array(preds_ == labels))) acc = float(correct) / float(labels.shape[0]) * 100...
Callifrey/ACGAN-Paddle
train.py
<gh_stars>0 import paddle.vision.transforms as tran from paddle.io import Dataset, DataLoader import argparse import paddle.nn as nn from visualdl import LogWriter from utils import * from network import Generator, Discriminator from dataset import ImageFolder parser = argparse.ArgumentParser() parser.add_argument('...
CodeSelfStudy/python-project-cookiecutter
{{cookiecutter.directory_name}}/setup.py
<gh_stars>0 """Configuration for {{ cookiecutter.project_name }}.""" try: from setuptools import setup except ImportError: from distutils.core import setup config = { 'description': '{{ cookiecutter.description }}', 'author': '{{ cookiecutter.author }}', 'url': '{{ cookiecutter.url }}', 'downlo...
CodeSelfStudy/python-project-cookiecutter
{{cookiecutter.directory_name}}/tests/{{cookiecutter.directory_name}}_tests.py
from nose.tools import * import NAME def setup(): print('setup') def teardown(): print('teardown') def test_basic(): print('test ran')
jordimarinvalle/requeues
pimpamqueues/simplequeue.py
<reponame>jordimarinvalle/requeues #!/usr/bin/env python # -*- coding: utf-8 -*- import redis from pimpamqueues import QUEUE_COLLECTION_OF_ELEMENTS from pimpamqueues import Tools from pimpamqueues.exceptions import PimPamQueuesError from pimpamqueues.exceptions import PimPamQueuesElementWithoutValueError class Sim...
jordimarinvalle/requeues
tests/test_bucketqueue.py
<gh_stars>1-10 #!/usr/bin/env python # -*- coding: utf-8 -*- import pytest from tests import redis_conn from pimpamqueues.bucketqueue import BucketQueue ELEMENT_EGG = b'egg' ELEMENT_BACON = b'bacon' ELEMENT_SPAM = b'spam' ELEMENT_42 = b'42' ELEMENT_UNEXISTENT_ELEMENT = b'utopia' some_elements = [ ELEMENT_EGG,...
jordimarinvalle/requeues
pimpamqueues/exceptions.py
#!/usr/bin/env python # -*- coding: utf-8 -*- class PimPamQueuesError(Exception): MESSAGE = 'Unexpected error' def __init__(self, message=''): self.message = message if message else self.MESSAGE def __str__(self): return '<%s %s>' % (self.__class__.__name__, self.message) class PimPam...
jordimarinvalle/requeues
tests/test_tools.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import pytest from pimpamqueues import Tools class TestTools(object): def setup(self): self.block_slices_300_1 = Tools.get_block_slices(300, 1) self.block_slices_10_10 = Tools.get_block_slices(10, 10) self.block_slices_27_10 = Tools.get_bloc...
jordimarinvalle/requeues
tests/__init__.py
<reponame>jordimarinvalle/requeues #!/usr/bin/env python # -*- coding: utf-8 -*- import redis # REDISLABS FREE ACCOUNT # https://redislabs.com/ REDIS_HOST = 'pub-redis-10356.us-east-1-3.6.ec2.redislabs.com' REDIS_PORT = '10356' REDIS_PASSWORD = '<PASSWORD>' REDIS_DATABASE = '0' redis_conn = redis.Redis( host=RED...
jordimarinvalle/requeues
tests/test_smartqueue.py
<filename>tests/test_smartqueue.py #!/usr/bin/env python # -*- coding: utf-8 -*- import pytest from tests import redis_conn from pimpamqueues.smartqueue import SmartQueue from pimpamqueues.exceptions import PimPamQueuesDisambiguatorInvalidError ELEMENT_EGG = b'egg' ELEMENT_BACON = b'bacon' ELEMENT_SPAM = b'spam' EL...
jordimarinvalle/requeues
pimpamqueues/bucketqueue.py
<filename>pimpamqueues/bucketqueue.py #!/usr/bin/env python # -*- coding: utf-8 -*- import redis from pimpamqueues import QUEUE_COLLECTION_OF_ELEMENTS from pimpamqueues import Tools from pimpamqueues.exceptions import PimPamQueuesError from pimpamqueues.exceptions import PimPamQueuesElementWithoutValueError class ...
jordimarinvalle/requeues
pimpamqueues/__init__.py
<filename>pimpamqueues/__init__.py #!/usr/bin/env python # -*- coding: utf-8 -*- import math NUM_BLOCK_SIZE = 1000 QUEUE_COLLECTION_OF_URLS = 'urls' QUEUE_COLLECTION_OF_JOBS = 'jobs' QUEUE_COLLECTION_OF_TASKS = 'tasks' QUEUE_COLLECTION_OF_ITEMS = 'items' QUEUE_COLLECTION_OF_ELEMENTS = 'elements' VERSION_MAJOR = 1 ...
jordimarinvalle/requeues
setup.py
<gh_stars>1-10 #!/usr/bin/env python # -*- coding: utf-8 -*- import sys from setuptools import setup from setuptools.command.test import test as TestCommand from pimpamqueues import __version__ class TestTox(TestCommand): def finalize_options(self): TestCommand.finalize_options(self) self.test...
jordimarinvalle/requeues
tests/test_simplequeue.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import pytest from tests import redis_conn from pimpamqueues.simplequeue import SimpleQueue ELEMENT_EGG = b'egg' ELEMENT_BACON = b'bacon' ELEMENT_SPAM = b'spam' ELEMENT_42 = b'42' some_elements = [ ELEMENT_EGG, ELEMENT_BACON, ELEMENT_SPAM, ELEMENT_42, ...
jordimarinvalle/requeues
pimpamqueues/smartqueue.py
#!/usr/bin/env python # -*- coding: utf-8 -*- import redis from pimpamqueues import QUEUE_COLLECTION_OF_ELEMENTS from pimpamqueues import Tools from pimpamqueues.simplequeue import SimpleQueue from pimpamqueues.bucketqueue import BucketQueue from pimpamqueues.exceptions import PimPamQueuesError from pimpamqueues.ex...
Cog-Creators/Red-GitHubBot
red_githubbot/routers/auto_apply_changelog_entry_pending.py
<filename>red_githubbot/routers/auto_apply_changelog_entry_pending.py<gh_stars>0 from gidgethub import sansio from .. import utils from . import gh_router @gh_router.register("pull_request", action="closed") async def auto_apply_changelog_entry_pending(event: sansio.Event) -> None: pr_data = event.data["pull_req...
Cog-Creators/Red-GitHubBot
red_githubbot/tasks.py
<reponame>Cog-Creators/Red-GitHubBot import logging import os import subprocess from aiohttp import web from apscheduler.schedulers.asyncio import AsyncIOScheduler from . import utils from .constants import FORK_REPO, GIT_EMAIL, GIT_NAME, REPO_NAME, UPSTREAM_REPO _log = logging.getLogger(__name__) # consider adding...
Cog-Creators/Red-GitHubBot
red_githubbot/routers/backport_pr.py
import asyncio import logging from cherry_picker import cherry_picker from gidgethub import sansio from .. import utils from ..constants import MAINTENANCE_BRANCHES, UPSTREAM_REPO, UPSTREAM_USERNAME from . import gh_router log = logging.getLogger(__name__) CHERRY_PICKER_CONFIG = { "team": UPSTREAM_USERNAME, ...
Cog-Creators/Red-GitHubBot
red_githubbot/routers/__init__.py
import importlib import pkgutil from gidgethub import routing DISABLED_ROUTERS = {"fix_committed_and_released"} gh_router = routing.Router() # import all submodules in order to fill `gh_router` with all the routes for loader, module_name, is_pkg in pkgutil.iter_modules(__path__, __name__ + "."): _, _, router_na...
Cog-Creators/Red-GitHubBot
red_githubbot/routers/maintenance_branch_actions.py
import logging import re from typing import Any from gidgethub import sansio from .. import utils from ..constants import MAINTENANCE_BRANCHES, UPSTREAM_REPO from . import gh_router log = logging.getLogger(__name__) TITLE_RE = re.compile(r"\s*\[(?P<branch>\d+\.\d+)\].+\(#(?P<pr_number>\d+)\)") MAINTENANCE_BRANCH_TI...
Cog-Creators/Red-GitHubBot
red_githubbot/routers/auto_delete_pr_branch.py
import contextlib import gidgethub from gidgethub import sansio from .. import utils from ..constants import FORK_REPO, MACHINE_USERNAME from . import gh_router @gh_router.register("pull_request", action="closed") async def auto_delete_pr_branch(event: sansio.Event) -> None: pr_data = event.data["pull_request"]...
Cog-Creators/Red-GitHubBot
red_githubbot/routers/fix_committed_and_released.py
<gh_stars>0 import logging import re from typing import Any import graphql_builder from gidgethub import sansio from .. import utils from ..constants import REPO_NAME, UPSTREAM_REPO, UPSTREAM_USERNAME from . import gh_router log = logging.getLogger(__name__) GET_CLOSED_EVENT_QUERY = utils.minify_graphql_call( "...
Cog-Creators/Red-GitHubBot
red_githubbot/issue_parser/actions.py
<filename>red_githubbot/issue_parser/actions.py ACTIONS = { "close": ( "close", "closes", "closed", "fix", "fixes", "fixed", "resolve", "resolves", "resolved", ), } KEYWORDS = { keyword: action for action, keyword_list in ACTIONS.items(...
Cog-Creators/Red-GitHubBot
red_githubbot/constants.py
<reponame>Cog-Creators/Red-GitHubBot MACHINE_USERNAME = "Red-GitHubBot" UPSTREAM_USERNAME = "Cog-Creators" REQUESTER = f"{UPSTREAM_USERNAME}/Red-GitHubBot" REPO_NAME = "Red-DiscordBot" FORK_REPO = f"{MACHINE_USERNAME}/{REPO_NAME}" UPSTREAM_REPO = f"{UPSTREAM_USERNAME}/{REPO_NAME}" GIT_NAME = MACHINE_USERNAME GIT_EMAIL ...
Cog-Creators/Red-GitHubBot
red_githubbot/__main__.py
import logging import os from aiohttp import web from .web import app as web_app log = logging.getLogger("red_githubbot") def main() -> None: if _sentry_dsn := os.environ.get("SENTRY_DSN"): # pylint: disable=import-outside-toplevel import sentry_sdk from sentry_sdk.integrations.pure_eva...
Cog-Creators/Red-GitHubBot
red_githubbot/routers/blocked_labels_check.py
<gh_stars>0 from gidgethub import sansio from .. import utils from . import gh_router CHECK_RUN_NAME = "Blocked status" @gh_router.register("pull_request", action="opened") @gh_router.register("pull_request", action="reopened") @gh_router.register("pull_request", action="synchronize") @gh_router.register("pull_requ...
Cog-Creators/Red-GitHubBot
red_githubbot/issue_parser/__init__.py
<reponame>Cog-Creators/Red-GitHubBot from ._parser import parse_issue_body __all__ = ("parse_issue_body",)
Cog-Creators/Red-GitHubBot
red_githubbot/routers/keep_up_to_date_application_ids.py
<gh_stars>0 import logging from gidgethub import sansio from .. import utils from . import gh_router log = logging.getLogger(__name__) @gh_router.register("installation", action="created") @gh_router.register("installation", action="deleted") async def update_installation_id_cache(event: sansio.Event) -> None: ...
Cog-Creators/Red-GitHubBot
red_githubbot/web.py
import asyncio import logging import os import gidgethub from aiohttp import web from gidgethub import sansio from . import tasks, utils from .constants import UPSTREAM_REPO from .routers import gh_router log = logging.getLogger(__name__) routes = web.RouteTableDef() @routes.get("/") async def hello(_request: web...
Cog-Creators/Red-GitHubBot
red_githubbot/issue_parser/_regexes.py
import regex from .actions import KEYWORDS # partial regex pattern strings _KEYWORD_PATTERN = rf""" (?: (?P<keyword_name>{'|'.join(map(regex.escape, KEYWORDS))}) # the issue reference needs to be delimited from the keyword by # any amount of whitespace and optionally one colon in it (?:\ |\t)* (...
Cog-Creators/Red-GitHubBot
red_githubbot/issue_parser/_parser.py
<reponame>Cog-Creators/Red-GitHubBot from typing import Any, Optional import regex from ..utils import parse_markdown from ._regexes import ISSUE_URL_RE, KEYWORD_RE, TEXT_RE from .actions import ACTIONS, KEYWORDS from .wrappers import ParsedIssue, ParsedIssueAction, ParsedIssueMention, ParsedIssueRef def parse_issu...
Cog-Creators/Red-GitHubBot
red_githubbot/issue_parser/wrappers.py
<gh_stars>0 from collections.abc import Iterable from dataclasses import InitVar, dataclass, field from typing import Optional @dataclass class ParsedIssueFragment: pass @dataclass class ParsedIssueRef(ParsedIssueFragment): slug: Optional[str] issue_number: int @dataclass class ParsedIssueAction(Parse...
Cog-Creators/Red-GitHubBot
red_githubbot/utils.py
import asyncio import dataclasses import datetime import enum import functools import logging import os import subprocess from collections.abc import Callable, Coroutine, Mapping, MutableMapping from contextlib import AbstractAsyncContextManager, AbstractContextManager from typing import Any, Optional, TypeVar import ...
uxcn/x2x
setup.py
from distutils.core import setup setup( url = 'https://github.com/uxcn/x2x', name = 'x2x', version = '0.9', fullname = 'x2x', description = 'commands to convert radixes', long_description = ''' x2x Command...
syed-ahmed/tensorflow
tensorflow/contrib/estimator/python/estimator/multi_head_test.py
# 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 applica...
imonursahin/python-simple-student-management-system
obs.py
import time import cagir print(""" ============================================== = = = Öğrenci Bilgi Sistemi - Akademisyen Girişi = = (k_adi: onur - sifre: 1903) = = = ============================================== "...
imonursahin/python-simple-student-management-system
cagir.py
import time class Ogrenci(object): def __init__(self, isim=None, soyisim=None, numara=None, bölüm=None, vizeNot=None, finalNot=None, topDersSaat=None, devamsızlıkBil=None, danisman=None): self.isim = isim self.soyisim = soyisim self.numara = numara self.bölüm = bölüm self.vi...
sakurai-youhei/rpsowmi
rpsowmi.py
<reponame>sakurai-youhei/rpsowmi ''' Created on 2017/04/06 @author: sakurai ''' import _winapi # TODO(X): It might be better to use ctypes.windll instead from base64 import encodebytes from collections import defaultdict from collections import namedtuple from concurrent.futures import ThreadPoolExecutor from contex...
sakurai-youhei/rpsowmi
setup.py
<gh_stars>1-10 from setuptools import setup import rpsowmi classifiers = [line.rstrip() for line in """\ License :: OSI Approved :: MIT License Development Status :: 3 - Alpha Programming Language :: Python :: 3.4 Programming Language :: Python :: 3.5 Programming Language :: Python :: 3.6 Operating System :: Micros...
naamaf/hw5_2019
hw5.py
import pathlib import os import pandas as pd import numpy as np import matplotlib.pyplot as plt from typing import Union, Tuple class QuestionnaireAnalysis: """ Reads and analyzes data generated by the questionnaire experiment. Should be able to accept strings and pathlib.Path objects. """ de...
Yugal41735/sample-repoasitory
Hello.py
print("hello World") print("This is the sample repository")
Lispython/httpecho
setup.py
<gh_stars>0 #!/usr/bin/env python # -*- coding: utf-8 -*- """ empty_server ~~~~~~~~~~~~ HTTP Request & Response service :copyright: (c) 2014 by <NAME> (<EMAIL>). :license: BSD, see LICENSE for more details. """ import sys import os from setuptools import setup, find_packages try: readme_content = open(os.path...
Lispython/httpecho
httpecho/app.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ http.app ~~~~~~~~~ Core of HTTP Request & Response service :copyright: (c) 2011 by <NAME> (<EMAIL>). :license: BSD, see LICENSE for more details. :github: http://github.com/Lispython/httpecho """ import os import sys import time import tornado.ioloop import tornado ...
Lispython/httpecho
httpecho/utils.py
<reponame>Lispython/httpecho #!/usr/bin/env python # -*- coding: utf-8 -*- """ httphq.utils ~~~~~~~~~~~~ Helpers for handlers :copyright: (c) 2011 - 2013 by <NAME> (<EMAIL>). :license: BSD, see LICENSE for more details. :github: http://github.com/Lispython/httphq """ import sys try: from urllib2 import parse_h...
Lispython/httpecho
debug.py
#!/usr/bin/env python # -*- coding: utf-8 -*- """ httphq.debug ~~~~~~~~~~~~ Local debug runner :copyright: (c) 2011 - 2013 by <NAME> (<EMAIL>). :license: BSD, see LICENSE for more details. """ import tornado.ioloop from tornado import httpserver, autoreload from tornado.options import options, parse_command_line f...
Lispython/httpecho
httpecho/compat.py
<gh_stars>1-10 #!/usr/bin/env python # -*- coding: utf-8 -*- """ Compatibility module ~~~~~~~~~~~~~~~~~~~~ Add utilities to support python2 and python3 :copyright: (c) 2013 by <NAME> (<EMAIL>). :license: BSD, see LICENSE for more details. :github: http://github.com/Lispython/httphq """ import sys py_ver = sys.vers...
fellipematos/TAG
tag/app.py
<filename>tag/app.py from flask import Flask, render_template, request, url_for import json app = Flask(__name__) @app.route('/') def index(): return render_template('index.html') @app.route('/etiqueta', methods=['GET', 'POST']) def tag(): if request.method == 'POST': dados = { 'dnome': ...
boyob/YOLO4
utils/utils_fit.py
<filename>utils/utils_fit.py import torch from tqdm import tqdm from utils.utils import get_lr def fit_one_epoch(model_train, model, yolo_loss, loss_history, optimizer, epoch, epoch_step, epoch_step_val, gen, gen_val, Epoch, cuda): loss = 0 val_loss = 0 model_train.train() print('S...
boyob/YOLO4
utils/dataloader.py
<gh_stars>0 from random import sample, shuffle import cv2 import numpy as np from PIL import Image from torch.utils.data.dataset import Dataset from utils.utils import cvtColor, preprocess_input class YoloDataset(Dataset): def __init__(self, annotation_lines, input_shape, num_classes, mosaic, train): su...
HotIce0/ht_docs
app_repo/models.py
from datetime import datetime from django.db import models from django.conf import settings class Repository(models.Model): """ 仓库表 """ class Meta: db_table = 't_repository' user = models.ForeignKey(verbose_name='仓库所有者', to=settings.AUTH_USER_MODEL, on_delete=models.CASCADE, ...
HotIce0/ht_docs
app_user/models.py
from datetime import datetime from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin from django.db import models class UserManager(BaseUserManager): def create_user(self, username, **extra_fields): """ Create and save a user with the given username, email, and ...
HotIce0/ht_docs
app_repo/migrations/0001_initial.py
<gh_stars>0 # Generated by Django 3.2.9 on 2021-11-27 18:47 import datetime from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH...
georghe-crihan/AlgoWaveGraph
wave.py
<reponame>georghe-crihan/AlgoWaveGraph<filename>wave.py<gh_stars>0 #!/usr/bin/env python # -*- coding: utf-8 -*- # Этот пpимеp демонстpиpует поиск кpатчайщего пути в лабиpинте. # Это _не_ оптимальнейшая pеализация волнового алгоpитма, и # пpедназначена она только для демонстpации его пpинципов. # # Должна компилиться л...
mbarkhau/markdown-katex
src/markdown_katex/__init__.py
# This file is part of the markdown-katex project # https://github.com/mbarkhau/markdown-katex # # Copyright (c) 2019-2021 <NAME> (<EMAIL>) - MIT License # SPDX-License-Identifier: MIT """markdown_katex extension. This is an extension for Python-Markdown which uses KaTeX to generate html from tex. """ __version__ = ...
TakeshiKishita/kadai_HNSon
summation_of_divisors.py
<filename>summation_of_divisors.py # coding=utf-8 """" int numを引数として渡すと、numの約数の総和を返す """ import math import sys def get_prime_number(num): """Summary line. エラトステネスの篩を使い、素数を列挙する Args: num (int): 素因数分解を行う数値 Returns: list: numまでの素数リスト """ sequence_list = [i for i in range(2, num + 1)] # 2から入力値までの数列のリスト pr...
terrotim/alpha-zero-general
pit.py
<gh_stars>0 import os os.environ['CUDA_VISIBLE_DEVICES'] = '0' os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' import Arena from MCTS import MCTS from sotf.SotfGame import SotfGame, display from sotf.SotfPlayers import * from sotf.tensorflow.NNet import NNetWrapper as NNet """ from connect4.Connect4Game import Connect4Gam...
terrotim/alpha-zero-general
sotf/SotfGame.py
<reponame>terrotim/alpha-zero-general<gh_stars>0 import sys import numpy as np import colorama from itertools import permutations,product sys.path.append('..') from Game import Game from .SotfLogic import Board from termcolor import colored, cprint colorama.init() class SotfGame(Game): """ Connect4 Game clas...
terrotim/alpha-zero-general
sotf/SotfLogic.py
from collections import namedtuple import numpy as np DEFAULT_HEIGHT = 6 DEFAULT_WIDTH = 7 DEFAULT_WIN_LENGTH = 4 WinState = namedtuple('WinState', 'is_ended winner') class Board(): """ Connect4 Board. """ def __init__(self, height=None, width=None, tiles=None): self.height = height ...
terrotim/alpha-zero-general
main.py
import os os.environ['CUDA_VISIBLE_DEVICES'] = '0' os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' import logging import coloredlogs """ from Coach import Coach from connect4.Connect4Game import Connect4Game as Game from connect4.tensorflow.NNet import NNetWrapper as nn from utils import dotdict """ from Coach import Coach ...
MarcusTL12/PyCalc
imports.py
import sys sys.path.append('./PyScr/') import numpy as np import matplotlib.pyplot as plt import cmath import math import copy import pfprint import primefac from scipy.special import comb as choose _ = None def ppprint(arg): global _ pfprint.pfprint(arg) _ = arg def frac(): pfprint.frac = not pfprint.frac retu...
MarcusTL12/PyCalc
PyScr/primefac.py
import math def primes(n:int) -> list: factors = [] if n < 0: factors.append(-1) factors.append(1) n *= -1 more = False i = 2 while i <= math.sqrt(n): while n % i == 0: if not more: factors.append(i) factors.append(1) more = True else: factors[-1] += 1 n /= i more = False ...
MarcusTL12/PyCalc
PyScr/pifrac.py
from fractions import Fraction import numpy as np a = [Fraction(22 / 7)] for i in range(8, 1000000): frac = Fraction(np.pi).limit_denominator(i) if abs(float(a[-1]) - np.pi) > abs(float(frac) - np.pi): a.append(frac)
MarcusTL12/PyCalc
PyScr/dicemap.py
<filename>PyScr/dicemap.py a = [[[str(i + 1) + str(j + 1) + 2 * str(k + 1) if (i != j and i != k and j != k) else ' ' for k in range(6)] for j in range(6)] for i in range(6)] b = [[[[str(i + 1) + str(j + 1) + str(k + 1) + str(l + 1) if (i != j and i != k and i != l and j != k and j != l and k != l) else ' ' for ...
MarcusTL12/PyCalc
PyScr/jsonparse.py
import os def parse(filename): with open(filename, "r") as i, open("tempjson.py", "w") as o: o.write("a = ") for l in i: o.write(l.replace("true", "True").replace("false", "False").replace("null", "None")) import tempjson os.remove("tempjson.py") return tempjson.a
MarcusTL12/PyCalc
test.py
import PyScr.jsonparse as json # import json import time t1 = time.time() # a = json.load(open("enemies.json", "r")) a = json.parse("enemies.json") t2 = time.time() print(t2 - t1) print(a[0]["randomshit"])
MarcusTL12/PyCalc
PyScr/pfprint.py
import numpy as np import copy from pprint import pprint from fractions import Fraction frac = True denom_lim = 100000 num_dec = 12 def toFrac(arg): return Fraction(arg).limit_denominator(denom_lim) def chkFrac(fra, arg): return abs(float(fra) - arg) < 10**(-14) def floatformat(arg): if frac: fra = toFrac(a...