repo_name
stringlengths
6
97
path
stringlengths
3
341
text
stringlengths
8
1.02M
bermeom/quadruped-robot
learning/sources/source_gym_cartpole.py
from sources.source_gym import source_gym import cv2 import numpy as np ##### SOURCE GYM CARTPOLE class source_gym_cartpole( source_gym ): ### __INIT__ def __init__( self ): source_gym.__init__( self , 'CartPole-v0' ) ### INFORMATION def num_actions( self ): return self.env.action_space.n ...
bermeom/quadruped-robot
learning/players_reinforcement/player_A2C_1A.py
<gh_stars>1-10 from players_reinforcement.player_A2C_1 import * import tensorflow as tf # PLAYER A2C class player_A2C_1A( player_A2C_1 ): BATCH_SIZE = 50 NUM_FRAMES = 3 C_LEARNING_RATE = 1e-4 A_LEARNING_RATE = 1e-5 REWARD_DISCOUNT = 0.99 EXPERIENCES_LEN = 1e6 S...
bermeom/quadruped-robot
tensorblock/recipe/recipe_block.py
<filename>tensorblock/recipe/recipe_block.py class recipe_block: ###### Repeat Block def repBlock( self , **args ): block_pars = { **self.defs_block , **args } src , dst , type = block_pars['src'] , block_pars['dst'] , block_pars['type'] list_src = src.split( '/' ) src = self.ite...
bermeom/quadruped-robot
learning/players_reinforcement/player_A2C_1.py
<gh_stars>1-10 from players_reinforcement.player import player from auxiliar.aux_plot import * import tensorflow as tf import random from collections import deque import sys sys.path.append('..') import tensorblock as tb import numpy as np # PLAYER A2C class player_A2C_1(player): # __INIT__ def __init__(se...
bermeom/quadruped-robot
learning/players_reinforcement/player_PPO_2A.py
<gh_stars>1-10 from players_reinforcement.player_PPO_2 import * # PLAYER PPO class player_PPO_2A( player_PPO_2 ): NUM_FRAMES = 3 LEARNING_RATE = 3e-4 UPDATE_SIZE = 5 BATCH_SIZE = 256 EPSILON = 0.2 GAMMA = 0.99 LAM = 0.95 rgb = 1 # 1 if black a...
bermeom/quadruped-robot
tensorblock/recipe/recipe_base.py
<reponame>bermeom/quadruped-robot<filename>tensorblock/recipe/recipe_base.py import tensorflow as tf import tensorblock as tb class recipe_base: ####### Get Collection def collection( self , name = None ): if name is None: name = self.folder return tf.get_collection( tf.GraphKeys.GLOBAL_VARIABLE...
bermeom/quadruped-robot
learning/players_reinforcement/player_dql_bayesian_2A.py
<reponame>bermeom/quadruped-robot from players_reinforcement.player_dql_bayesian_2 import * # PLAYER DQL BAYESIAN class player_dql_bayesian_2A( player_dql_bayesian_2 ): NUM_FRAMES = 2 BATCH_SIZE = 512 LEARNING_RATE = 3e-4 REWARD_DISCOUNT = 0.99 START_RANDOM_PROB = 1.00 FINAL_RANDOM...
bermeom/quadruped-robot
learning/players_reinforcement/player_reinforce_rnn_1A.py
<filename>learning/players_reinforcement/player_reinforce_rnn_1A.py from players_reinforcement.player_reinforce_rnn_1 import * import tensorflow as tf # PLAYER REINFORCE RNN class player_reinforce_rnn_1A( player_reinforce_rnn_1 ): NUM_FRAMES = 3 LEARNING_RATE = 1e-4 REWARD_DISCOUNT = 0.99 ###...
bermeom/quadruped-robot
tensorblock/functions/func_activations.py
<reponame>bermeom/quadruped-robot import tensorflow as tf ### ELU Activation def elu( x ): return tf.nn.elu( x ) ### ReLU Activation def relu( x ): return tf.nn.relu( x ) ### Tanh Activation def tanh( x ): return tf.nn.tanh( x ) ### SoftPlus Activation def softplus( x, scale = 1): return tf.nn...
bermeom/quadruped-robot
tensorblock/aux/aux_batch.py
import copy import numpy as np ### Get Batch Data (Numpy) def get_batch_numpy( data , b , i ): l = len( data ) st = ( i + 0 ) * b % l fn = ( i + 1 ) * b % l if st > fn : if fn == 0: return data [ st : l ] else: return np.vstack( ( data[ st : l ] , data[ 0 : fn ] ) ) else: ...
bermeom/quadruped-robot
tensorblock/layers/layer_hlfully.py
import numpy as np import tensorflow as tf import tensorblock as tb class layer_hlfully: ####### Data def name(): return 'Fully' def shapeMult(): return 1 def dims(): return 1 def allowPooling(): return False ####### Function def function( x , W , b , recipe , pars ): if tb.aux.tf_len...
bermeom/quadruped-robot
learning/players_imitation/player.py
<gh_stars>1-10 import random from collections import deque import sys sys.path.append( '..' ) sys.path.append( '../..' ) import tensorblock as tb import numpy as np ##### PLAYER class player: ### __INIT__ def __init__( self ): self.num_stored_obsv = 0 ### DUMMY FUNCTIONS def prepare( self )...
bermeom/quadruped-robot
learning/sources/source_pygame.py
import signal import sys import importlib from sources.source import source ##### SOURCE PYGAME class source_pygame( source ): ### __INIT__ def __init__( self , game ): source.__init__( self ) module = importlib.import_module( 'sources.pygames.' + game ) self.env = getattr( module , ...
bermeom/quadruped-robot
learning/sources/vrep/vrepper/version.py
<filename>learning/sources/vrep/vrepper/version.py VERSION = '3.5.0' ARCH = 'x64'
bermeom/quadruped-robot
learning/players_reinforcement/player_dql_rnn_egreedy.py
import random from collections import deque from players_reinforcement.player import player import sys sys.path.append( '..' ) import tensorblock as tb import numpy as np import time ##### PLAYER DQL RNN EGREEDY class player_dql_rnn_egreedy( player ): ### __INIT__ def __init__( self ): player.__ini...
bermeom/quadruped-robot
tensorblock/aux/__init__.py
from tensorblock.aux.aux_batch import * from tensorblock.aux.aux_load import * from tensorblock.aux.aux_reshape import * from tensorblock.aux.aux_parse import * from tensorblock.aux.aux_tf_reshape import *
bermeom/quadruped-robot
trained_models/quadruped_robot_err_vel_DDPG_1A_7/auxiliar/aux_plot.py
import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt import matplotlib.image as mpimg import numpy as np ### PLOT STATE def plot_state( state ): n = state.shape[2] fig = plt.figure() for i in range( n ): plt.subplot( 2 , n , i + 1 ) plt.imshow( state[:,:,i] , cmap = 'gr...
bermeom/quadruped-robot
tensorblock/recipe/recipe_print.py
import tensorflow as tf import tensorblock as tb class recipe_print: ####### Print Nodes def printNodes( self ): print( '############################################################## TENSORS' , '/' + self.folder[0:-1] ) print( '##################################################...
bermeom/quadruped-robot
learning/players_reinforcement/player_reinforce_2.py
from players_reinforcement.player import player from auxiliar.aux_plot import * import random from collections import deque import sys sys.path.append('..') import tensorblock as tb import numpy as np # PLAYER REINFORCE class player_reinforce_2(player): # __INIT__ def __init__(self): player.__init...
bermeom/quadruped-robot
learning/players_reinforcement/player_dql_bayesian_1.py
<gh_stars>1-10 from players_reinforcement.player import player from auxiliar.aux_plot import * import random from collections import deque import sys sys.path.append('..') import tensorblock as tb import numpy as np # PLAYER DQL BAYESIAN class player_dql_bayesian_1(player): # __INIT__ def __init__(self): ...
bermeom/quadruped-robot
tensorblock/layers/__init__.py
from tensorblock.layers.layer_flatten import layer_flatten as flatten from tensorblock.layers.layer_fully import layer_fully as fully from tensorblock.layers.layer_conv1d import layer_conv1d as conv1d from tensorblock.layers.layer_conv2d import layer_conv2d as conv2d from tenso...
bermeom/quadruped-robot
learning/players_imitation/player_DAgger_1A.py
<gh_stars>1-10 from players_imitation.player_DAgger_1 import * # PLAYER DAgger class player_DAgger_1A( player_DAgger_1 ): LEARNING_RATE = 1e-4 BETA = 0.5 NUM_FRAMES = 1 BATCH_SIZE = 64 EPOCHS = 10 TIME_TO_UPDATE = 5000 DS_SIZE = 100000 DATASET ...
bermeom/quadruped-robot
tensorblock/recipe/recipe_layer.py
<reponame>bermeom/quadruped-robot import numpy as np import tensorflow as tf import tensorblock as tb class recipe_layer: ####### Add Layer def addLayer( self , **args ): pars = { **self.defs_layer , **args } if pars['input'] is None: pars['input'] = self.curr_input pars = self.parsePar...
bermeom/quadruped-robot
learning/sources/source_quadruped_robot.py
from sources.source_gym import source_gym import numpy as np import gym gym.envs.register( id='quadruped-robot-v0', entry_point='envs.quadruped:QuadrupedEnv', max_episode_steps=10000, reward_threshold=4800.0, ) ##### SOURCE GYM HALFCHEETAH class source_quadruped_robot( source_gym ): ### __INIT__...
bermeom/quadruped-robot
learning/players_imitation/player_GAIL_1.py
<reponame>bermeom/quadruped-robot from players_imitation.player import player import sys sys.path.append('..') import tensorblock as tb import numpy as np import random # PLAYER GAIL class player_GAIL_1(player): # __INIT__ def __init__(self): player.__init__(self) self.num_stored_obsv = se...
bermeom/quadruped-robot
learning/players_reinforcement/player_reinforce_rnn_2A.py
from players_reinforcement.player_reinforce_rnn_2 import * import tensorflow as tf # PLAYER REINFORCE RNN class player_reinforce_rnn_2A( player_reinforce_rnn_2 ): NUM_FRAMES = 3 LEARNING_RATE = 1e-4 REWARD_DISCOUNT = 0.99 ### __INIT__ def __init__( self ): player_reinforce_rnn_2....
bermeom/quadruped-robot
learning/sources/source_pygame_catch.py
from sources.source_pygame import source_pygame import cv2 ##### SOURCE PYGAME CATCH class source_pygame_catch( source_pygame ): ### __INIT__ def __init__( self ): source_pygame.__init__( self , 'pygame_catch' ) ### INFORMATION def num_actions( self ): return 3 ### MAP KEYS def map...
bermeom/quadruped-robot
tensorblock/recipe/__init__.py
from tensorblock.recipe.recipe_base import recipe_base as base from tensorblock.recipe.recipe_block import recipe_block as block from tensorblock.recipe.recipe_init import recipe_init as init from tensorblock.recipe.recipe_input import recipe_input as input from tensorblock.recipe.recipe_layer import recipe_layer as l...
bermeom/quadruped-robot
__init__.py
<filename>__init__.py from gym.envs.registration import registry, register, make, spec # import sys # sys.path.insert(0, '/ddpg') # sys.path.insert(0, '/ddpg/nets') register( id='quadreped-robot-v0', entry_point='envs.quadreped:QuadrepedEnv', max_episode_steps=10000, reward_threshold=4800.0, )
bermeom/quadruped-robot
learning/sources/source_vrep_poppy.py
<gh_stars>1-10 from sources.source_vrep import source_vrep import numpy as np import time ##### SOURCE VREP POPPY class source_vrep_poppy( source_vrep ): RENDER = False DESIRED_POSITION = [ 30, 45, -20, 90, 45, -45 ] ### __INIT__ def __init__( self ): source_vrep.__init__( self , 'poppy_erg...
bermeom/quadruped-robot
learning/sources/source_unity.py
import signal import sys import numpy as np from sources.source import source from sources.unity.unityagents import UnityEnvironment ##### SOURCE UNITY class source_unity( source ): ### __INIT__ def __init__( self, game ): source.__init__( self ) self.env = UnityEnvironment( file_name = "....
bermeom/quadruped-robot
tensorblock/functions/func_operations.py
import tensorflow as tf import tensorblock as tb ### Copy def copy( tensors , extras , pars ): list = [] for i in range( len( tensors[0] ) ): list.append( tensors[1][i].assign( tensors[0][i] ) ) return list ### Assign def assign( tensors , extras , pars ): vars = tf.trainable_variables() ...
bermeom/quadruped-robot
learning/players_reinforcement/player_PPO_1A.py
<reponame>bermeom/quadruped-robot<gh_stars>1-10 from players_reinforcement.player_PPO_1 import * # PLAYER PPO class player_PPO_1A( player_PPO_1 ): LEARNING_RATE = 1e-4 UPDATE_SIZE = 5 BATCH_SIZE = 64 EPSILON = 0.2 GAMMA = 0.99 LAM = 0.95 ### __INIT__ def ...
bermeom/quadruped-robot
learning/players_imitation/player_DAgger_1.py
<reponame>bermeom/quadruped-robot from players_imitation.player import player import sys sys.path.append('..') import tensorblock as tb import numpy as np import random # PLAYER DAgger class player_DAgger_1(player): # __INIT__ def __init__(self): player.__init__(self) self.num_stored_obsv ...
bermeom/quadruped-robot
tensorblock/layers/layer_flatten.py
import tensorblock as tb class layer_flatten: ####### Data def name(): return 'Flatten' def shapeMult(): return None def dims(): return 1 def allowPooling(): return False ####### Function def function( x , W , b , recipe , pars ): layer = tb.aux.tf_flatten( x ) return [ layer ...
bermeom/quadruped-robot
learning/sources/source_unity_exporter.py
import tensorflow as tf import tensorblock as tb from tensorflow.python.tools import freeze_graph def export_ugraph( brain, model_path, env_name, target_nodes): """ Unity ML Agents Exports latest saved model to .bytes format for Unity embedding. :brain: tensorblock brain :param model_path: path of...
bermeom/quadruped-robot
learning/sources/source.py
<filename>learning/sources/source.py import time from collections import deque from auxiliar.aux_plot import * ##### SOURCE class source: ### __INIT__ def __init__( self ): self.elapsed_time = 0 self.avg_rewd = deque() self.sum_rewd = 0 self.acc_rewd = 0 self.acc_time...
bermeom/quadruped-robot
learning/sources/source_gym_pong.py
<reponame>bermeom/quadruped-robot from sources.source_gym import source_gym import cv2 import numpy as np ##### SOURCE GYM PONG class source_gym_pong( source_gym ): ### __INIT__ def __init__( self ): source_gym.__init__( self , 'Pong-v4' ) ### INFORMATION def num_actions( self ): return 3 ...
bermeom/quadruped-robot
tensorblock/aux/aux_parse.py
import numpy as np ### Parse Pais def parse_pairs( data ): if not isinstance( data , list ): return [ [ data , None ] ] for i in range( len( data ) ): if not isinstance( data[i] , list ): data[i] = [ data[i] , None ] return data ### Get Folder def get_folder( name ): f...
bermeom/quadruped-robot
tensorblock/functions/func_optimizers.py
import tensorflow as tf ### Adam Optimizer def adam( tensors , extras , pars ): extra_update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS) with tf.control_dependencies(extra_update_ops): trainer = tf.train.AdamOptimizer( pars['learning_rate'] ) update = trainer.minimize( tensors[0] ) ...
bermeom/quadruped-robot
envs/test_robot.py
#!/usr/bin/env python3 """ Shows how to toss a capsule to a container. """ import numpy as np import math from pprint import pprint import mujoco_py as mpy #import load_model_from_path, MjSim, MjViewer import os model = mpy.mujoco_py.load_model_from_path("xml/quadrupedrobot.xml") # model = mpy.mujoco_py.load_model...
JanaKat-git/MovieRecommender
recommender.py
<filename>recommender.py ''' File with function for the Movie Recommender ''' import pandas as pd import numpy as np from sklearn.decomposition import NMF def create_user_item_matrix(file_ratings, file_movies, n_rows): ''' Create a user_item_matrix as pd.DataFrame. Paramters --------- file_rating...
JanaKat-git/MovieRecommender
create_matrix_model.py
''' File to: (1) load the user-item matrix and (2) train an NMF model (use recommender.model_recommender) (3) pickle the model and matrices in the file 'nmf_model' ''' from recommender import model_recommender, create_user_item_matrix import pandas as pd import pickle df = create_user_item_matrix('RATINGS', 'MOVIES...
JanaKat-git/MovieRecommender
application.py
<filename>application.py ''' Controller file for the web appilaction The central file of the application ''' from flask import Flask from flask import render_template from flask import request from recommender import user_recommendation import pickle app = Flask(__name__) @app.route('/') def index(): return ...
thobianchi/ansible-role-sys_update
molecule/default/tests/test_default.py
<filename>molecule/default/tests/test_default.py import os import testinfra.utils.ansible_runner testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner( os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all') def test_dep_pkg(host): if host.system_info.distribution == "CentOS": pkg = host.pa...
maikealame/xpboards-python-lib
xpboards/dataset.py
import csv import json from uuid import uuid4 class XPBoardsDataSet: def __init__(self, dataset, convert_types=False): """ The dataset must have the following pattern: { "id": <integer>, (for XPBoards datasets that already exists, optional) "name": <...
maikealame/xpboards-python-lib
tests/test_dataset.py
import pytest from xpboards import dataset as xpb_dataset DATASET_DICT = [ { 'firstname': 'Maike', 'lastname': 'Alame' }, { 'firstname': 'Fernando', 'lastname': 'Palmeiro' } ] # Fixtures @pytest.fixture def dataset_instance(): return xpb_dataset.read_dict(DATASET_...
maikealame/xpboards-python-lib
xpboards/services.py
import requests from .plan import XPBoardsPlan from .dataset import XPBoardsDataSet class XPBoardsServices: __API_VERSION = 'v1' __BASE_URL = f'https://hom.web.xpboards.com.br/api/{__API_VERSION}' __DEFAULT_HEADERS = {'Accept': 'application/json', 'Content-Type': 'application/json' } def __init__(sel...
maikealame/xpboards-python-lib
xpboards/__init__.py
from .services import XPBoardsServices as services from .dataset import XPBoardsDataSet as dataset from .plan import XPBoardsPlan as plan
maikealame/xpboards-python-lib
xpboards/plan.py
<gh_stars>0 class XPBoardsPlan: def __init__(self, user_dict): datasets_limit = user_dict['customer']['datasets_limit'] datasets_count = user_dict['customer']['datasets_count'] datasets_limit = 0 if datasets_limit == None else datasets_limit datasets_count = 0 if datasets_count == ...
maikealame/xpboards-python-lib
setup.py
from setuptools import setup, find_packages from os import path # Reads documentation from README.md this_directory = path.abspath(path.dirname(__file__)) with open(path.join(this_directory, 'README.md'), encoding='utf-8') as f: long_description = f.read() setup( name='xpboards', packages=find_packages(in...
rr326/ad_app_autoclimate
_autoclimate/laston.py
import datetime as dt import json from typing import Dict, List, Optional from _autoclimate.state import State from _autoclimate.utils import climate_name from adplus import Hass """ Laston - create new sensors that track the last time the climate was "on" as defined by autoclimate entity_rules. sensor.autoclimate_...
rr326/ad_app_autoclimate
_autoclimate/state.py
<filename>_autoclimate/state.py import json # noqa import math from typing import Optional, Tuple import adplus from adplus import Hass adplus.importlib.reload(adplus) from _autoclimate.occupancy import Occupancy from _autoclimate.utils import climate_name class State: def __init__( self, hass:...
rr326/ad_app_autoclimate
_autoclimate/occupancy.py
<gh_stars>0 import datetime as dt from typing import List from _autoclimate.utils import climate_name from adplus import Hass from dateutil import tz """ Create new sensors Reason: That way you do auto off if unoccupied since AND last_manual_change > X hours * unoccupied_since: * Last unoccupied * None if no...
rr326/ad_app_autoclimate
_autoclimate/mocks.py
from typing import Callable, List from adplus import Hass class Mocks: def __init__( self, hass: Hass, mock_config: dict, mock_callbacks: List[Callable], run_mocks: bool = False, init_delay: int = 1, mock_delay: int = 1, ): self.hass = hass ...
rr326/ad_app_autoclimate
autoclimate.py
from copy import Error import json # noqa import re import datetime as dt from _autoclimate.utils import in_inactive_period import adplus adplus.importlib.reload(adplus) import _autoclimate import _autoclimate.laston import _autoclimate.mocks import _autoclimate.occupancy import _autoclimate.schema import _autoclima...
rr326/ad_app_autoclimate
_autoclimate/turn_off.py
<reponame>rr326/ad_app_autoclimate<filename>_autoclimate/turn_off.py # pyright: reportUnusedCoroutine=false import datetime as dt import json # noqa from typing import Union import pytz import adplus from adplus import Hass from typing import Optional adplus.importlib.reload(adplus) from _autoclimate.laston import ...
rr326/ad_app_autoclimate
_autoclimate/schema.py
SCHEMA = { "name": {"required": True, "type": "string"}, "poll_frequency": {"required": True, "type": "number"}, "test_mode": {"required": False, "type": "boolean", "default": False}, "run_mocks": {"required": False, "type": "boolean", "default": False}, "create_temp_sensors": {"required": True, "ty...
rr326/ad_app_autoclimate
_autoclimate/utils.py
from adplus import Hass import datetime as dt import pytz def climate_name(entity): # climate.my_thermostat ==> my_thermostat return entity.split(".")[1] def in_inactive_period(hass: Hass, inactive_period) -> bool: if in_inactive_period is None: return False try: now = hass.get_now()...
Alkemic/yaACL
yaacl/migrations/0001_initial.py
<filename>yaacl/migrations/0001_initial.py # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('auth', '__first__'), ] operations = [ migrations.CreateModel( name='A...
Alkemic/yaACL
yaacl/models.py
# -*- coding: utf-8 -*- from django.db import models from django.utils.translation import gettext_lazy as _ from django.utils.encoding import python_2_unicode_compatible from .managers import ACLManager from django.conf import settings user_model = getattr(settings, 'AUTH_USER_MODEL', 'auth.User') group_model = geta...
Alkemic/yaACL
setup.py
# -*- coding:utf-8 -*- import os from setuptools import setup f = open(os.path.join(os.path.dirname(__file__), 'README.md')) readme = f.read() f.close() setup( name='yaacl', version='0.8.2', description='Yet another access control list (ACL) per view for Django', long_description=readme, author="<...
Alkemic/yaACL
yaacl/templatetags/acl.py
# -*- coding:utf-8 -*- from django import template from yaacl import functions register = template.Library() @register.filter def has_access(user, resource): """ :type user: django.contrib.auth.models.User :type name : str Checks if user has rights to given resource """ return functions.has_...
Alkemic/yaACL
demo/test_acl/urls.py
<reponame>Alkemic/yaACL<gh_stars>0 # -*- coding:utf-8 -*- from django.conf.urls import * from .views import Index, TestClassBasedView, test, other_index, utf_test urlpatterns = [ url(r'^$', Index.as_view(), name='index'), url(r'^$', TestClassBasedView.as_view(), name='index'), url(r'test/$', test, name='t...
Alkemic/yaACL
yaacl/management/commands/show_acl.py
# -*- coding:utf-8 -*- from django.core.management.base import BaseCommand from django.utils.translation import ugettext_lazy as _ from yaacl.models import ACL __author__ = '<NAME> <<EMAIL>>' class Command(BaseCommand): help = _('Lists all saved resources') def handle(self, *args, **options): for a...
Alkemic/yaACL
yaacl/managers.py
<gh_stars>0 # -*- coding:utf-8 -*- from django.db.models.query_utils import Q from django.db.models import Manager class ACLManager(Manager): def get_user_resources(self, user): return self.get_queryset().filter( Q(user=user) | Q(group__in=user.groups.all()) ).distinct()
Alkemic/yaACL
yaacl/decorators.py
<filename>yaacl/decorators.py # -*- coding:utf-8 -*- from functools import wraps from django.utils.decorators import method_decorator, available_attrs from yaacl.functions import has_access from .views import no_access from .models import ACL from .signals import register_resource def acl_register_view(name=None, r...
Alkemic/yaACL
yaacl/views.py
# -*- coding: utf-8 -*- from django.template import loader from django.template.response import TemplateResponse def no_access(request): """No access view""" template = loader.get_template('yaacl/no_access.html') return TemplateResponse(request, template)
Alkemic/yaACL
yaacl/functions.py
# -*- coding:utf-8 -*- from django.db.models.query_utils import Q from yaacl.models import ACL __author__ = '<NAME> <<EMAIL>>' def get_acl_resources(user): """ :type user: django.contrib.auth.models.User :type name : str Checks if user has rights to given resource """ return ACL.objects.filt...
Alkemic/yaACL
yaacl/signals.py
<filename>yaacl/signals.py # -*- coding:utf-8 -*- from django.dispatch import Signal __author__ = '<NAME> <<EMAIL>>' register_resource = Signal( providing_args=['resource', 'name'], )
Alkemic/yaACL
yaacl/management/commands/sync_acl.py
# -*- coding:utf-8 -*- from django.core.management.base import BaseCommand from django.utils.translation import ugettext_lazy as _ from django.conf import settings from yaacl.models import ACL __author__ = '<NAME> <<EMAIL>>' class Command(BaseCommand): help = _('Sync resources with database') def handle(se...
Alkemic/yaACL
yaacl/admin.py
<reponame>Alkemic/yaACL<gh_stars>0 # -*- coding:utf-8 -*- from django import forms try: from django.apps import apps get_model = apps.get_model except ImportError: from django.db.models.loading import get_model from django.conf import settings from django.contrib import admin from django.contrib.auth import...
Alkemic/yaACL
yaacl/migrations/0002_m2m_relations.py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models import django.contrib.auth.models from django.conf import settings class Migration(migrations.Migration): dependencies = [ ('auth', '0006_require_contenttypes_0002'), ('yaacl', '0001_initial'...
Alkemic/yaACL
yaacl/management/commands/__init__.py
<filename>yaacl/management/commands/__init__.py __author__ = '<NAME> <<EMAIL>>'
Alkemic/yaACL
demo/test_acl/views.py
<gh_stars>0 # -*- coding:utf-8 -*- from django.views.generic import View, TemplateView from yaacl.decorators import acl_register_view, acl_register_class class Index(TemplateView): template_name = 'test_acl/index.html' @acl_register_view() def test(request): pass @acl_register_view('This is the "other" i...
Alkemic/yaACL
yaacl/templatetags/__init__.py
# -*- coding:utf-8 -*- __author__ = '<NAME> <<EMAIL>>'
seantis/spare
spare/tests/test_utils.py
<reponame>seantis/spare<gh_stars>1-10 import os import pytest import signal from multiprocessing import Process from spare import utils from spare.errors import FileChangedDuringReadError from time import sleep def test_abort_if_file_changed(temporary_path, loghandler): path = temporary_path / 'foo' path.tou...
seantis/spare
spare/tests/test_block.py
<gh_stars>1-10 import pytest import random from hypothesis import given, strategies from spare.block import AVAILABLE_BLOCKS from secrets import token_bytes @pytest.mark.parametrize("cls", AVAILABLE_BLOCKS.values()) def test_block(cls): block = cls(password=b'password', nonce=token_bytes(16), data=b'foobar') ...
seantis/spare
spare/inventory.py
import grp import hashlib import io import os import os.path import platform import pwd import re import stat from cached_property import cached_property from collections import defaultdict from contextlib import suppress from pathlib import Path from spare import log from spare.utils import abort_if_file_changes_duri...
seantis/spare
spare/tests/test_inventory.py
import os import pytest import socket import tempfile from contextlib import suppress from io import UnsupportedOperation from pathlib import Path from spare.inventory import Inventory, scandir def test_empty_inventory(temporary_path): inventory = Inventory(temporary_path) inventory.scan() assert not in...
seantis/spare
spare/recovery.py
import os import grp import pwd from cached_property import cached_property from itertools import groupby from pathlib import Path from spare import log, FOLLOW_SYMLINKS from spare.errors import TargetPathNotEmpty from spare.download import Download, DownloadProcess from multiprocessing import cpu_count, Queue class...
seantis/spare
spare/cli.py
import click import pdb import sys import traceback from logbook import StreamHandler from spare.backup import create, restore, validate, lock, unlock from spare.utils import s3_client VALID_PATH = click.Path(exists=True, file_okay=False) def enable_post_mortem_debugging(): # pragma: no cover def hook(type, ...
seantis/spare
spare/block.py
<filename>spare/block.py import lzma import hashlib from cryptography.hazmat.primitives.ciphers.aead import AESGCM from miscreant.aead import AEAD AVAILABLE_BLOCKS = {} DEFAULT_BLOCK = 'aes-siv' class Block(object): """ Interface to implement a block. Each block is meant to encrypt and decrypt data in memo...
seantis/spare
spare/envoy.py
import re import secrets import weakref from boto3.s3.transfer import TransferConfig from concurrent.futures import ThreadPoolExecutor from io import BytesIO from spare.block import DEFAULT_BLOCK, AVAILABLE_BLOCKS from spare.errors import BucketAlreadyLockedError from spare.errors import BucketNotLockedError from spar...
seantis/spare
spare/utils.py
import os import signal import stat import sys import weakref from boto3 import resource from botocore.client import Config from contextlib import contextmanager, ExitStack from logbook import SyslogHandler from pathlib import Path from spare import log from spare.errors import FileChangedDuringReadError CLEANUP_FUN...
seantis/spare
spare/backup.py
from spare import log from spare.envoy import Envoy from spare.inventory import Inventory from spare.recovery import Recovery from spare.snapshot import SnapshotCollection def create(path, s3, bucket, password, keep=1, skip=None, force=False): inventory = Inventory(path, skip) inventory.scan() with Envoy...
seantis/spare
spare/tests/test_cli.py
<filename>spare/tests/test_cli.py from click.testing import CliRunner from spare.cli import create_cli from spare.cli import lock_cli from spare.cli import restore_cli from spare.cli import unlock_cli from spare.cli import validate_cli def test_create_cli(endpoint, access_key, secret_key, temporary_path): runner ...
seantis/spare
spare/tests/test_transfer.py
def test_access(s3): assert not tuple(s3.buckets.iterator()) s3.create_bucket(Bucket='foobar') assert tuple(s3.buckets.iterator()) def test_buckets_cleared_between_tests(s3): assert not tuple(s3.buckets.iterator())
seantis/spare
spare/download.py
<reponame>seantis/spare<gh_stars>1-10 import os import random import shutil from concurrent.futures import ThreadPoolExecutor from multiprocessing import Process from spare import log, FOLLOW_SYMLINKS from spare.envoy import Envoy from spare.inventory import hash_implementation from spare.utils import s3_client, writa...
seantis/spare
setup.py
# -*- coding: utf-8 -*- from setuptools import setup, find_packages name = 'spare' description = 'One S3 backup, encrypted on the fly.' version = '0.4.0' def get_long_description(): readme = open('README.rst').read() history = open('HISTORY.rst').read() # cut the part before the description to avoid re...
seantis/spare
spare/tests/conftest.py
import os import port_for import pytest import secrets import sys import tempfile from mirakuru import HTTPExecutor from pathlib import Path from spare.envoy import Envoy from spare.utils import s3_client from urllib.request import urlretrieve MINIO_RELEASES = ( ('darwin', 'https://dl.minio.io/server/minio/relea...
seantis/spare
spare/errors.py
class SpareError(Exception): pass class FileChangedDuringReadError(SpareError): """ Raised when a file has changed while it was read. """ def __init__(self, path): self.path = path class FileChangedBeforeUploadError(SpareError): """ Raised when a file changed after it was inventoried, but b...
seantis/spare
spare/tests/test_envoy.py
import os import secrets import signal import weakref import pytest from io import BytesIO from spare.block import AVAILABLE_BLOCKS from spare.envoy import Envoy from spare.errors import BucketAlreadyLockedError from spare.errors import BucketNotLockedError from spare.errors import BucketOtherwiseUsedError from spare....
seantis/spare
spare/tests/test_download.py
from io import BytesIO from spare.download import Download, DownloadManager def test_digestless_download(envoy, temporary_path): envoy.send('foo', BytesIO(b'foo')) with DownloadManager(envoy) as manager: download = Download('foo', 'wrong-digest') download.to(temporary_path / 'foo') m...
seantis/spare
spare/tests/test_snapshot.py
import pytest from io import BytesIO from spare.errors import FileChangedBeforeUploadError from spare.errors import SnapshotMismatchError from spare.errors import PruneToZeroError from spare.inventory import Inventory from spare.snapshot import SnapshotCollection def test_empty_bucket(envoy): collection = Snapsh...
seantis/spare
spare/snapshot.py
<reponame>seantis/spare<gh_stars>1-10 import json import ulid from io import BytesIO from spare import log from spare.errors import FileChangedBeforeUploadError from spare.errors import PruneToZeroError from spare.errors import SnapshotMismatchError from spare.inventory import hash_implementation from spare.utils impo...
seantis/spare
spare/tests/test_backup.py
import os import secrets import pytest from pathlib import Path from spare.backup import create, restore, validate from spare.envoy import Envoy from spare.errors import TargetPathNotEmpty, SnapshotMismatchError from spare.snapshot import SnapshotCollection from tempfile import TemporaryDirectory def test_create(s3,...
seantis/spare
spare/__init__.py
<reponame>seantis/spare from logbook import Logger from os import supports_follow_symlinks log = Logger('spare') FOLLOW_SYMLINKS = supports_follow_symlinks and {'follow_symlinks': True} or {} __all__ = ('log', 'FOLLOW_SYMLINKS')
CXUtk/TRV2
build.py
import sys import os import shutil # 把资源文件夹里的资源按照是否相等复制一份到输出目录 def copyFiles(resourcePath: str, dirName: str, outputPath: str): fileList = [] totalFiles = 0 for root, dirs, files in os.walk(resourcePath): for file in files: filePath = os.path.join(root, file) targetPath = ...
CXUtk/TRV2
encoding.py
<filename>encoding.py import os import sys import codecs from chardet.universaldetector import UniversalDetector # 把文件夹中所有 *.cpp, *.h, *.hpp, *.inl, ... 等源码文件全部转换为utf8编码 __exts__ = ( ".cpp", ".h", ".hpp", ".inl", ".frag", ".vert" ) # 检测文件的编码 def detectEncoding(file): detector = UniversalDetector() with ...