repo_name stringlengths 6 97 | path stringlengths 3 341 | text stringlengths 8 1.02M |
|---|---|---|
bikramlmsl/epiphany | core/src/epicli/cli/engine/providers/any/InfrastructureConfigCollector.py | from cli.helpers.Step import Step
from cli.helpers.doc_list_helpers import select_single
class InfrastructureConfigCollector(Step):
def __init__(self, docs):
super().__init__(__name__)
self.cluster_model = select_single(docs, lambda x: x.kind == 'epiphany-cluster')
self.docs = docs
d... |
bikramlmsl/epiphany | core/src/epicli/tests/cli/engine/providers/test_provider_class_loader_any.py | <gh_stars>100-1000
from cli.engine.providers.provider_class_loader import provider_class_loader
from cli.engine.providers.any.InfrastructureBuilder import InfrastructureBuilder
from cli.engine.providers.any.APIProxy import APIProxy
from cli.engine.providers.any.InfrastructureConfigCollector import InfrastructureConfigC... |
bikramlmsl/epiphany | core/src/epicli/cli/engine/providers/provider_class_loader.py | import importlib
def provider_class_loader(provider, class_name):
try:
return getattr(importlib.import_module('cli.engine.providers.' + provider.lower() + '.' + class_name), class_name)
except:
raise Exception('No ' + class_name + ' for ' + provider)
|
bikramlmsl/epiphany | tools/file_hash_generator/directory_hash.py | import os
import hashlib
import logging
import argparse
import time
BLOCK_SIZE = 65536
def hash_factory(hash_algorithm):
if hash_algorithm == "sha256":
return hashlib.sha256()
if hash_algorithm == "sha512":
return hashlib.sha512()
raise NotImplementedError
def file_hash(file_path, has... |
bikramlmsl/epiphany | core/src/epicli/cli/engine/DeleteEngine.py | <reponame>bikramlmsl/epiphany
import os
import shutil
from cli.helpers.Step import Step
from cli.helpers.Config import Config
from cli.helpers.build_saver import MANIFEST_FILE_NAME, TERRAFORM_OUTPUT_DIR
from cli.helpers.data_loader import load_yamls_file
from cli.helpers.doc_list_helpers import select_single
from cli.... |
bikramlmsl/epiphany | core/src/epicli/cli/helpers/config_merger.py | <reponame>bikramlmsl/epiphany<filename>core/src/epicli/cli/helpers/config_merger.py<gh_stars>1-10
from cli.helpers.doc_list_helpers import select_first
from cli.helpers.data_loader import load_all_yaml_objs, types
from cli.helpers.objdict_helpers import merge_objdict
from cli.version import VERSION
def merge_with_def... |
bikramlmsl/epiphany | core/src/epicli/tests/cli/engine/providers/test_provider_class_loader_aws.py | from cli.engine.providers.provider_class_loader import provider_class_loader
from cli.engine.providers.aws.InfrastructureBuilder import InfrastructureBuilder
from cli.engine.providers.aws.APIProxy import APIProxy
from cli.engine.providers.aws.InfrastructureConfigCollector import InfrastructureConfigCollector
def test... |
Casmic210/02-Text-Adventure | main.py | <reponame>Casmic210/02-Text-Adventure
#!/usr/bin/env python3
import sys, os, json
# Check to make sure we are running the correct version of Python
assert sys.version_info >= (3,7), "This script requires at least Python 3.7"
# The game and item description files (in the same folder as this script)
game_file = 'game.js... |
JamesNgo3781/vietocr | vietocr/model/trainer.py | from vietocr.optim.optim import ScheduledOptim
from vietocr.optim.labelsmoothingloss import LabelSmoothingLoss
from torch.optim import Adam, SGD, AdamW
from torch import nn
from vietocr.tool.translate import build_model
from vietocr.tool.translate import translate, batch_translate_beam_search
from vietocr.tool.utils im... |
JamesNgo3781/vietocr | vietocr/model/cnn.py | <filename>vietocr/model/cnn.py
import torch
from torch import nn
import vietocr.model.vgg as vgg
from vietocr.model.resnet import Resnet50
from vietocr.model.resnet_fpn import resnet_fpn
class CNN(nn.Module):
def __init__(self, backbone, **kwargs):
super(CNN, self).__init__()
if backbone == 'vgg1... |
JamesNgo3781/vietocr | vietocr/model/transformer.py | from einops import rearrange
from torchvision import models
import math
import torch
from torch import nn
class LanguageTransformer(nn.Module):
def __init__(self, vocab_size,
d_model, nhead,
num_encoder_layers, num_decoder_layers,
dim_feedforward, max_seq_lengt... |
JamesNgo3781/vietocr | vietocr/model/transformerocr.py | <filename>vietocr/model/transformerocr.py
from vietocr.model.cnn import CNN
from vietocr.model.transformer import LanguageTransformer
from torch import nn
class VietOCR(nn.Module):
def __init__(self, vocab_size,
backbone,
cnn_args,
transformer_args):
... |
JamesNgo3781/vietocr | vietocr/tool/visualizer.py | <gh_stars>1-10
from vietocr.tool.translate import translate
def visualize(model, vocab, gen, sample=30):
pred_sents = []
actual_sents = []
img_files = []
n = 0
for batch in valid_loader.gen(sample):
translated_sentence = translate(batch['img'], model)
pred_sent = vocab.batch_decode(translated_s... |
JamesNgo3781/vietocr | vietocr/model/resnet_fpn.py | import torch
from torch import nn
from torchvision.models.detection.backbone_utils import resnet_fpn_backbone
class resnet_fpn(nn.Module):
def __init__(self, backbone):
super().__init__()
backbone = resnet_fpn_backbone(backbone, pretrained=True)
for n, p in backbone.named_parameters... |
Saad848/keywordextractor | key.py | <filename>key.py<gh_stars>1-10
# 13/09/2020 OOP practice number one working with class. making keword stracting app
import sys
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from rake_nltk import Metric,Rake
class Key():
def __init__(self):
self.win_title = 'KEYWORD Ve... |
GH920/Improve-Medical-Image-Classification-with-GAN | codes/tsne_plot.py | # %% --------------------------------------- Load Packages -------------------------------------------------------------
import numpy as np
import matplotlib.pyplot as plt
from sklearn.manifold import TSNE
from tensorflow.keras.models import load_model
# %% --------------------------------------- Load Models ---------... |
GH920/Improve-Medical-Image-Classification-with-GAN | codes/fid_score.py | # %% --------------------------------------- Load Packages -------------------------------------------------------------
import numpy as np
from numpy import cov
from numpy import trace
from numpy import iscomplexobj
from numpy import asarray
from numpy.random import shuffle
from scipy.linalg import sqrtm
from tensorfl... |
GH920/Improve-Medical-Image-Classification-with-GAN | codes/tsne_feature_resnet.py | <reponame>GH920/Improve-Medical-Image-Classification-with-GAN<filename>codes/tsne_feature_resnet.py
# %% --------------------------------------- Load Packages -------------------------------------------------------------
import os
import random
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
... |
GH920/Improve-Medical-Image-Classification-with-GAN | codes/improved_bagan_gp.py | <reponame>GH920/Improve-Medical-Image-Classification-with-GAN
# %% --------------------------------------- Load Packages -------------------------------------------------------------
import os
import random
import cv2
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
import tensorflow.keras.bac... |
GH920/Improve-Medical-Image-Classification-with-GAN | codes/fetch_data.py | # %% --------------------------------------- Load Packages -------------------------------------------------------------
import os
import numpy as np
import cv2
from sklearn.preprocessing import LabelEncoder
from sklearn.model_selection import train_test_split
# %% --------------------------------------- Data Prep ---... |
yatselin/VK-API-sandbox | alert_service.py | <reponame>yatselin/VK-API-sandbox
import os
import requests
import time
from dotenv import load_dotenv
from twilio.rest import Client
load_dotenv()
def get_status(user_id):
params = {
"user_ids": user_id,
"v": 5.122,
"fields": "online",
"access_token": os.getenv('ACCESS_TOKEN')
... |
victorbenichoux/ticktock | ticktock/renderers.py | import abc
import logging
import os
from typing import TYPE_CHECKING, List
from ticktock.utils import _TockName
if TYPE_CHECKING:
from ticktock.clocks import Clock
from ticktock.data import AggregateTimes
logger = logging.getLogger("ticktock.renderers")
class AbstractRenderer(abc.ABC):
def render(self... |
victorbenichoux/ticktock | setup.py | import setuptools
setuptools.setup(
version="0.1.2"
)
|
victorbenichoux/ticktock | ticktock/collection.py | <filename>ticktock/collection.py
import atexit
import logging
import time
import weakref
from typing import TYPE_CHECKING, Dict, Optional
import psutil
if TYPE_CHECKING:
from ticktock.renderers import AbstractRenderer
from ticktock.clocks import Clock
from ticktock.std import StandardRenderer
from ticktock.u... |
DominicBurkart/wikipedia-revisions-scraper | wikipedia_revisions/write_to_files.py | <reponame>DominicBurkart/wikipedia-revisions-scraper
import bz2
import csv
import fcntl
import math
import os
from concurrent.futures import ProcessPoolExecutor, wait, FIRST_COMPLETED
from typing import Callable, Iterable, Dict, List, Optional
import time
import dill
from wikipedia_revisions import config, FIELDS
fro... |
DominicBurkart/wikipedia-revisions-scraper | wikipedia_revisions/download.py | <reponame>DominicBurkart/wikipedia-revisions-scraper
import bz2
import errno
import hashlib
import os
import platform
import re
import threading
import time
import traceback
import xml.etree.ElementTree as ET
from typing import Optional, Dict, Generator, Iterable, Callable, Set
import click
import requests
from wikip... |
DominicBurkart/wikipedia-revisions-scraper | wikipedia_revisions/utils.py | <filename>wikipedia_revisions/utils.py
import datetime
import dill
def timestr() -> str:
return datetime.datetime.now().isoformat()
def run_dilled_function(dilled_function: bytes):
try:
f = dill.loads(dilled_function)
res = f()
return res
except Exception as e:
import tr... |
DominicBurkart/wikipedia-revisions-scraper | setup.py | from setuptools import setup
setup(
name="wikipedia_revisions",
version="0.1",
description="Download every wikipedia edit.",
author="<NAME>",
author_email="@DominicBurkart",
packages=["wikipedia_revisions"],
license="BSD-3-Clause",
install_requires=[
"requests==2.23.0",
... |
DominicBurkart/wikipedia-revisions-scraper | wikipedia_revisions/write_to_database.py | <reponame>DominicBurkart/wikipedia-revisions-scraper
import concurrent.futures
import time
import traceback
from concurrent.futures import (
ProcessPoolExecutor,
ThreadPoolExecutor,
wait,
FIRST_COMPLETED,
)
from typing import Dict, Tuple, Iterable, Callable
import dill
from dateutil.parser import parse... |
DominicBurkart/wikipedia-revisions-scraper | wikipedia_revisions/test.py | <gh_stars>0
import os
import functools
import bz2
import wikipedia_revisions
import wikipedia_revisions.download as download
def populate_config():
date = "20200601"
wikipedia_revisions.config["date"] = date
wikipedia_revisions.config[
"dump_page_url"
] = f"https://dumps.wikimedia.org/enwiki/... |
DominicBurkart/wikipedia-revisions-scraper | wikipedia_revisions/__init__.py | import dill
dill.settings["recurse"] = True
config = dict()
FIELDS = [
"id",
"parent_id",
"page_title",
"contributor_id",
"contributor_name",
"contributor_ip",
"timestamp",
"text",
"comment",
"page_id",
"page_ns",
]
|
KRunchPL/script_args_parser | tests/common_fixtures.py | <filename>tests/common_fixtures.py
"""
Provides fixtures common for different test modules.
"""
import os
from collections.abc import Generator
import pytest
from script_args_parser.arguments import Argument
@pytest.fixture
def arguments_definition_with_env(arguments_definition: list[Argument], env_var_name: str) -... |
KRunchPL/script_args_parser | tests/test_getting_attribute_value.py | import os
from tempfile import NamedTemporaryFile
import pytest
import toml
from script_args_parser import ArgumentsParser
@pytest.fixture
def toml_file_path():
mappings = {
'first_arg': {
'type': 'str',
'description': 'Some fancy description',
'cli_arg': '--cli-optio... |
KRunchPL/script_args_parser | tests/test_list.py | import os
import pytest
from script_args_parser import ArgumentsParser
from script_args_parser.arguments import ListArgument
from tests.common_fixtures import * # noqa: F401, F403
@pytest.fixture
def env_var_name():
return 'UT_LIST_ENV_VALUE'
@pytest.fixture
def arguments_definition():
return [ListArgume... |
KRunchPL/script_args_parser | tests/test_list_of_tuples.py | <filename>tests/test_list_of_tuples.py
import os
import pytest
from script_args_parser import ArgumentsParser
from script_args_parser.arguments import ListOfTuplesArgument
from tests.common_fixtures import * # noqa: F401, F403
@pytest.fixture
def env_var_name():
return 'UT_LIST_TUPLES_ENV_VALUE'
@pytest.fixt... |
KRunchPL/script_args_parser | tests/test_loading_user_values.py | <reponame>KRunchPL/script_args_parser
import os
from tempfile import NamedTemporaryFile
import pytest
import toml
import yaml
from script_args_parser import ArgumentsParser
@pytest.fixture
def toml_file_path():
mappings = {
'first_arg': {
'type': 'str',
'description': 'Some fancy... |
KRunchPL/script_args_parser | script_args_parser/arguments.py | <gh_stars>0
"""
Defines arguments' types.
"""
import re
import shlex
from copy import deepcopy
from dataclasses import asdict, dataclass
from itertools import chain
from pathlib import Path
from typing import Any, Callable, Optional, Type, Union
def _split_string_by_semicolon(argument_value: str) -> list[Any]:
if... |
KRunchPL/script_args_parser | logging_setup.py | """
Logging configuration used in example.
"""
from logging.config import dictConfig
def setup_logging() -> None:
"""
Set up logging, so library emited logs are shown on console.
"""
dictConfig({
'version': 1,
'formatters': {
'detailed': {
'class': 'logging.... |
KRunchPL/script_args_parser | tests/test_string.py | <reponame>KRunchPL/script_args_parser
import os
import pytest
from script_args_parser import ArgumentsParser
from script_args_parser.arguments import Argument
from tests.common_fixtures import * # noqa: F401, F403
@pytest.fixture
def env_var_name():
return 'UT_STRING_ENV_VALUE'
@pytest.fixture
def arguments_... |
KRunchPL/script_args_parser | tests/test_path.py | <filename>tests/test_path.py<gh_stars>0
import os
from pathlib import Path
import pytest
from script_args_parser import ArgumentsParser
from script_args_parser.arguments import PathArgument
from tests.common_fixtures import * # noqa: F401, F403
@pytest.fixture
def env_var_name():
return 'UT_PATH_ENV_VALUE'
@... |
KRunchPL/script_args_parser | tests/test_bool.py | <gh_stars>0
import os
import pytest
from script_args_parser import ArgumentsParser
from script_args_parser.arguments import Argument
from tests.common_fixtures import * # noqa: F401, F403
@pytest.fixture
def env_var_name():
return 'UT_BOOL_ENV_VALUE'
@pytest.fixture
def arguments_definition():
return [Ar... |
KRunchPL/script_args_parser | tests/test_tuple.py | <filename>tests/test_tuple.py
import os
import pytest
from script_args_parser import ArgumentsParser
from script_args_parser.arguments import TupleArgument
from tests.common_fixtures import * # noqa: F401, F403
@pytest.fixture
def env_var_name():
return 'UT_TUPLE_ENV_VALUE'
@pytest.fixture
def arguments_defi... |
KRunchPL/script_args_parser | tests/test_switch.py | <filename>tests/test_switch.py
import os
import pytest
from script_args_parser import ArgumentsParser
from script_args_parser.arguments import SwitchArgument
from tests.common_fixtures import * # noqa: F401, F403
@pytest.fixture
def env_var_name():
return 'UT_SWITCH_ENV_VALUE'
@pytest.fixture
def arguments_d... |
KRunchPL/script_args_parser | tests/test_required.py | import os
from tempfile import NamedTemporaryFile
import pytest
import toml
from script_args_parser import ArgumentsParser
@pytest.fixture
def toml_file_path_required():
mappings = {
'first_arg': {
'type': 'str',
'description': 'Some fancy description',
'cli_arg': '--... |
KRunchPL/script_args_parser | tests/test_parsing_arguments_definitions.py | <reponame>KRunchPL/script_args_parser
import os
from dataclasses import asdict
from tempfile import NamedTemporaryFile
import pytest
import toml
from script_args_parser import ArgumentsParser
def assert_argument_values(name, mapping_dict, argument_dict):
assert name == argument_dict['name']
for k, v in mapp... |
KRunchPL/script_args_parser | tests/test_integer.py | <filename>tests/test_integer.py
import os
import pytest
from script_args_parser import ArgumentsParser
from script_args_parser.arguments import IntArgument
from tests.common_fixtures import * # noqa: F401, F403
@pytest.fixture
def env_var_name():
return 'UT_INTEGER_ENV_VALUE'
@pytest.fixture
def arguments_de... |
KRunchPL/script_args_parser | script_args_parser/decorators.py | <reponame>KRunchPL/script_args_parser<filename>script_args_parser/decorators.py<gh_stars>0
"""
Decorators that helps defining argument types.
"""
from typing import Any, Type, Union
from script_args_parser.arguments import CUSTOM_TYPES_MAPPING
def dataclass_argument(decorated: Type[Any]) -> Type[Any]:
"""
Re... |
KRunchPL/script_args_parser | script_args_parser/parser.py | """
Defines parser class.
"""
import os
from argparse import ArgumentParser
from pathlib import Path
from typing import Any, Optional, Union
import toml
import yaml
from script_args_parser.arguments import Argument, argument_factory
class ArgumentsParser:
"""
Parses arguments according to given toml definit... |
KRunchPL/script_args_parser | script_args_parser/__init__.py | <reponame>KRunchPL/script_args_parser
from .arguments import CUSTOM_ARGUMENTS_TYPES, CUSTOM_TYPES_MAPPING
from .decorators import dataclass_argument
from .parser import ArgumentsParser
__all__ = [
'ArgumentsParser',
'CUSTOM_ARGUMENTS_TYPES',
'CUSTOM_TYPES_MAPPING',
'dataclass_argument',
]
|
KRunchPL/script_args_parser | example.py | """
Usage example.
"""
from dataclasses import dataclass
from script_args_parser import ArgumentsParser, dataclass_argument
@dataclass_argument
@dataclass
class MyDataClass:
"""
Example dataclass used as argument.
"""
value_1: str
value_2: str
parser = ArgumentsParser.from_files('example-para... |
KRunchPL/script_args_parser | tests/test_dataclass_argument.py | <filename>tests/test_dataclass_argument.py<gh_stars>0
from dataclasses import dataclass
import pytest
from script_args_parser.arguments import ListArgument
from script_args_parser.decorators import dataclass_argument
from script_args_parser.parser import Argument, ArgumentsParser
@dataclass_argument
@dataclass
clas... |
GPr1me/ObjectDetection | hello_world.py | <gh_stars>0
msg = 'Hello world'
print(msg)
input() |
shi510/ffem-anti-spoofing | generate_bbox/main.py | <filename>generate_bbox/main.py
import argparse
import os
import celeba_spoof
parser = argparse.ArgumentParser()
sub_parser = parser.add_subparsers(dest='cmd')
celeba_spoof_parser = sub_parser.add_parser('celeba_spoof')
celeba_spoof_parser.add_argument('--dir')
if __name__ == '__main__':
args = parser.parse_ar... |
shi510/ffem-anti-spoofing | train/main.py | import os
import train.utils as utils
import train.input_pipeline as input_pipeline
import train.config
from train.callbacks import LossTensorBoard
import net_arch.models
import train.blocks
import tensorflow as tf
def build_dataset(config):
train_ds = input_pipeline.make_tfdataset(
config['train_file']... |
shi510/ffem-anti-spoofing | train/utils.py | import base64
import csv
import importlib
import json
import os
import struct
import numpy as np
import tensorflow as tf
from tensorboard.plugins import projector
def open_config_file(file_path):
with open(file_path, 'r') as f:
file = json.load(f)
return file
def get_model(model_type):
as_file ... |
shi510/ffem-anti-spoofing | train/callbacks.py | <reponame>shi510/ffem-anti-spoofing<filename>train/callbacks.py
import os
import tensorflow as tf
from tensorflow.python.keras import backend as K
class LossTensorBoard(tf.keras.callbacks.Callback):
"""
This callback writes loss and learning rate.
"""
def __init__(self, update_freq, log_dir='./logs')... |
shi510/ffem-anti-spoofing | train/input_pipeline.py | <filename>train/input_pipeline.py<gh_stars>0
import os
import tensorflow as tf
import tensorflow_addons as tfa
import train.utils as utils
TF_AUTOTUNE = tf.data.experimental.AUTOTUNE
def random_flip(x: tf.Tensor):
return tf.image.random_flip_left_right(x)
def random_color(x: tf.Tensor):
x = tf.image.ran... |
shi510/ffem-anti-spoofing | net_arch/models.py | <filename>net_arch/models.py
import net_arch.mobilenet_v2
import net_arch.mobilenet_v3
import net_arch.efficient_net
import tensorflow as tf
model_list = {
"MobileNetV2": net_arch.mobilenet_v2.MobileNetV2,
"MobileNetV3": net_arch.mobilenet_v3.MakeMobileNetV3,
"EfficientNetB3": net_arch.efficient_net.Effic... |
shi510/ffem-anti-spoofing | generate_bbox/celeba_spoof.py | <gh_stars>0
import json
import os
from PIL import Image
def read_bbox_from_file(bbox_file):
if not os.path.exists(bbox_file):
return None
with open(bbox_file, 'r') as f:
line = f.readline()
data = line.split(' ')
if len(line) == 0:
return None
return data[0:4]
def... |
shi510/ffem-anti-spoofing | net_arch/mobilenet_v2.py | import tensorflow as tf
def MobileNetV2(shape):
model = tf.keras.applications.MobileNetV2(
input_shape=shape,
classifier_activation=None,
include_top=False,
weights=None)
return model |
shi510/ffem-anti-spoofing | net_arch/efficient_net.py | <filename>net_arch/efficient_net.py
import tensorflow as tf
def EfficientNetB3(shape):
model = tf.keras.applications.EfficientNetB3(
input_shape=shape,
classifier_activation=None,
include_top=False,
weights=None)
return model |
shi510/ffem-anti-spoofing | train/config.py | config = {
#
# Save trained model named with 'model_name'.h5.
# The best model at each epoch is saved to the folder ./checkpoint/'model_name'.
#
'model_name': 'MobileNetV3_face_spoof_gavg',
#
# Restore trained weights.
# The architecture must be same with 'model' option.
# checkpoin... |
shi510/ffem-anti-spoofing | train/blocks.py | import tensorflow as tf
def attach_GNAP(x : tf.Tensor):
out = x
norm = tf.norm(out, ord=2, axis=3, keepdims=True)
norm = tf.math.maximum(norm, 1e-12)
mean = tf.math.reduce_mean(norm)
out = tf.keras.layers.BatchNormalization(scale=False)(out)
out = tf.math.divide(out, norm)
out = tf.multipl... |
essiequoi/cifar5 | project/lit_image_classifier.py | from argparse import ArgumentParser
import os
import torch
import pytorch_lightning as pl
from torchmetrics import functional as PLF
from torch.nn import functional as F
from flash.image import ImageClassificationData
from torchvision import models
import numpy as np
class LitClassifier(pl.LightningModule):
def ... |
withwind8/HTTPretty | tests/unit/test_http.py | <reponame>withwind8/HTTPretty<filename>tests/unit/test_http.py<gh_stars>1000+
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from httpretty.http import parse_requestline
def test_parse_request_line_connect():
("parse_requestline should parse the CONNECT method appropriately"... |
withwind8/HTTPretty | tests/functional/test_passthrough.py | # <HTTPretty - HTTP client mock for Python>
# Copyright (C) <2011-2020> <NAME> <<EMAIL>>
#
# 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 ... |
withwind8/HTTPretty | httpretty/__init__.py | # #!/usr/bin/env python
# -*- coding: utf-8 -*-
# <HTTPretty - HTTP client mock for Python>
# Copyright (C) <2011-2020> <NAME> <<EMAIL>>
#
# 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 with... |
withwind8/HTTPretty | tests/functional/bugfixes/test_tornado_bind_unused_port.py | import httpretty
from unittest import skip
from tornado.testing import bind_unused_port
@skip('')
@httpretty.activate(allow_net_connect=True)
def test_passthrough_binding_socket():
# issue #247
result = bind_unused_port()
result.should.be.a(tuple)
result.should.have.length_of(2)
socket, port = r... |
withwind8/HTTPretty | docs/source/conf.py | <filename>docs/source/conf.py
# -*- coding: utf-8 -*-
import sys
import sphinx_rtd_theme
try:
from pathlib2 import Path
except ImportError:
from pathlib import Path
project_path = Path(__file__).absolute().parent.joinpath('../..')
sys.path.insert(0, project_path.as_posix())
from httpretty.version import ver... |
withwind8/HTTPretty | tests/functional/test_bypass.py | # #!/usr/bin/env python
# -*- coding: utf-8 -*-
# <httpretty - HTTP client mock for Python>
# Copyright (C) <2011-2020> <NAME> <<EMAIL>>
#
# 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 wit... |
withwind8/HTTPretty | tests/functional/bugfixes/test_eventlet.py | import httpretty
import requests
import eventlet
eventlet.monkey_patch(all=False, socket=True)
@httpretty.activate
def test_something():
httpretty.register_uri(httpretty.GET, 'https://example.com', body='foo')
requests.get('https://example.com').text.should.equal('foo')
|
withwind8/HTTPretty | tests/functional/bugfixes/test_242_ssl_bad_handshake.py | import httpretty
import requests
@httpretty.activate
def test_test_ssl_bad_handshake():
# Reproduces https://github.com/gabrielfalcao/HTTPretty/issues/242
url_http = 'http://httpbin.org/status/200'
url_https = 'https://github.com/gabrielfalcao/HTTPretty'
httpretty.register_uri(httpretty.GET, url_htt... |
withwind8/HTTPretty | tests/compat.py | <gh_stars>1000+
try:
from unittest.mock import Mock, patch, call, MagicMock
except ImportError:
from mock import Mock, patch, call, MagicMock
|
lwhjon/repo-labels-cli | utilities/config.py | """
This module handles environmental variables
"""
import os
from dotenv import load_dotenv
load_dotenv()
# GitHub credentials
GITHUB_USERNAME = os.getenv('GITHUB_USERNAME')
GITHUB_PERSONAL_ACCESS_TOKEN = os.getenv('GITHUB_PERSONAL_ACCESS_TOKEN')
|
lwhjon/repo-labels-cli | importers/base_importer.py | <gh_stars>1-10
"""
This module contains the BaseImporter Abstract class which all other importers are inherited from.
"""
from abc import ABC, abstractmethod
from utilities.constants import ImportModes
class BaseImporter(ABC):
def __init__(self, link, loaded_json_data):
self.link = link
self.jso... |
lwhjon/repo-labels-cli | utilities/constants.py | <filename>utilities/constants.py
from enum import Enum
class ImportModes(Enum):
IMPORT_LABELS = 'IMPORT'
DEL_ALL_LABELS = 'DEL_ALL_LABELS'
|
lwhjon/repo-labels-cli | extractors/base_extractor.py | <reponame>lwhjon/repo-labels-cli
"""
This module contains the BaseExtractor Abstract class which all other extractors are inherited from.
"""
from abc import ABC, abstractmethod
class BaseExtractor(ABC):
def __init__(self, link):
self.link = link
self.repo_owner = None
self.repo_name = No... |
lwhjon/repo-labels-cli | importers/github_importer.py | <filename>importers/github_importer.py
"""
This module contains the importer for GitHub.
GitHub: https://github.com/
"""
import asyncio
import logging
import os
import aiohttp
from aiohttp import BasicAuth
from extractors.github_extractor import GitHubExtractor
from importers.base_importer import BaseImporter
from ut... |
lwhjon/repo-labels-cli | repolabels.py | <filename>repolabels.py
"""
This module contains the main command line interface.
"""
import argparse
import json
import re
import sys
import logging
from pathlib import Path
from utilities.cli_utils import open_link, run_extractor, format_url, run_importer, rate_limits, validate_url, \
check_updates
from utiliti... |
lwhjon/repo-labels-cli | __main__.py | import repolabels
if __name__ == "__main__":
repolabels.main()
|
lwhjon/repo-labels-cli | test/test_cli_utils.py | import argparse
from utilities.cli_utils import open_link, remove_url_trailing_slash, format_url, run_extractor
from unittest import TestCase
from unittest.mock import patch
class Test(TestCase):
@patch('webbrowser.open')
def test_open_link_success(self, mock_web_browser_open):
args = argparse.Names... |
lwhjon/repo-labels-cli | utilities/cli_utils.py | """
This module contains the command line interface (cli) utility methods
"""
import asyncio
import aiohttp
import logging
import os
import webbrowser
import validators
from pathlib import Path
from utilities.extractor_facade import ExtractorFacade
from utilities.importer_facade import ImporterFacade
from urllib.pars... |
lwhjon/repo-labels-cli | utilities/importer_facade.py | """
This module contains the ImporterFacade which calls the appropriate method from the appropriate classes
based on the parameter passed.
"""
import logging
from urllib.parse import urlparse
from exceptions.general_exceptions import SiteNotSupported
from importers.github_importer import GitHubImporter
logger = logg... |
lwhjon/repo-labels-cli | exceptions/general_exceptions.py | <reponame>lwhjon/repo-labels-cli
"""
This module contains the exceptions that are commonly used.
"""
class SiteNotSupported(Exception):
def __init__(self, hostname):
self.message = f"SiteNotSupported: {hostname} Repository host not supported."
|
lwhjon/repo-labels-cli | extractors/github_extractor.py | """
This module contains the extractor for GitHub.
GitHub: https://github.com/
"""
import json
import os
import aiohttp
import asyncio
import logging
from aiohttp import BasicAuth
from bs4 import BeautifulSoup
from datetime import datetime
from extractors.base_extractor import BaseExtractor
from utilities.config imp... |
lwhjon/repo-labels-cli | utilities/extractor_facade.py | """
This module contains the ExtractorFacade which calls the appropriate method from the appropriate classes
based on the parameter passed.
"""
import logging
from urllib.parse import urlparse
from exceptions.general_exceptions import SiteNotSupported
from extractors.github_extractor import GitHubExtractor
logger = ... |
catman85/Python-Image-Download-from-Link | urlmorf.py | <gh_stars>0
import sys
import os
def main():
filepath = sys.argv[1]
if not os.path.isfile(filepath):
print("File path {} does not exist. Exiting...".format(filepath))
sys.exit()
with open(filepath) as fp:
for line in fp:
# if line == " ":
# break
url = ... |
rigzba21/kubespawner | docs/source/conf.py | import os
import sys
from os.path import dirname
# For conversion from markdown to html
# set paths
docs = dirname(dirname(__file__))
root = dirname(docs)
sys.path.insert(0, root)
sys.path.insert(0, os.path.join(docs, 'sphinxext'))
# -- General configuration ------------------------------------------------
extensions... |
rigzba21/kubespawner | kubespawner/proxy.py | import asyncio
import json
import os
import string
import escapism
from jupyterhub.proxy import Proxy
from jupyterhub.utils import exponential_backoff
from kubernetes_asyncio import client
from traitlets import Unicode
from .clients import load_config
from .clients import shared_client
from .objects import make_ingre... |
1stResponder/pi-loc | gps_data.py | <reponame>1stResponder/pi-loc<gh_stars>0
"""Sample Main File to Poll GPS"""
import os
import time
from gps_poll import GpsPoller
if __name__ == '__main__':
GPSP = GpsPoller()
try:
GPSP.start()
while True:
os.system('clear')
REPORT = GPSP.get_current_value()
#... |
1stResponder/pi-loc | logger.py | <gh_stars>0
"""This module uploads logs to S3"""
import subprocess
import datetime
import boto
from boto.s3.key import Key
# You will need to fill out your own details here for logging
S3 = boto.connect_s3('<aws access key>', '<aws secret key>')
BUCKETNAME = 'BUCKETNAME'
BUCKET = S3.get_bucket(BUCKETNAME, validate=Tr... |
1stResponder/pi-loc | gps_poll.py | <reponame>1stResponder/pi-loc
"""GPS Library Handler"""
import threading
from gps import *
#from time import *
class GpsPoller(threading.Thread):
"""GPS Class for Pythong"""
def __init__(self):
threading.Thread.__init__(self)
self.session = gps(mode=WATCH_ENABLE)
self.current_value = N... |
1stResponder/pi-loc | main.py | """This module does blah blah."""
import ConfigParser
import os
import time
import logging
import logging.handlers
import sys
import requests
from gps_poll import GpsPoller
from edxlde_util import generate_de
if __name__ == '__main__':
GPSP = GpsPoller()
CONFIG = ConfigParser.RawConfigParser()
CONFIG.read(... |
1stResponder/pi-loc | gps_test.py | <reponame>1stResponder/pi-loc
from gps import *
from pi_helper import *
session = gps()
session.stream(WATCH_ENABLE|WATCH_NEWSTYLE)
table_service=connect_to_service()
MAX = 200
oldLat = None
oldLon = None
while True:
for i in range(MAX):
time.sleep(1.0)
report = session.next()
if repo... |
1stResponder/pi-loc | edxlde_util.py | <reponame>1stResponder/pi-loc<gh_stars>0
"""Python Utilities for EDXL-DE"""
import xml.etree.ElementTree as ET
import ConfigParser
import datetime
from datetime import timedelta
def generate_de(lat, lon):
"""Generates a DE Message"""
config = ConfigParser.RawConfigParser()
config.read('config.cfg')
uni... |
fortyninemaps/picoraster | src/band.py | import itertools
import numpy
from osgeo import gdal
from .geotransform import GeoTransform
from .pipeline import Pipeline
from .types import NUMPY_TO_GDT
class Band(object):
def __init__(self, source, pipeline=None):
# The pipeline describes how this band is created.
self.source = source
... |
fortyninemaps/picoraster | src/tests/__main__.py | <gh_stars>0
import unittest
from . import *
unittest.main() |
fortyninemaps/picoraster | src/tests/geotransform_tests.py | import unittest
from ..geotransform import GeoTransform
class GeotransformTests(unittest.TestCase):
def round_trip(self, t, j, i):
x, y = t.apply(j, i)
nj, ni = t.invert(x, y)
self.assertEqual((j, i), (nj, ni))
def test_north_up(self):
t = GeoTransform(1.0, 2, 0, 2.0, 0, 3)
... |
fortyninemaps/picoraster | src/types.py | import numpy
from osgeo import gdal
GDT_TO_NUMPY = {
gdal.GDT_Byte: numpy.uint8,
gdal.GDT_UInt16: numpy.uint16,
gdal.GDT_UInt32: numpy.uint32,
gdal.GDT_Int16: numpy.int16,
gdal.GDT_Int32: numpy.int32,
gdal.GDT_Float32: numpy.float32,
gdal.GDT_Float64: numpy.float64,
gdal.GDT_CFloat64: n... |
fortyninemaps/picoraster | src/geotransform.py | class GeoTransform(object):
def __init__(self, a, b, c, d, e, f):
self.a = a
self.b = b
self.c = c
self.d = d
self.e = e
self.f = f
def apply(self, j, i):
""" compute the (x, y) coordinates of the upper left corner of a cell
where the indices are... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.