repo_name
stringlengths
6
97
path
stringlengths
3
341
text
stringlengths
8
1.02M
gitter-badger/grow-controller-Rpi
main/ref/IOupdater.py
<reponame>gitter-badger/grow-controller-Rpi<filename>main/ref/IOupdater.py import settings from Adafruit_IO import Client import gpioState from datetime import datetime settings.webgui() guienable = settings.enable1 ADAFRUIT_IO_KEY = settings.key1 web = Client(ADAFRUIT_IO_KEY) settings.light() lightOn = settings.l...
Minitour/BigDataHW4
modules/twitter/top_users.py
import csv import re from urllib.request import Request, urlopen from bs4 import BeautifulSoup top, users, list_of_cells, header = 500, [], [], [] req = Request("https://socialblade.com/twitter/top/" + str(top) + "/followers", headers={'User-Agent': 'Mozilla/5.0'}) soup = BeautifulSoup(urlopen(req).read(), "lxml") [he...
Minitour/BigDataHW4
modules/spark/symbol_lookup.py
import json import requests import re url = "https://api.iextrading.com/1.0/ref-data/symbols" headers = {'cache-control': 'no-cache'} response = requests.request("GET", url, headers=headers) data = json.loads(response.text) name_symbol_map = {} symbol_name_map = {} single_words_dict = {} for company in data: sym...
Minitour/BigDataHW4
modules/twitter/users_ids.py
<filename>modules/twitter/users_ids.py import json import requests import requests_oauthlib import csv CONSUMER_KEY = 'owJ9m2q48GGYrMubsOSEyZbap' CONSUMER_SECRET = '<KEY>' ACCESS_TOKEN = '<KEY>' ACCESS_SECRET = '<KEY>' my_auth = requests_oauthlib.OAuth1(CONSUMER_KEY, CONSUMER_SECRET,ACCESS_TOKEN, ACCESS_SECRET) def...
Minitour/BigDataHW4
modules/nlp/predict.py
<gh_stars>1-10 import pickle from sklearn.externals import joblib import os from modules.nlp.vectorizer import get_features, vectorizer filename = 'model.dat' dir_path = os.path.dirname(os.path.realpath(__file__)) loaded_model = joblib.load(dir_path + '/' + filename) vocabulary_to_load = pickle.load(open(dir_path +...
Minitour/BigDataHW4
modules/spark/spark_service.py
<filename>modules/spark/spark_service.py import json from datetime import datetime import requests from pyspark import SparkConf, SparkContext from pyspark.sql import Row, SQLContext from pyspark.streaming import StreamingContext from modules.nlp.predict import predict from modules.spark.symbol_lookup import get_symb...
Minitour/BigDataHW4
modules/nlp/train.py
from sklearn import model_selection from sklearn.externals import joblib from sklearn.linear_model import LogisticRegression from sklearn.metrics import classification_report import pickle from modules.nlp.vectorizer import get_features_train, vectorizer # fetching traindata from files data = [] data_labels = [] with...
Minitour/BigDataHW4
modules/nlp/vectorizer.py
<gh_stars>1-10 import re import nltk import pickle from sklearn.feature_extraction.text import CountVectorizer from nltk.stem.porter import PorterStemmer stemmer = PorterStemmer() def stem_tokens(tokens, stemmer): stemmed = [stemmer.stem(item) for item in tokens] return (stemmed) def tokenize(text): te...
Minitour/BigDataHW4
modules/backend/app.py
<reponame>Minitour/BigDataHW4 import os from flask import Flask, jsonify, request from flask import render_template template_dir = os.path.abspath('./../frontend') print(template_dir) app = Flask(__name__, template_folder=template_dir) tweets = [] stocks = {} tweet_index = set() @app.route("/") def index(): r...
Minitour/BigDataHW4
modules/twitter/twitter_service.py
<gh_stars>1-10 import json import socket import pandas as pd import requests import requests_oauthlib # lsof -n -i | grep -e LISTEN -e ESTABLISHED # Replace the values below with yours from modules.twitter.users_ids import get_users_usernames, get_users_ids ACCESS_TOKEN = '<KEY>' ACCESS_SECRET = '<KEY>' CONSUMER_KE...
Nazg-Gul/glcew
auto/auto.py
#!/usr/bin/env python from __future__ import print_function from clang.cindex import * import os import sys ############################################################################### # List of function to wrangle. # Those functions will have regular warngler logic, based on simple function # pinter read from t...
jospint/Grep-kl06-scraper
src/script.py
<filename>src/script.py #Author <NAME> @jospint from urllib.request import urlopen import json from pathlib import Path import io BASE_URL = 'http://data.udir.no/kl06/' UTF8 = 'utf-8' def main(): #Parsing blob with all study plans norwayplans = json.load(urlopen(BASE_URL + 'laereplaner.json')) #getting information...
tomkcook/tunnel-server
src/util.py
<reponame>tomkcook/tunnel-server import subprocess import logging import netifaces as ni def command(args): logging.warning(args) result = subprocess.run( args.split(" "), stdout=subprocess.PIPE, stderr=subprocess.STDOUT, encoding="utf-8") return result def startTunnel(remoteIP, localIP, b...
tomkcook/tunnel-server
src/client.py
#!/usr/bin/env python3 from argparse import ArgumentParser from util import startTunnel, stopTunnel, addressesForInterface, srcAddressForDst import logging import signal import requests import socket def main(): parser = ArgumentParser() parser.add_argument("--bridge", type=str) parser.add_argument("remot...
tomkcook/tunnel-server
src/server.py
#!/usr/bin/env python3 from flask import Flask from flask import request from util import startTunnel, stopTunnel, addressesForInterface from argparse import ArgumentParser import logging app = Flask(__name__) settings = {} @app.route("/connect") def connect(): address = request.remote_addr logging.info("Con...
leovandriel/global
cloud.py
<filename>cloud.py<gh_stars>0 from datetime import datetime, timedelta import hashlib import json import base64 import os from urllib import request, parse, error cloud_url = 'https://storage.googleapis.com' twilio_url = 'https://api.twilio.com/2010-04-01/Accounts' gov_url = 'https://ttp.cbp.dhs.gov' wait_hours = 1 m...
AliMarashian/C-Minus-Compiler-Python
testt.py
print("Salut!") print("Comment ca va?")
RakshaPRao/ARC
src/solution_29c11459.py
<filename>src/solution_29c11459.py # This file has the solution to the task 29c11459.json from ioOps import read_file, get_file_path, print_grid import json import sys """ Method to find solution for the task 29c11459.json Args: data(input): The data grid to be processed Returns: Output grid with a line of t...
RakshaPRao/ARC
src/ioOps.py
<filename>src/ioOps.py import numpy as np import json import itertools from sys import exit """ This method gets the file path from the arguments passed Args: args(str): The list of arguments passed Returns: Path to the input file """ def get_file_path(args): if len(args) <= 1: print("Please provid...
RakshaPRao/ARC
src/solution_746b3537.py
# This file has the solution to the task 746b3537.json from ioOps import read_file, get_file_path, print_grid from itertools import groupby import numpy as np import sys """ Method to find solution for the task 746b3537.json Args: data(input): The input grid to be processed Returns: The unique colour in ...
RakshaPRao/ARC
src/solution_a699fb00.py
<reponame>RakshaPRao/ARC # This file has the solution for the task a699fb00.json from ioOps import read_file, print_grid, get_file_path import json import sys """ Method to find solution for the task a699fb00.json Args: data(input): The input grid to be processed Returns: Output grid with cell filled with re...
RakshaPRao/ARC
src/solution_aabf363d.py
<reponame>RakshaPRao/ARC<gh_stars>0 # This file has the solution to the task aabf363d.json from ioOps import read_file, get_file_path, print_grid from itertools import groupby import numpy as np import sys """ Method to find solution for the task aabf363d.json Args: data(input): The input grid to be processed Re...
dnguyen0304/downloadbot.common
downloadbot_common/retry/tests/test_wait_strategies.py
<reponame>dnguyen0304/downloadbot.common # -*- coding: utf-8 -*- from nose.tools import assert_equal from .. import wait_strategies def test_fixed_wait_time(): wait_time = 1 wait_strategy = wait_strategies.Fixed(wait_time=wait_time) attempt = None output = wait_strategy.compute_wait_time(attempt=at...
dnguyen0304/downloadbot.common
downloadbot_common/messaging/consuming/deleters.py
<reponame>dnguyen0304/downloadbot.common # -*- coding: utf-8 -*- import abc class Deleter(metaclass=abc.ABCMeta): # Should this instead return the number of messages that were # deleted successfully? @abc.abstractmethod def delete(self, message): """ Delete a message from the queue....
dnguyen0304/downloadbot.common
downloadbot_common/retry/tests/test_continue_strategies.py
# -*- coding: utf-8 -*- from nose.tools import assert_false, assert_true, raises from .. import continue_strategies from ..attempt import Attempt def test_after_result_should_continue(): continue_strategy = continue_strategies.AfterResult( predicate=lambda x: x == 'foo') attempt = Attempt(number=Non...
dnguyen0304/downloadbot.common
downloadbot_common/retry/tests/test_stop_strategies.py
<reponame>dnguyen0304/downloadbot.common<gh_stars>0 # -*- coding: utf-8 -*- from nose.tools import assert_false, raises from .. import exceptions, stop_strategies from ..attempt import Attempt @raises(exceptions.MaximumRetry) def test_after_attempt_greater_than_threshold_should_stop(): maximum_attempt = 1 ...
dnguyen0304/downloadbot.common
downloadbot_common/messaging/consuming/consumers.py
# -*- coding: utf-8 -*- import abc import time from . import exceptions from downloadbot_common import io class Consumer(metaclass=abc.ABCMeta): # Should this instead raise an exception when it fails to receive # or handle a message? @abc.abstractmethod def consume(self): """ Recei...
dnguyen0304/downloadbot.common
downloadbot_common/messaging/tests/test_filters.py
<gh_stars>0 # -*- coding: utf-8 -*- import mock from nose.tools import assert_in, assert_not_in from .. import filters from .. import messages class TestLogging: def __init__(self): self.message = None self.logger = None def setup(self): self.message = messages.Message(id='', body=...
dnguyen0304/downloadbot.common
downloadbot_common/tests/test_utility.py
<filename>downloadbot_common/tests/test_utility.py # -*- coding: utf-8 -*- import json from nose.tools import assert_equal, assert_false, assert_true from .. import utility class MockException(Exception): pass class MockGetNowInSeconds: def __init__(self, start_time, next_time): """ Par...
dnguyen0304/downloadbot.common
downloadbot_common/messaging/consuming/exceptions.py
# -*- coding: utf-8 -*- from .. import exceptions class DeleteError(Exception): pass class HandleError(Exception): pass class ReceiveTimeout(exceptions.Timeout): pass
dnguyen0304/downloadbot.common
downloadbot_common/messaging/consuming/receivers.py
# -*- coding: utf-8 -*- import abc class Receiver(metaclass=abc.ABCMeta): @abc.abstractmethod def receive(self): """ Receive gets a message from the queue. Returns ------- downloadbot_common.messaging.messages.Message Raises ------ downloadb...
dnguyen0304/downloadbot.common
downloadbot_common/messaging/messages.py
<reponame>dnguyen0304/downloadbot.common<filename>downloadbot_common/messaging/messages.py<gh_stars>0 # -*- coding: utf-8 -*- class Message: def __init__(self, id, body, delivery_receipt): """ Parameters ---------- id : str Unique identifier. body : str ...
dnguyen0304/downloadbot.common
downloadbot_common/retry/stop_strategies.py
# -*- coding: utf-8 -*- import abc import time from . import exceptions class IStopStrategy(object): __metaclass__ = abc.ABCMeta @abc.abstractmethod def should_stop(self, attempt): """ Parameters ---------- attempt : clare.common.retry.attempt.Attempt Returns ...
dnguyen0304/downloadbot.common
downloadbot_common/event/messaging/broker.py
<reponame>dnguyen0304/downloadbot.common # -*- coding: utf-8 -*- import six class Broker(object): def __init__(self, observable_class): """ Parameters ---------- observable_class : clare.common.event_driven.Observable """ self._observable_class = observable_clas...
dnguyen0304/downloadbot.common
downloadbot_common/messaging/exceptions.py
# -*- coding: utf-8 -*- class Timeout(Exception): pass
dnguyen0304/downloadbot.common
downloadbot_common/retry/policy.py
# -*- coding: utf-8 -*- import abc import collections import json import sys import time import six from . import exceptions from .attempt import Attempt from downloadbot_common import io from downloadbot_common import utility class Topic(utility.AutomatedEnum): ATTEMPT_STARTED = () ATTEMPT_COMPLETED = () ...
dnguyen0304/downloadbot.common
downloadbot_common/lookup/results.py
# -*- coding: utf-8 -*- from downloadbot_common import lookup class Find(object): def __init__(self, value, zero_value): """ A generic proxy for the result of a find operation. Parameters ---------- value : object zero_value : object """ self._v...
dnguyen0304/downloadbot.common
downloadbot_common/event/tests/test_observable.py
<filename>downloadbot_common/event/tests/test_observable.py # -*- coding: utf-8 -*- import mock from nose.tools import assert_equal from .. import notifiables class MockObserver(notifiables.Notifyable): def notify(self, event): pass class TestObservable(object): def __init__(self): self....
dnguyen0304/downloadbot.common
downloadbot_common/retry/continue_strategies.py
# -*- coding: utf-8 -*- import abc class ContinueStrategy(object): __metaclass__ = abc.ABCMeta @abc.abstractmethod def should_continue(self, attempt): """ Parameters ---------- attempt : downloadbot_common.retry.attempt.Attempt Returns ------- b...
dnguyen0304/downloadbot.common
downloadbot_common/retry/tests/test_attempt.py
# -*- coding: utf-8 -*- from nose.tools import assert_equal from ..attempt import Attempt class TestAttempt(object): def __init__(self): self.attempt = None def setup(self): self.attempt = Attempt.first(_get_now_in_seconds=lambda: 0) def test_first(self): assert_equal(self.att...
dnguyen0304/downloadbot.common
downloadbot_common/event/__init__.py
<gh_stars>0 # -*- coding: utf-8 -*- from . import messaging from . import notifiables __all__ = ['messaging', 'notifiables']
dnguyen0304/downloadbot.common
downloadbot_common/retry/__init__.py
# -*- coding: utf-8 -*- from . import exceptions from . import messaging from . import stop_strategies from . import wait_strategies from .policy import Topic from .policy_builder import PolicyBuilder __all__ = ['PolicyBuilder', 'Topic', 'exceptions', 'messaging', 'stop_str...
dnguyen0304/downloadbot.common
downloadbot_common/retry/policy_builder.py
# -*- coding: utf-8 -*- from . import continue_strategies from .policy import Policy from .. import event class HookAdapter(event.notifiables.Notifyable): def __init__(self, predicate): self._predicate = predicate def notify(self, event): self._predicate(event) def __repr__(self): ...
dnguyen0304/downloadbot.common
downloadbot_common/lookup/__init__.py
# -*- coding: utf-8 -*- from . import exceptions from . import results __all__ = ['exceptions', 'results']
dnguyen0304/downloadbot.common
downloadbot_common/retry/attempt.py
# -*- coding: utf-8 -*- import time class Attempt(object): def __init__(self, number, was_successful, result, exception, first_attempt_start_time): self.number = number self.was_successful = was_successful ...
dnguyen0304/downloadbot.common
downloadbot_common/retry/wait_strategies.py
# -*- coding: utf-8 -*- import abc class IWaitStrategy(object): __metaclass__ = abc.ABCMeta @abc.abstractmethod def compute_wait_time(self, attempt): """ Parameters ---------- attempt : clare.common.retry.attempt.Attempt Returns ------- float ...
dnguyen0304/downloadbot.common
downloadbot_common/messaging/consuming/tests/test_consumers.py
# -*- coding: utf-8 -*- import mock from .. import consumers from downloadbot_common import messaging from downloadbot_common.messaging import consuming class MockReceiver(consuming.receivers.Receiver): def receive(self): raise NotImplementedError class MockHandler(consuming.handlers.Handler): d...
dnguyen0304/downloadbot.common
downloadbot_common/retry/tests/test_policy.py
<reponame>dnguyen0304/downloadbot.common # -*- coding: utf-8 -*- import json import mock from nose.tools import (assert_equal, assert_false, assert_greater, assert_in, assert_true, raises) import d...
dnguyen0304/downloadbot.common
downloadbot_common/event/messaging/__init__.py
# -*- coding: utf-8 -*- from .broker import Broker __all__ = ['Broker']
dnguyen0304/downloadbot.common
downloadbot_common/messaging/__init__.py
# -*- coding: utf-8 -*- from . import consuming from . import events from . import exceptions from . import filters from . import messages __all__ = ['consuming', 'events', 'exceptions', 'filters', 'messages']
dnguyen0304/downloadbot.common
setup.py
<reponame>dnguyen0304/downloadbot.common #!/usr/bin/env python # -*- coding: utf-8 -*- import setuptools if __name__ == '__main__': package_name = 'downloadbot_common' description = 'Common libraries for Pokemon Showdown web scrapers.' install_requires = [ # This package is needed by the library...
dnguyen0304/downloadbot.common
downloadbot_common/lookup/tests/test_results.py
<reponame>dnguyen0304/downloadbot.common<filename>downloadbot_common/lookup/tests/test_results.py # -*- coding: utf-8 -*- from nose.tools import assert_is, assert_is_none, raises from .. import exceptions from .. import results class TestFind(object): def setup(self): self.value = 'foo' self.ze...
dnguyen0304/downloadbot.common
downloadbot_common/messaging/filters.py
<filename>downloadbot_common/messaging/filters.py # -*- coding: utf-8 -*- import abc class Message(metaclass=abc.ABCMeta): @abc.abstractmethod def filter(self, message): """ Implementations may mutate the input. Parameters ---------- message : downloadbot_common.mes...
dnguyen0304/downloadbot.common
downloadbot_common/retry/exceptions.py
<reponame>dnguyen0304/downloadbot.common<filename>downloadbot_common/retry/exceptions.py<gh_stars>0 # -*- coding: utf-8 -*- class MaximumRetry(Exception): pass
dnguyen0304/downloadbot.common
downloadbot_common/__init__.py
<gh_stars>0 # -*- coding: utf-8 -*- from . import event from . import io from . import lookup from . import retry from . import utility __all__ = ['event', 'io', 'lookup', 'retry', 'utility']
dnguyen0304/downloadbot.common
downloadbot_common/messaging/consuming/handlers.py
# -*- coding: utf-8 -*- import abc class Handler(metaclass=abc.ABCMeta): @abc.abstractmethod def handle(self, message): """ Parameters ---------- message : downloadbot_common.messaging.messages.Message Returns ------- None Raises ---...
Tknika/iombian-system-info-provider
src/iombian_info_provider.py
#!/usr/bin/env python3 import logging import platform import psutil import socket import time from generic_info_provider import GenericInfoProvider logger = logging.getLogger(__name__) class IoMBianInfoProvider(GenericInfoProvider): def __init__(self): self.hostname = None self.system_time = N...
Tknika/iombian-system-info-provider
src/main.py
<filename>src/main.py #!/usr/bin/env python3 import logging import signal from iombian_info_provider import IoMBianInfoProvider from host_info_controller import HostInfoController from pub_client import PubClient logging.basicConfig(format='%(asctime)s %(levelname)-8s %(name)-20s - %(message)s', level=logging.INFO)...
Tknika/iombian-system-info-provider
src/pub_client.py
#!/usr/bin/env python3 import logging import zmq logger = logging.getLogger(__name__) class PubClient(object): def __init__(self, host="127.0.0.1", port=5557): self.host = host self.port = port self.addr = f"tcp://{self.host}:{self.port}" self.context = zmq.Context() sel...
Tknika/iombian-system-info-provider
src/host_info_controller.py
<gh_stars>0 #!/usr/bin/env python3 import logging import threading import time logger = logging.getLogger(__name__) class HostInfoController(object): def __init__(self, host_info, on_update_callback, polling_freq=5): self.host_info = host_info self.polling_freq = polling_freq self.polli...
karstenw/photobotlib
examples/imagewells/__init__.py
<gh_stars>1-10 import sys import os import io import time import datetime import unicodedata import fractions Fraction = fractions.Fraction import pdb import pprint pp = pprint.pprint kwdbg = 0 kwlog = 0 import traceback import PIL import PIL.Image as Image __all__ = ['imagewells', 'loadImageWell'] # py3 stuff p...
112roel/binb
python/write_song.py
import redis import os import json import requests from collections import defaultdict import yaml # Parameters default_limit = 8 default_room = "mixed" default_file = "test.yml" default_log = "log.json" verbose = 0 # Globals song_id = 0 track_dict = defaultdict(int) artist_log = {} ## Database meuk # Replace defaul...
112roel/binb
python/findids.py
<filename>python/findids.py import requests, time, json ##### # Made by Marc # This script uses the itunes api to find artist_ids by the names from the artistlist.txt # It might no be perfect, but it works # I'm not responsible for any damage done (lost friendships, etc) # Parameters print("which genre") genre = inpu...
112roel/binb
python/scraper.py
import requests, re from bs4 import BeautifulSoup from csv import writer folder = "output/" maxLength = 30 genre = "seventies" response = requests.get('https://top40weekly.com/top-100-artists-of-the-70s/') soup = BeautifulSoup(response.text, 'html.parser') artists = soup.find_all(class_={"artist-title"}) f = open...
0xdabbad00/aws-remediations
tests/remediations/test_aws_guardduty_create_detector.py
<filename>tests/remediations/test_aws_guardduty_create_detector.py from unittest import mock, TestCase from boto3 import Session from src.remediations.aws_guardduty_create_detector import AwsGuardDutyCreateDetector class TestAwsGuardDutyCreateDetector(TestCase): @mock.patch.object(Session, 'client') def test...
0xdabbad00/aws-remediations
src/remediations/aws_s3_block_bucket_public_access.py
from typing import Any, Dict from boto3 import Session from app import Remediation from app.remediation_base import RemediationBase @Remediation class AwsS3BlockBucketPublicAccess(RemediationBase): """Remediation that puts an S3 bucket block public access configuration""" @classmethod def _id(cls) -> s...
0xdabbad00/aws-remediations
src/remediations/aws_ddb_encrypt_table.py
from typing import Any, Dict from boto3 import Session from app import Remediation from app.remediation_base import RemediationBase @Remediation class AwsDdbEncryptTable(RemediationBase): """Remediation that creates a KMS key and uses it to encrypt DDB table""" @classmethod def _id(cls) -> str: ...
0xdabbad00/aws-remediations
tests/remediations/test_aws_s3_enable_bucket_encryption.py
from unittest import mock, TestCase from boto3 import Session from app.exceptions import InvalidParameterException from remediations.aws_s3_enable_bucket_encryption import AwsS3EnableBucketEncryption class TestAwsS3EnableBucketEncryption(TestCase): @mock.patch.object(Session, 'client') def test_fix_aes256(s...
0xdabbad00/aws-remediations
src/remediations/aws_guardduty_create_detector.py
<gh_stars>1-10 from typing import Any, Dict from boto3 import Session from app import Remediation from app.remediation_base import RemediationBase @Remediation class AwsGuardDutyCreateDetector(RemediationBase): """Remediation that creates a GuardDuty detector if one doesn't exist""" @classmethod def _i...
0xdabbad00/aws-remediations
src/remediations/aws_s3_enable_bucket_versioning.py
<gh_stars>1-10 from typing import Any, Dict from boto3 import Session from app import Remediation from app.remediation_base import RemediationBase @Remediation class AwsS3EnableBucketVersioning(RemediationBase): """Remediation that enables versioning for an S3 bucket""" @classmethod def _id(cls) -> str...
0xdabbad00/aws-remediations
tests/remediations/test_aws_ddb_encrypt_table.py
from unittest import mock, TestCase from boto3 import Session from src.remediations.aws_ddb_encrypt_table import AwsDdbEncryptTable class TestAwsDdbEncryptTable(TestCase): @mock.patch.object(Session, 'client') def test_fix(self, mock_session): mock_client = mock.Mock() mock_session.return_val...
0xdabbad00/aws-remediations
src/remediations/aws_rds_enable_auto_minor_version_upgrade.py
from typing import Any, Dict from boto3 import Session from app import Remediation from app.remediation_base import RemediationBase @Remediation class AwsRdsEnableAutoMinorVersionUpgrade(RemediationBase): """Remediation that enables Auto Minor Version upgrade for RDS instances""" @classmethod def _id(c...
0xdabbad00/aws-remediations
tests/remediations/test_aws_ec2_terminate_instance.py
<filename>tests/remediations/test_aws_ec2_terminate_instance.py from unittest import mock, TestCase from boto3 import Session from src.remediations.aws_ec2_terminate_instance import AwsEc2TerminateInstance class TestAwsEc2TerminateInstance(TestCase): @mock.patch.object(Session, 'client') def test_fix(self, m...
0xdabbad00/aws-remediations
tests/remediations/test_aws_s3_block_bucket_public_acl.py
from unittest import mock, TestCase from boto3 import Session from src.remediations.aws_s3_block_bucket_public_acl import AwsS3BlockBucketPublicACL class TestAwsS3BlockBucketPublicACL(TestCase): @mock.patch.object(Session, 'client') def test_fix(self, mock_session): mock_client = mock.Mock() ...
0xdabbad00/aws-remediations
tests/remediations/test_aws_s3_block_bucket_public_access.py
from unittest import mock, TestCase from boto3 import Session from src.remediations.aws_s3_block_bucket_public_access import AwsS3BlockBucketPublicAccess class TestAwsS3BlockBucketPublicAccessConfigurable(TestCase): @mock.patch.object(Session, 'client') def test_fix(self, mock_session): mock_client =...
0xdabbad00/aws-remediations
src/remediations/aws_iam_delete_inactive_user_keys.py
<gh_stars>1-10 from typing import Any, Dict from boto3 import Session from app import Remediation from app.remediation_base import RemediationBase @Remediation class AwsIamDeleteInactiveAccessKeys(RemediationBase): """Remediation that deletes inactive user access keys""" @classmethod def _id(cls) -> st...
0xdabbad00/aws-remediations
src/remediations/aws_s3_enable_bucket_logging.py
from typing import Any, Dict from boto3 import Session from app import Remediation from app.remediation_base import RemediationBase @Remediation class AwsS3EnableBucketLogging(RemediationBase): """Remediation that enables S3 bucket access logging""" @classmethod def _id(cls) -> str: return 'S3....
0xdabbad00/aws-remediations
tests/remediations/test_aws_rds_disable_instance_public_access.py
<reponame>0xdabbad00/aws-remediations<filename>tests/remediations/test_aws_rds_disable_instance_public_access.py from unittest import mock, TestCase from boto3 import Session from src.remediations.aws_rds_disable_instance_public_access import AwsRdsDisableInstancePublicAccess class TestAwsRdsDisableInstancePublicAcce...
0xdabbad00/aws-remediations
src/remediations/aws_iam_update_account_password_policy.py
<reponame>0xdabbad00/aws-remediations<gh_stars>1-10 from typing import Any, Dict from boto3 import Session from app import Remediation from app.remediation_base import RemediationBase @Remediation class AwsIamUpdateAccountPasswordPolicy(RemediationBase): """Remediation that updates the Account password policy t...
0xdabbad00/aws-remediations
src/app/logging.py
<reponame>0xdabbad00/aws-remediations import logging import os def get_logger() -> logging.Logger: """Utility method to get a properly configured logger instance""" level = os.environ.get('LOGGING_LEVEL', 'INFO') logging.basicConfig(format='[%(levelname)s %(asctime)s (%(name)s:%(lineno)d)]: %(message)s'...
0xdabbad00/aws-remediations
src/remediations/aws_s3_block_bucket_public_acl.py
<reponame>0xdabbad00/aws-remediations<filename>src/remediations/aws_s3_block_bucket_public_acl.py from typing import Any, Dict from boto3 import Session from app import Remediation from app.remediation_base import RemediationBase @Remediation class AwsS3BlockBucketPublicACL(RemediationBase): """Remediation that...
0xdabbad00/aws-remediations
tests/remediations/test_aws_ec2_stop_instance.py
<reponame>0xdabbad00/aws-remediations<gh_stars>1-10 from unittest import mock, TestCase from boto3 import Session from src.remediations.aws_ec2_stop_instance import AwsEc2StopInstance class TestAwsEc2StopInstance(TestCase): @mock.patch.object(Session, 'client') def test_fix(self, mock_session): mock_...
0xdabbad00/aws-remediations
tests/remediations/test_aws_kms_enable_key_rotation.py
<gh_stars>1-10 from unittest import mock, TestCase from boto3 import Session from src.remediations.aws_kms_enable_key_rotation import AwsKmsEnableKeyRotation class TestAwsIamUpdateAccountPasswordPolicy(TestCase): @mock.patch.object(Session, 'client') def test_fix(self, mock_session): mock_client = mo...
0xdabbad00/aws-remediations
tests/remediations/test_aws_s3_enable_bucket_versioning.py
<gh_stars>1-10 from unittest import mock, TestCase from boto3 import Session from src.remediations.aws_s3_enable_bucket_logging import AwsS3EnableBucketLogging class TestAwsS3EnableBucketLogging(TestCase): @mock.patch.object(Session, 'client') def test_fix(self, mock_session): mock_client = mock.Mock...
0xdabbad00/aws-remediations
src/remediations/aws_rds_disable_instance_public_access.py
<filename>src/remediations/aws_rds_disable_instance_public_access.py from typing import Any, Dict from boto3 import Session from app import Remediation from app.remediation_base import RemediationBase @Remediation class AwsRdsDisableInstancePublicAccess(RemediationBase): """Remediation that disables public acce...
0xdabbad00/aws-remediations
src/remediations/aws_ec2_stop_instance.py
from typing import Any, Dict from boto3 import Session from app import Remediation from app.remediation_base import RemediationBase @Remediation class AwsEc2StopInstance(RemediationBase): """Remediation that stops an EC2 instance""" @classmethod def _id(cls) -> str: return 'EC2.StopInstance' ...
0xdabbad00/aws-remediations
src/remediations/aws_cloudtrail_enable_log_validation.py
from typing import Any, Dict from boto3 import Session from app import Remediation from app.remediation_base import RemediationBase @Remediation class AwsCloudTrailEnableLogValidation(RemediationBase): """Remediation that enables log validation for existing CloudTrail trail""" @classmethod def _id(cls)...
0xdabbad00/aws-remediations
tests/remediations/test_aws_cloudtrail_enable_log_validation.py
<reponame>0xdabbad00/aws-remediations from unittest import mock, TestCase from boto3 import Session from src.remediations.aws_cloudtrail_enable_log_validation import AwsCloudTrailEnableLogValidation class TestAwsCloudTrailEnableLogValidation(TestCase): @mock.patch.object(Session, 'client') def test_fix(self,...
0xdabbad00/aws-remediations
tests/remediations/test_aws_rds_disable_snapshot_public_access.py
<reponame>0xdabbad00/aws-remediations<gh_stars>1-10 from unittest import mock, TestCase from boto3 import Session from src.remediations.aws_rds_disable_snapshot_public_access import AwsRdsDisableSnapshotPublicAccess class TestAwsRdsDisableSnapshotPublicAccess(TestCase): @mock.patch.object(Session, 'client') ...
0xdabbad00/aws-remediations
tests/remediations/test_aws_cloudtrail_create_trail.py
from unittest import mock, TestCase from boto3 import Session from src.remediations.aws_cloudtrail_create_trail import AwsCloudTrailCreateTrail class TestAwsCloudTrailCreateTrail(TestCase): @mock.patch.object(Session, 'client') def test_fix(self, mock_session): mock_client = mock.Mock() mock_...
0xdabbad00/aws-remediations
src/remediations/aws_ec2_terminate_instance.py
from typing import Any, Dict from boto3 import Session from app import Remediation from app.remediation_base import RemediationBase @Remediation class AwsEc2TerminateInstance(RemediationBase): """Remediation that terminates an EC2 instance""" @classmethod def _id(cls) -> str: return 'EC2.Termin...
0xdabbad00/aws-remediations
src/app/__init__.py
<reponame>0xdabbad00/aws-remediations import importlib import os from typing import Dict, Type from app.exceptions import RemediationDoesNotExist, RemediationAlreadyExists from app.remediation_base import RemediationBase class Remediation: """Class to be used as a decorator to register all remediation subclasses...
0xdabbad00/aws-remediations
tests/remediations/test_aws_iam_update_account_password_policy.py
from unittest import mock, TestCase from boto3 import Session from src.remediations.aws_iam_update_account_password_policy import AwsIamUpdateAccountPasswordPolicy class TestAwsIamUpdateAccountPasswordPolicy(TestCase): @mock.patch.object(Session, 'client') def test_fix(self, mock_session): mock_clien...
0xdabbad00/aws-remediations
src/app/exceptions.py
class RemediationException(Exception): """Base exception class for remediations""" class RemediationDoesNotExist(RemediationException): """Exception thrown when defined remediation couldn't be found""" class RemediationAlreadyExists(RemediationException): """Exception thrown when a remediation with the ...
0xdabbad00/aws-remediations
tests/remediations/test_aws_rds_enable_auto_minor_version_upgrade.py
from unittest import mock, TestCase from boto3 import Session from src.remediations.aws_rds_enable_auto_minor_version_upgrade import AwsRdsEnableAutoMinorVersionUpgrade class TestAwsRdsEnableAutoMinorVersionUpgrade(TestCase): @mock.patch.object(Session, 'client') def test_fix(self, mock_session): moc...
0xdabbad00/aws-remediations
src/remediations/aws_s3_enable_bucket_encryption.py
from typing import Any, Dict from boto3 import Session from app import Remediation from app.remediation_base import RemediationBase from app.exceptions import InvalidParameterException @Remediation class AwsS3EnableBucketEncryption(RemediationBase): """Remediation that enables encryption for an S3 bucket""" ...
0xdabbad00/aws-remediations
src/remediations/aws_cloudtrail_create_trail.py
<filename>src/remediations/aws_cloudtrail_create_trail.py from typing import Any, Dict from boto3 import Session from app import Remediation from app.remediation_base import RemediationBase @Remediation class AwsCloudTrailCreateTrail(RemediationBase): """Remediation that creates a new CloudTrail trail to S3""" ...
0xdabbad00/aws-remediations
tests/remediations/test_aws_ec2_enable_vpc_flow_logs_to_s3.py
<reponame>0xdabbad00/aws-remediations from unittest import mock, TestCase from boto3 import Session from src.remediations.aws_ec2_enable_vpc_flow_logs_to_s3 import AwsEc2EnableVpcFlowLogsToS3 class TestAwsEc2EnableVpcFlowLogsToS3(TestCase): @mock.patch.object(Session, 'client') def test_fix(self, mock_sessio...
shua2018ti/leetcode_python
Python/random-pick-with-blacklist.py
<filename>Python/random-pick-with-blacklist.py # Time: ctor: O(nlogn) # pick: O(logn) # Space: O(n) # Given a blacklist B containing unique integers from [0, N), # write a function to return a uniform random integer from # [0, N) which is NOT in B. # # Optimize it such that it minimizes the call to system’s Ma...
advocatux/fosdem-qml
backend/utils.py
<gh_stars>0 import os def create_path(filename): dirname = os.path.dirname(filename) if not os.path.exists(dirname): os.makedirs(dirname)