# -*- mode: python -*-

block_cipher = None

HIDDEN_IMPORTS = [
    'aiohttp',
    'pyportify',
    'pyportify.middlewares',
    'pyportify.server',
]

a = Analysis(['pyportify/server.py'],
             pathex=['/Users/jbraeg/projects/pyportify'],
             binaries=None,
             datas=[
                ('pyportify/static', 'pyportify'),
             ],
             hiddenimports=HIDDEN_IMPORTS,
             hookspath=[],
             runtime_hooks=[],
             excludes=[],
             win_no_prefer_redirects=False,
             win_private_assemblies=False,
             cipher=block_cipher)
pyz = PYZ(a.pure, a.zipped_data, cipher=block_cipher)
exe = EXE(pyz,
          a.scripts,
          a.binaries,
          a.zipfiles,
          a.datas,
          name='pyportify',
          debug=False,
          strip=False,
          upx=True,
          console=True)

a1 = Analysis(['pyportify/copy_all.py'],
             pathex=['/Users/jbraeg/projects/pyportify'],
             binaries=None,
             datas=None,
             hiddenimports=HIDDEN_IMPORTS,
             hookspath=[],
             runtime_hooks=[],
             excludes=[],
             win_no_prefer_redirects=False,
             win_private_assemblies=False,
             cipher=block_cipher)
pyz1 = PYZ(a1.pure, a1.zipped_data, cipher=block_cipher)
exe1 = EXE(pyz,
          a1.scripts,
          a1.binaries,
          a1.zipfiles,
          a1.datas,
          name='pyportify-copyall',
          debug=False,
          strip=False,
          upx=True,
          console=True)


# Palindromo
frase = str(input('Digite uma frase: ')).strip().lower()
palavras = frase.split()
junto = ''.join(palavras)
#inverso = ''
inverso = junto[::-1]   # Inverte todas as letras lendo de tras para frente.

#for letra in range(len(junto) - 1, -1, -1):
#    inverso = inverso + junto[letra]
if inverso == junto:
    print('É um palindromo.')
else:
    print('Não é um palindromo.')


import json
from channels.generic.websocket import AsyncWebsocketConsumer
from authentication.models import User
from chat.models import Message
from asgiref.sync import sync_to_async, async_to_sync
from django.db import models
from django.db.models import Q
from django.db.models import Case, IntegerField, F, When
from .models import ChatRoom, ChatMessage

class ChatConsumer(AsyncWebsocketConsumer):
    async def connect(self):
        # Get the user IDs for the sender and receiver from the URL path.
        self.sender_id = self.scope['url_route']['kwargs']['sender_id']
        self.receiver_id = self.scope['url_route']['kwargs']['receiver_id']

        # Check that the sender and receiver are valid users.
        try:
            self.sender = await sync_to_async(User.objects.get)(id=self.sender_id)
            self.receiver = await sync_to_async(User.objects.get)(id=self.receiver_id)
        except User.DoesNotExist:
            await self.close()

        # Join the channel group for this chat.
        chat_group_ids = sorted([self.sender_id, self.receiver_id])
        self.chat_group_name = f'chat_{chat_group_ids[0]}_{chat_group_ids[1]}'
        await self.channel_layer.group_add(
            self.chat_group_name,
            self.channel_name
        )
        await self.accept()

        messages = await sync_to_async(Message.objects.filter)(
            (models.Q(sender=self.sender) & models.Q(receiver=self.receiver)) |
            (models.Q(sender=self.receiver) & models.Q(receiver=self.sender))
        )
        async for message in messages:
            await self.send(text_data=json.dumps({
                'message': message.message,
                'sender_id': str(message.sender_id),
                'timestamp': str(message.created_at)
            }))

    async def disconnect(self, close_code):
        # Leave the channel group.
        await self.channel_layer.group_discard(
            self.chat_group_name,
            self.channel_name
        )

    async def receive(self, text_data):
        # Save the message to the database.
        message = await sync_to_async(Message.objects.create)(
            sender=self.sender,
            receiver=self.receiver,
            message=text_data
        )

        # Broadcast the message to everyone in the chat group.
        await self.channel_layer.group_send(
            self.chat_group_name,
            {
                'type': 'chat_message',
                'message': message.message,
                'sender_id': str(message.sender_id),
                'timestamp': str(message.created_at)
            }
        )

    async def chat_message(self, event):
        # Send the message to the WebSocket.
        await self.send(text_data=json.dumps({
            'message': event['message'],
            'sender_id': event['sender_id'],
            'timestamp': event['timestamp']
        }))

class ChatList(AsyncWebsocketConsumer):
    async def connect(self):
        # Get the user id from the query string
        self.user_id = self.scope['url_route']['kwargs']['user_id']
         # Get the chat room name from the URL
        self.room_name = 'chat_%s' % self.scope['url_route']['kwargs']['user_id']
        self.room_group_name = self.room_name
        # Join the room group
        await self.channel_layer.group_add(
            self.room_group_name,
            self.channel_name
        )
        await self.accept()
        chat_rooms = await self.get_chat_rooms()
        await self.send(text_data=chat_rooms)

    async def receive(self, text_data):
        chat_rooms = await self.get_chat_rooms()
        await self.send(text_data=chat_rooms)

    async def update_chat_list(self, message):
        text = message.get('text_data', '')
        await self.send(text_data=text)

    async def disconnect(self, close_code):
        # Leave the group for this user's chat list
        await self.channel_layer.group_discard(
            'chat_list_{}'.format(self.user_id),
            self.channel_name,
        )

    @sync_to_async
    def get_chat_rooms(self):
        chat_rooms = ChatRoom.objects.filter(users__id=self.user_id)
        chat_list = []
        for room in chat_rooms:
            messages = ChatMessage.objects.filter(chat=room).order_by("timestamp")
            other_user = room.users.exclude(id=self.user_id).first()
            if ChatMessage.objects.filter(chat=room):
                print("hello")
                last_message = messages.last()
                unread_count = room.messages.filter(sender=other_user, is_seen=False).count()
                chat_room_data = {
                    'room_id': str(room.room_id),
                    'current_user_id': str(self.user_id),
                    'other_user_id': str(other_user.id),
                    'other_user_name': other_user.username,
                    'unread_count': unread_count,
                    'last_message':{
                        'sender': str(last_message.sender.id),
                        'is_seen': last_message.is_seen,
                        'content': last_message.content,
                        'timestamp': str(last_message.timestamp),
                        'room_id': str(last_message.chat.room_id),
                    }
                }
                chat_list.append(chat_room_data)
        return json.dumps(chat_list)


from tensorflow.python.checkpoint import checkpoint as tracking_util
from tensorflow.python.distribute import collective_all_reduce_strategy
from tensorflow.python.distribute import combinations
from tensorflow.python.distribute import distribute_lib
from tensorflow.python.distribute import distribute_utils
from tensorflow.python.distribute import strategy_combinations
from tensorflow.python.distribute import values
from tensorflow.python.eager import backprop
from tensorflow.python.eager import context
from tensorflow.python.eager import def_function
from tensorflow.python.eager import test
from tensorflow.python.framework import config
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import errors
from tensorflow.python.framework import func_graph
from tensorflow.python.framework import ops
from tensorflow.python.framework import tensor
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import custom_gradient
from tensorflow.python.ops import math_ops
from tensorflow.python.ops import rnn
from tensorflow.python.ops import rnn_cell_impl
from tensorflow.python.ops import state_ops
from tensorflow.python.ops import variable_scope
from tensorflow.python.ops import variable_v1
from tensorflow.python.ops import variables
from tensorflow.python.saved_model import load
from tensorflow.python.saved_model import save

def _replica_id():
  replica_id = distribute_lib.get_replica_context().replica_id_in_sync_group
  if not isinstance(replica_id, tensor.Tensor):
    replica_id = constant_op.constant(replica_id)
  return replica_id

def _mimic_two_cpus():
  cpus = config.list_physical_devices("CPU")

  config.set_logical_device_configuration(cpus[0], [
      context.LogicalDeviceConfiguration(),
      context.LogicalDeviceConfiguration(),
  ])

@combinations.generate(
    combinations.combine(
        distribution=[
            strategy_combinations.mirrored_strategy_with_gpu_and_cpu,
            combinations.NamedDistribution(
                "Collective2CPUs",
                # pylint: disable=g-long-lambda
                lambda: collective_all_reduce_strategy.
                CollectiveAllReduceStrategy._from_local_devices((
                    "/device:CPU:0", "/device:CPU:1")),
                required_gpus=0)
        ],
        mode=["graph", "eager"]))
class MirroredVariableCreationTest(test.TestCase):
  """Base class that tests mirrored variable creator.

  Currently it assumes all strategy objects have two replicas.
  """

  @classmethod
  def setUpClass(cls):
    _mimic_two_cpus()

  def assertAllDifferent(self, objs):
    for i in range(len(objs)):
      for j in range(len(objs)):
        if i == j:
          continue
        self.assertIsNot(objs[i], objs[j])

  # TODO(priyag): Modify more tests to use this helper and check more
  # properties.
  def _test_mv_properties(self, var, name, strategy):
    self.assertTrue(distribute_utils.is_mirrored(var))
    self.assertEqual(name, var.name)
    self.assertIs(strategy, var.distribute_strategy)
    for i, d in enumerate(var._devices):
      self.assertEqual(d, strategy.experimental_local_results(var)[i].device)
      self.assertIs(
          strategy,
          strategy.experimental_local_results(var)[i]._distribute_strategy)  # pylint: disable=protected-access

  def testVariableInFuncGraph(self, distribution):

    def model_fn():
      v = variable_v1.VariableV1(2.0, name="bar")
      distribute_lib.get_replica_context().merge_call(lambda _: _)
      return v

    with func_graph.FuncGraph("fg").as_default(), distribution.scope():
      v1 = variable_v1.VariableV1(1.0, name="foo")
      v2 = distribution.extended.call_for_each_replica(model_fn)

    self._test_mv_properties(v1, "foo:0", distribution)
    self._test_mv_properties(v2, "bar:0", distribution)

  def testVariableWithTensorInitialValueInFunction(self, distribution):
    if not context.executing_eagerly():
      self.skipTest("`tf.function` is an eager-only feature")

    v = [None]

    def model_fn():
      if v[0] is None:
        init_val = array_ops.zeros([])
        v[0] = variables.Variable(init_val)
      distribute_lib.get_replica_context().merge_call(lambda _: _)
      return v[0]

    @def_function.function(autograph=False)
    def make_v1():
      return distribution.experimental_local_results(
          distribution.extended.call_for_each_replica(model_fn))

    self.assertAllEqual([0, 0], make_v1())

  def testVariableWithTensorInitialValueInFunctionXLA(self, distribution):
    if not context.executing_eagerly():
      self.skipTest("`tf.function` is an eager-only feature")

    v = [None]

    def model_fn():
      if v[0] is None:
        init_val = array_ops.zeros([])
        v[0] = variables.Variable(init_val)
      distribute_lib.get_replica_context().merge_call(lambda _: _)
      return v[0]

    @def_function.function(autograph=False, jit_compile=True)
    def make_v1():
      return distribution.experimental_local_results(
          distribution.extended.call_for_each_replica(model_fn))

    with self.assertRaisesRegex(
        errors.UnimplementedError,
        "We failed to lift variable creations out of this tf.function, "
        "so this tf.function cannot be run on XLA."):
      _ = make_v1()

  def testSingleVariable(self, distribution):

    def model_fn():
      # This variable should be created only once across the threads because of
      # special variable_creator functions used by
      # `distribution.extended.call_for_each_replica`.
      v = variable_v1.VariableV1(1.0, name="foo")
      distribute_lib.get_replica_context().merge_call(lambda _: _)
      return v

    with distribution.scope():
      result = distribution.extended.call_for_each_replica(model_fn)
      self._test_mv_properties(result, "foo:0", distribution)

  def testUnnamedVariable(self, distribution):

    def model_fn():
      v = variable_v1.VariableV1(1.0)
      distribute_lib.get_replica_context().merge_call(lambda _: _)
      return v

    with distribution.scope():
      result = distribution.extended.call_for_each_replica(model_fn)
      self._test_mv_properties(result, "Variable:0", distribution)

  def testMultipleVariables(self, distribution):

    def model_fn():
      vs = []
      for i in range(5):
        vs.append(variable_v1.VariableV1(1.0, name="foo" + str(i)))
      distribute_lib.get_replica_context().merge_call(lambda _: _)
      return vs

    with distribution.scope():
      result = distribution.extended.call_for_each_replica(model_fn)
      for i, v in enumerate(result):
        self._test_mv_properties(v, "foo" + str(i) + ":0", distribution)

  def testMultipleVariablesWithSameCanonicalName(self, distribution):

    def model_fn():
      vs = []
      vs.append(variable_v1.VariableV1(1.0, name="foo/bar"))
      vs.append(variable_v1.VariableV1(1.0, name="foo_1/bar"))
      vs.append(variable_v1.VariableV1(1.0, name="foo_1/bar_1"))
      vs.append(variable_v1.VariableV1(1.0, name="foo/bar_1"))
      distribute_lib.get_replica_context().merge_call(lambda _: _)
      return vs

    with distribution.scope():
      result = distribution.extended.call_for_each_replica(model_fn)
      for v in result:
        self.assertTrue(distribute_utils.is_mirrored(v))
      self.assertEqual(4, len(result))
      self.assertEqual("foo/bar:0", result[0].name)
      self.assertEqual("foo_1/bar:0", result[1].name)
      self.assertEqual("foo_1/bar_1:0", result[2].name)
      self.assertEqual("foo/bar_1:0", result[3].name)

  def testVariableWithSameCanonicalNameAcrossThreads(self, distribution):

    def model_fn():
      replica_id = self.evaluate(_replica_id())
      v = variable_v1.VariableV1(1.0, name="foo_" + str(replica_id))
      distribute_lib.get_replica_context().merge_call(lambda _: _)
      return v

    with distribution.scope():
      result = distribution.extended.call_for_each_replica(model_fn)
      self.assertTrue(distribute_utils.is_mirrored(result))
      # The resulting mirrored variable will use the name from the first device.
      self.assertEqual("foo_0:0", result.name)

  def testWithVariableAndVariableScope(self, distribution):

    def model_fn():
      v0 = variable_v1.VariableV1(1.0, name="var0", aggregation=None)
      with variable_scope.variable_scope("common"):
        v1 = variable_v1.VariableV1(1.0, name="var1")
        # This will pause the current thread, and execute the other thread.
        distribute_lib.get_replica_context().merge_call(lambda _: _)
        v2 = variable_v1.VariableV1(
            1.0,
            name="var2",
            synchronization=variable_scope.VariableSynchronization.ON_READ,
            aggregation=variable_scope.VariableAggregation.SUM)
        v3 = variable_v1.VariableV1(
            1.0,
            name="var3",
            synchronization=variable_scope.VariableSynchronization.ON_WRITE,
            aggregation=variable_scope.VariableAggregation.MEAN)

      return v0, v1, v2, v3

    with distribution.scope():
      v = variable_v1.VariableV1(1.0, name="var-main0")
      self.assertEqual("var-main0:0", v.name)

      result = distribution.extended.call_for_each_replica(model_fn)
      self.assertEqual(4, len(result))
      v0, v1, v2, v3 = result
      self.assertTrue(distribute_utils.is_mirrored(v0))
      self.assertEqual("var0:0", v0.name)
      self.assertTrue(distribute_utils.is_mirrored(v1))
      self.assertEqual("common/var1:0", v1.name)
      self.assertTrue(distribute_utils.is_sync_on_read(v2))
      self.assertEqual("common/var2:0", v2.name)
      self.assertEqual(variable_scope.VariableAggregation.SUM, v2.aggregation)
      self.assertTrue(distribute_utils.is_mirrored(v3))
      self.assertEqual("common/var3:0", v3.name)
      self.assertEqual(variable_scope.VariableAggregation.MEAN, v3.aggregation)

  def testWithGetVariableAndVariableScope(self, distribution):

    def model_fn():
      v0 = variable_scope.get_variable("var0", [1])
      with variable_scope.variable_scope("common"):
        v1 = variable_scope.get_variable("var1", [1])
        # This will pause the current thread, and execute the other thread.
        distribute_lib.get_replica_context().merge_call(lambda _: _)
        v2 = variable_scope.get_variable(
            "var2", [1],
            synchronization=variable_scope.VariableSynchronization.ON_READ,
            aggregation=variable_scope.VariableAggregation.SUM)
        v3 = variable_scope.get_variable(
            "var3", [1],
            synchronization=variable_scope.VariableSynchronization.ON_WRITE,
            aggregation=variable_scope.VariableAggregation.MEAN)

      return v0, v1, v2, v3

    with distribution.scope():
      with variable_scope.variable_scope("main"):
        v = variable_scope.get_variable("var-main0", [1])
        self.assertEqual("main/var-main0:0", v.name)

        result = distribution.extended.call_for_each_replica(model_fn)
        self.assertEqual(4, len(result))
        v0, v1, v2, v3 = result
        self.assertTrue(distribute_utils.is_mirrored(v0))
        self.assertEqual("main/var0:0", v0.name)
        self.assertTrue(distribute_utils.is_mirrored(v1))
        self.assertEqual("main/common/var1:0", v1.name)
        self.assertTrue(distribute_utils.is_sync_on_read(v2))
        self.assertEqual("main/common/var2:0", v2.name)
        self.assertEqual(variable_scope.VariableAggregation.SUM, v2.aggregation)
        self.assertTrue(distribute_utils.is_mirrored(v3))
        self.assertEqual("main/common/var3:0", v3.name)
        self.assertEqual(variable_scope.VariableAggregation.MEAN,
                         v3.aggregation)

  def testOnlyFirstReplicaUpdatesVariables(self, distribution):

    def create_fn():
      aggregation = variable_scope.VariableAggregation.ONLY_FIRST_REPLICA
      v0 = variable_v1.VariableV1(
          2.0,
          name="on_read",
          synchronization=variable_scope.VariableSynchronization.ON_READ,
          aggregation=aggregation)
      v1 = variable_v1.VariableV1(
          3.0,
          name="on_write",
          synchronization=variable_scope.VariableSynchronization.ON_WRITE,
          aggregation=aggregation)
      return v0, v1

    with distribution.scope():
      v0, v1 = distribution.extended.call_for_each_replica(create_fn)
      self.evaluate(v0.initializer)
      self.assertEqual(
          2.0, self.evaluate(distribution.experimental_local_results(v0)[0]))
      self.assertEqual(
          2.0, self.evaluate(distribution.experimental_local_results(v0)[1]))
      self.assertEqual(2.0, self.evaluate(distribution.extended.read_var(v0)))
      self.evaluate(v1.initializer)
      self.assertEqual(
          3.0, self.evaluate(distribution.experimental_local_results(v1)[0]))
      self.assertEqual(
          3.0, self.evaluate(distribution.experimental_local_results(v1)[1]))
      self.assertEqual(3.0, self.evaluate(distribution.extended.read_var(v1)))

      def replica_id_plus_one():
        return math_ops.cast(_replica_id() + 1, dtype=dtypes.float32)

      # Update using the assign_add member function.
      def update_member_fn():
        update0 = v0.assign_add(5.0 * replica_id_plus_one())
        update1 = v1.assign_add(7.0 * replica_id_plus_one())
        return update0, update1

      update0a, update1a = distribution.extended.call_for_each_replica(
          update_member_fn)

      # Update "sync on read" variable.
      self.evaluate(distribution.group(update0a))
      local_results = self.evaluate(distribution.experimental_local_results(v0))
      self.assertEqual(2.0 + 5.0, local_results[0])
      # Writes are not synchronized for "sync on read" variables,
      # so device[1] can end up with a different value.
      self.assertEqual(2.0 + 2 * 5.0, local_results[1])
      # Always reads from device 0.
      self.assertEqual(2.0 + 5.0,
                       self.evaluate(distribution.extended.read_var(v0)))

      # Update "sync on write" variable.
      self.evaluate(distribution.group(update1a))
      local_results1 = self.evaluate(
          distribution.experimental_local_results(v1))
      self.assertEqual(3.0 + 7.0, local_results1[0])
      # Writes are synchronized for v1, only the argument to assign_add on
      # device[0] is used.
      self.assertEqual(3.0 + 7.0, local_results1[1])
      self.assertEqual(3.0 + 7.0,
                       self.evaluate(distribution.extended.read_var(v1)))

      # Update using state_ops.assign_add global function.
      def update_state_ops_fn():
        update0 = state_ops.assign_add(v0, 11.0 * replica_id_plus_one())
        update1 = state_ops.assign_add(v1, 13.0 * replica_id_plus_one())
        return update0, update1

      update0b, update1b = distribution.extended.call_for_each_replica(
          update_state_ops_fn)
      self.evaluate(distribution.group(update0b))

      # Update "sync on read" variable.
      local_results = self.evaluate(distribution.experimental_local_results(v0))
      self.assertEqual(2.0 + 5.0 + 11.0, local_results[0])
      self.assertEqual(2.0 + 2 * 5.0 + 2 * 11.0, local_results[1])
      self.assertEqual(2.0 + 5.0 + 11.0,
                       self.evaluate(distribution.extended.read_var(v0)))

      # Update "sync on write" variable.
      self.evaluate(distribution.group(update1b))
      local_results1 = self.evaluate(
          distribution.experimental_local_results(v1))
      self.assertEqual(3.0 + 7.0 + 13.0, local_results1[0])
      self.assertEqual(3.0 + 7.0 + 13.0, local_results1[1])
      self.assertEqual(3.0 + 7.0 + 13.0,
                       self.evaluate(distribution.extended.read_var(v1)))

  def testNoneSynchronizationWithGetVariable(self, distribution):
    with distribution.scope():
      with self.assertRaisesRegex(
          ValueError, "`NONE` variable synchronization mode is not "
          "supported with "):
        variable_scope.get_variable(
            "v", [1],
            synchronization=variable_scope.VariableSynchronization.NONE)

  def testNoneSynchronizationWithVariable(self, distribution):
    with distribution.scope():
      with self.assertRaisesRegex(
          ValueError, "`NONE` variable synchronization mode is not "
          "supported with "):
        variable_v1.VariableV1(
            1.0,
            name="v",
            synchronization=variable_scope.VariableSynchronization.NONE)

  def testInvalidSynchronizationWithVariable(self, distribution):
    with distribution.scope():
      with self.assertRaisesRegex(
          ValueError, "Invalid variable synchronization mode: Invalid for "
          "variable: v"):
        variable_v1.VariableV1(1.0, name="v", synchronization="Invalid")

  def testInvalidAggregationWithGetVariable(self, distribution):
    with distribution.scope():
      with self.assertRaisesRegex(
          ValueError, "Invalid variable aggregation mode: invalid for "
          "variable: v"):
        variable_scope.get_variable(
            "v", [1],
            synchronization=variable_scope.VariableSynchronization.ON_WRITE,
            aggregation="invalid")

  def testInvalidAggregationWithVariable(self, distribution):
    with distribution.scope():
      with self.assertRaisesRegex(
          ValueError, "Invalid variable aggregation mode: invalid for "
          "variable: v"):
        variable_v1.VariableV1(
            1.0,
            name="v",
            synchronization=variable_scope.VariableSynchronization.ON_WRITE,
            aggregation="invalid")

  def testNonMatchingVariableCreation(self, distribution):

    def model_fn(name):
      v = variable_v1.VariableV1(1.0, name=name)
      distribute_lib.get_replica_context().merge_call(lambda _: _)
      return v

    with distribution.scope():
      names = values.PerReplica(("foo", "bar"))
      with self.assertRaises(RuntimeError):
        _ = distribution.extended.call_for_each_replica(model_fn, args=(names,))

  def testSyncOnReadVariable(self, distribution):

    all_v_sum = {}
    all_v_mean = {}
    components_sum = {}
    components_mean = {}

    def model_fn():
      replica_id = self.evaluate(_replica_id())
      v_sum = variable_v1.VariableV1(
          1.0,
          synchronization=variable_scope.VariableSynchronization.ON_READ,
          aggregation=variable_scope.VariableAggregation.SUM)
      v_mean = variable_v1.VariableV1(
          4.0,
          synchronization=variable_scope.VariableSynchronization.ON_READ,
          aggregation=variable_scope.VariableAggregation.MEAN)
      self.assertTrue(distribute_utils.is_sync_on_read(v_sum))
      self.assertTrue(distribute_utils.is_sync_on_read(v_mean))
      updates = [
          v_sum.assign_add(2.0 + replica_id),
          v_mean.assign(6.0 * replica_id)
      ]
      all_v_sum[replica_id] = v_sum
      all_v_mean[replica_id] = v_mean
      c_sum = v_sum._get()
      c_mean = v_mean._get()
      components_sum[replica_id] = c_sum
      components_mean[replica_id] = c_mean
      self.assertIsNot(v_sum, c_sum)
      self.assertIsNot(v_mean, c_mean)
      return updates, v_sum, v_mean, c_sum, c_mean

    with distribution.scope():
      # Create "sum" and "mean" versions of SyncOnReadVariables.
      ret_ops, ret_v_sum, ret_v_mean, regrouped_sum, regrouped_mean = (
          distribution.extended.call_for_each_replica(model_fn))
      # Should see the same wrapping instance in all replicas.
      self.assertIs(all_v_sum[0], ret_v_sum)
      self.assertIs(all_v_mean[0], ret_v_mean)
      self.assertIs(all_v_sum[0], all_v_sum[1])
      self.assertIs(all_v_mean[0], all_v_mean[1])

      # Regroup should recover the same wrapper.
      self.assertIs(ret_v_sum, regrouped_sum)
      self.assertIs(ret_v_mean, regrouped_mean)
      self.assertIsNot(components_sum[0], components_sum[1])
      self.assertIsNot(components_mean[0], components_mean[1])

      # Apply updates
      self.evaluate(variables.global_variables_initializer())
      self.evaluate([
          y for x in ret_ops  # pylint: disable=g-complex-comprehension
          for y in distribution.experimental_local_results(x)
      ])
      expected_sum = 0.0
      expected_mean = 0.0
      for i, _ in enumerate(distribution.extended.worker_devices):
        # Should see different values on different devices.
        v_sum_value = self.evaluate(
            distribution.experimental_local_results(ret_v_sum)[i].read_value())
        v_mean_value = self.evaluate(
            distribution.experimental_local_results(ret_v_mean)[i].read_value())
        expected = i + 3.0
        self.assertEqual(expected, v_sum_value)
        expected_sum += expected
        expected = i * 6.0
        self.assertEqual(expected, v_mean_value)
        expected_mean += expected
      expected_mean /= len(distribution.extended.worker_devices)

      # Without get(device), should return the value you get by
      # applying the reduction across all replicas (whether you use
      # read_var(), get(), or nothing).
      self.assertEqual(expected_sum, self.evaluate(
          distribution.extended.read_var(ret_v_sum)))
      self.assertEqual(expected_mean, self.evaluate(
          distribution.extended.read_var(ret_v_mean)))
      self.assertEqual(expected_sum, self.evaluate(ret_v_sum._get()))
      self.assertEqual(expected_mean, self.evaluate(ret_v_mean._get()))
      self.assertEqual(expected_sum, self.evaluate(ret_v_sum))
      self.assertEqual(expected_mean, self.evaluate(ret_v_mean))

  # TODO(priyag): Update this test to work in eager mode as well.
  def testDynamicRnnVariables(self, distribution):

    def model_fn():
      inputs = constant_op.constant(2 * [2 * [[0.0, 1.0, 2.0, 3.0, 4.0]]])
      cell_fw = rnn_cell_impl.LSTMCell(300)
      cell_bw = rnn_cell_impl.LSTMCell(300)
      (outputs, _) = rnn.bidirectional_dynamic_rnn(
          cell_fw, cell_bw, inputs, dtype=dtypes.float32)
      return outputs

    with context.graph_mode(), distribution.scope():
      result = distribution.extended.call_for_each_replica(model_fn)
      # Two variables are created by the RNN layer.
      self.assertEqual(2, len(result))
      for v in result:
        self.assertIsInstance(v, values.DistributedValues)
        _, v1 = distribution.experimental_local_results(v)
        self.assertStartsWith(v1._op.name, "replica_1/")

  def testSyncOnReadVariableUpdate(self, distribution):

    def model_fn():
      v_sum = variable_v1.VariableV1(
          1.0,
          synchronization=variable_scope.VariableSynchronization.ON_READ,
          aggregation=variable_scope.VariableAggregation.SUM)
      self.assertTrue(distribute_utils.is_sync_on_read(v_sum))
      return v_sum

    def update(var, value):
      return var.assign(value)

    with distribution.scope():
      ret_v_sum = distribution.extended.call_for_each_replica(model_fn)

      # Initialize variables.
      self.evaluate(variables.global_variables_initializer())
      # Assert that the aggregated value of the sync on read var is the sum
      # of the individual values before running the update ops.
      self.assertEqual(
          1.0,
          self.evaluate(
              distribution.experimental_local_results(ret_v_sum)
              [0].read_value()))
      self.assertEqual(2.0, self.evaluate(ret_v_sum))

      # Apply updates.
      update_ops = distribution.extended.update(
          ret_v_sum, update, args=(5.0,), group=False)
      self.evaluate(update_ops)
      # Assert that the aggregated value of the sync on read vars is the sum
      # of the individual values after running the update ops.
      self.assertEqual(
          5.0,
          self.evaluate(
              distribution.experimental_local_results(ret_v_sum)
              [0].read_value()))
      self.assertEqual(10.0, self.evaluate(ret_v_sum))

  def testVarDistributeStrategy(self, distribution):
    with distribution.scope():
      mirrored = variable_v1.VariableV1(1.0)
      sync_on_read = variable_v1.VariableV1(
          1.0, synchronization=variable_scope.VariableSynchronization.ON_READ)
      self.assertIs(distribution, mirrored.distribute_strategy)
      self.assertIs(distribution, sync_on_read.distribute_strategy)

  def testInitializer(self, distribution, mode):
    if mode == "graph":
      self.skipTest("Skip graph mode")

    temp_dir = self.get_temp_dir()

    class Model(tracking_util.Checkpoint):

      def __init__(self):
        self._v = variables.Variable(1.0)

    with distribution.scope():
      m = Model()
    save.save(m, temp_dir)

    g = ops.Graph()
    with g.as_default():
      with distribution.scope():
        load.load(temp_dir)

      for v in ops.get_collection(ops.GraphKeys.GLOBAL_VARIABLES):
        self.assertIsNotNone(v.initializer)

  def testCustomGradient(self, distribution):

    class CustomModel:

      def __init__(self):
        self._v = variables.Variable(1.0)

      def __call__(self):

        @custom_gradient.recompute_grad
        def _call():
          return self._v + 1

        return _call()

    with distribution.scope():
      model = CustomModel()

      @def_function.function
      def train_step():

        def replica_step():
          with backprop.GradientTape() as tape:
            result = model()
          return tape.gradient(result, [model._v])

        return distribution.run(replica_step)

    grads = distribution.experimental_local_results(train_step())
    self.assertLen(grads, distribution.num_replicas_in_sync)

if __name__ == "__main__":
  test.main()


# -*- coding: utf-8 -*-
"""
Created on Thu May  4 11:48:39 2023

@author: alexc
"""

# IMPORTS
import pandas as pd
import cv2
import skimage
from skimage.feature import hog

# HOG parameters
orientations = 9
pixels_per_cell = (8, 8)
cells_per_block = (2, 2)
def extract_hog_features(image):
    return hog(image, orientations=orientations, pixels_per_cell=pixels_per_cell,
               cells_per_block=cells_per_block, channel_axis=-1)

def extract_color_histogram(image):
    hist = cv2.calcHist([image], [0, 1, 2], None, [8, 8, 8], [0, 256, 0, 256, 0, 256])
    hist = cv2.normalize(hist, hist).flatten()
    return hist

def extract_lbp_features(image):
    gray = skimage.color.rgb2gray(image)
    lbp = skimage.feature.local_binary_pattern(gray, P=8, R=1)
    return lbp.flatten()

def get_features(df: pd.DataFrame, features: str='hog_features'):
    # GET HOG FEATURES
    if features == 'hog_features':
        df[features] = df['image'].apply(lambda x: extract_hog_features(x))
    elif features == 'color_histogram':
        df[features] = df['image'].apply(lambda x: extract_color_histogram(x))
    elif features == 'lbp_features':
        df[features] = df['image'].apply(lambda x: extract_lbp_features(x))

    # make each position of the array a column of the df
    hog_df = pd.DataFrame(df[features].values.tolist())
    hog_df.columns = ['feature{}'.format(i) for i in range(hog_df.shape[1])]
    df = pd.concat([df, hog_df], axis=1)
    df = df.drop([features, 'image', 'index'], axis=1)
    df = df.dropna(axis=1)
    return df


import copy
from shared import get_positions, find_locations

with open("year_2015/input_19.txt", encoding="utf-8") as f:
    contents = f.readlines()

def parse_molecule(string):
    output = []
    buffer = ""
    for character in string:
        if character.lower() == character:
            buffer += character
        else:
            output.append(buffer)
            buffer = character
    if len(buffer) > 0:
        output.append(buffer)
    return [m for m in output if len(m) > 0]

def replace_list(input_list, value, replacement, max_replacements=None):
    new_list = copy.deepcopy(input_list)
    if max_replacements is None:
        max_replacements = len(input_list)
    current_replacements = 0
    for index, original_value in enumerate(input_list):
        if original_value == value:
            new_list[index] = replacement
            current_replacements += 1
            if current_replacements >= max_replacements:
                return new_list

    return new_list

contents = [line.strip() for line in contents]
molecule_string = contents[-1]
contents = contents[:-2]

molecule = parse_molecule(molecule_string)

replacement_list = []
replacements = {}
constructions = {}
for line in contents:
    input_value, output_value = line.split(" => ")
    replacement_list.append((input_value, parse_molecule(output_value)))
    if replacements.get(input_value) is None:
        replacements[input_value] = []
    replacements[input_value].append(parse_molecule(output_value))
    replacements[input_value].sort(key=len)
    constructions[output_value] = input_value

def part1():
    generated = []

    for key, values in replacements.items():
        for value in values:
            positions = get_positions(molecule, key)
            for position in positions:
                new_molecule = copy.deepcopy(molecule)
                new_molecule[position] = value
                new_molecule = [item for sublist in new_molecule for item in sublist]
                generated.append("".join(new_molecule))

    return len(set(generated))

def part2_ll():

    # Stupidly slow. I would guess this would take years to run at a minimum

    stack = [(0, ["e"])]

    solutions = []

    iterations = 0

    seen = set()

    while True:
        iterations += 1
        if iterations % 1000 == 0:
            print(iterations, len(stack), stack[len(stack) - 10000])
        if len(stack) == 0:
            break

        stack_count, last_value = stack.pop()

        if last_value == molecule:
            solutions.append(stack_count)
            continue

        if len(last_value) >= len(molecule):
            continue

        remaining_length = len(molecule) - len(last_value)

        for atom_index, atom in enumerate(last_value):
            for replacement in replacements.get(atom, []):
                if len(replacement) > remaining_length:
                    break
                new_attempt = (
                    last_value[:atom_index] + replacement + last_value[atom_index + 1 :]
                )
                j = "".join(new_attempt)
                if j in seen:
                    continue
                seen.add(j)
                stack.append((stack_count + 1, new_attempt))

    return min(solutions)

def part2():

    molecule_str = "".join(molecule)

    stack = [(0, molecule_str)]

    reverses = list(constructions.items())
    reverses.sort(key=lambda x: len(x[0]))

    while True:
        if len(stack) == 0:
            break

        count, m = stack.pop()

        if m == "e":
            return count

        for compound, derivative in reverses:
            if compound not in m:
                continue

            locations = find_locations(m, compound)
            for location in locations:
                new_molecule = m[:location] + derivative + m[location + len(compound) :]
                stack.append((count + 1, new_molecule))

    return None

print("Part 1:", part1())
print("Part 2:", part2())


import copy
from typing import Any, Callable, List, Optional, Tuple

from dm_alchemy import symbolic_alchemy
from dm_alchemy import symbolic_alchemy_bots
from dm_alchemy import symbolic_alchemy_trackers
from dm_alchemy.types import stones_and_potions
from dm_alchemy.types import utils
import numpy as np
import tree

AlignedStoneIndex = stones_and_potions.AlignedStoneIndex
PerceivedPotionIndex = stones_and_potions.PerceivedPotionIndex
PerceivedStone = stones_and_potions.PerceivedStone

def get_envs_and_bots(
    env: symbolic_alchemy.SymbolicAlchemy,
    bot_from_env: Callable[[symbolic_alchemy.SymbolicAlchemy],
                           symbolic_alchemy_bots.SymbolicAlchemyBot],
    num_bots: int,
    add_trackers_to_env: Callable[[symbolic_alchemy.SymbolicAlchemy], None]
) -> Tuple[List[symbolic_alchemy.SymbolicAlchemy],
           List[symbolic_alchemy_bots.SymbolicAlchemyBot]]:
  """Gets several copies of the environment and bots to run on them.

  Args:
    env: The base environment to make copies of.
    bot_from_env: A callable which given an environment creates a bot to run on
      it.
    num_bots: The number of bots and environment copies to make.
    add_trackers_to_env: A callable which adds any trackers required to the
      environment copies.

  Returns:
    A list of copies of the environment.
    A list of bots to run on copies of the environment.
  """
  env_without_bot_running_trackers = copy.deepcopy(env)
  if env_without_bot_running_trackers:
    env_without_bot_running_trackers.trackers = {}
    add_trackers_to_env(env_without_bot_running_trackers)
  envs = [copy.deepcopy(env_without_bot_running_trackers)
          for _ in range(num_bots)]
  bots = [bot_from_env(e) for e in envs]
  return envs, bots

class BotRunningTracker(symbolic_alchemy_trackers.SymbolicAlchemyTracker):
  """Run bots which take actions whenever an action is taken in the environment."""

  NAME = 'bot_runner'

  @property
  def name(self) -> str:
    return self.NAME

  def __init__(
      self, env: symbolic_alchemy.SymbolicAlchemy,
      bot_from_env: Callable[[symbolic_alchemy.SymbolicAlchemy],
                             symbolic_alchemy_bots.SymbolicAlchemyBot],
      num_bots: int,
      add_trackers_to_env: Callable[[symbolic_alchemy.SymbolicAlchemy], None]):
    self.envs, self.bots = get_envs_and_bots(
        env, bot_from_env, num_bots, add_trackers_to_env)

  def episode_start(self, unused_chemistry: utils.Chemistry) -> None:
    """Resets all environments when an episode has started."""
    for env in self.envs:
      env.reset()

  def action_and_outcome(
      self, action: utils.TypeBasedAction,
      unused_outcome: Optional[PerceivedStone],
      unused_action_info: symbolic_alchemy_trackers.ActionInfo
  ) -> None:
    """Lets bots take an action when an action is taken in the main environment."""
    del unused_outcome, unused_action_info
    # Only take an action if a potion is used (actions to put stones in the
    # cauldron will happen automatically when the end trial action is selected).
    if action.using_potion:
      for bot, env in zip(self.bots, self.envs):
        new_action = bot.select_action()
        # Don't select end trial actions as this will be done when the trial
        # ends in the original environment.
        if new_action.end_trial:
          continue
        symbolic_alchemy.take_simplified_action(new_action, env)

  def trial_end(self) -> None:
    """Ends the trial in all copies of the environment."""
    for env in self.envs:
      symbolic_alchemy.take_simplified_action(
          utils.SlotBasedAction(end_trial=True), env)

  def episode_returns(self) -> Any:
    """Gets returns from trackers on environment copies."""
    return tree.map_structure(lambda *args: np.mean(args, axis=0), *tuple(
        env.episode_returns() for env in self.envs))

  def default_returns(self, num_trials: int, num_actions_per_trial: int) -> Any:
    """Gets a set of default returns."""
    ep_returns = self.envs[0].episode_returns()
    def to_float(arg: Any) -> Any:
      if isinstance(arg, np.ndarray):
        return arg.astype(float)
      return float(arg)

    return tree.map_structure(to_float, ep_returns)


""" This grabs data from the files on COSMA and makes them into a nice pickled
    format for local development """

import survis
import os
import pickle
from tqdm import tqdm

# ---- Global Parameters
snapshot = 96
bbox_x = [-40, 40]
bbox_y = bbox_x
res_elem_lr = 0.5
res_elem_nr = 0.2
res_lr = survis.helper.get_res(res_elem_lr, bbox_x, bbox_y)
res_nr = survis.helper.get_res(res_elem_nr, bbox_x, bbox_y)
# ----------------------

def grab_names():
    """ The simulations live in a directory where they are the only directories
        (but not the only files!) so we must clean os.listdir() """

    output = []
    original = os.listdir()

    for filename in original:
        if "." in filename:
            continue
        else:
            output.append(filename)

    return output

if __name__ == "__main__":
    # Run in scripting mode, and actually perform the analysis
    output = {}

    for simulation in tqdm(grab_names()):
        filename = "{}/snapshot_{:03d}.hdf5".format(simulation, snapshot)

        if "lowres" in simulation:
            data = survis.analysis.CommonDataObject(filename, res_lr, bbox_x, bbox_y, res_elem_lr)
        else:
            data = survis.analysis.CommonDataObject(filename, res_nr, bbox_x, bbox_y, res_elem_nr)

        try:
            if "default" in simulation:
                data.sound_speed = survis.toomre.sound_speed

            tqdm.write("Attempting to analyse {} {}".format(simulation, snapshot))
            data.run_analysis()
            tqdm.write("Analysis of {} {} successful.".format(simulation, snapshot))
        except:
            print("Snapshot {} {} not found, skipping.".format(simulation, snapshot))
            continue

        output[simulation] = data

    # Now we pickle the data ready for download

    with open('snapshot_{:03d}_data.pkl'.format(snapshot), 'wb') as pck:
        pickle.dump(output, pck)


import json
from collections import OrderedDict
import urllib3
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

def return_gist_id():
    return {
        "hin": "a467db04321a29414cd87e04b0c901d1"
    }

def download_json(lang):
    http = urllib3.PoolManager()
    try:
        res = json.loads(http.request('GET', 'https://api.github.com/gists/' +
                                      return_gist_id()[lang], headers={'user-agent': 'brailler'}).data.decode("utf-8").replace("'", '"'), object_pairs_hook=OrderedDict)
        data = res["files"][list(res["files"].keys())[0]]['content']
        with open('brailler/{}_to_brl.json'.format(lang), 'w') as outfile:
            outfile.write(data)
    except Exception as e:
        print("There was an error downloading . .")
        print(e)

def get_json(lang="hin"):
    try:
        openfile = open("brailler/{}_to_brl.json".format(lang), "r")
        jsonfile = json.loads(
            openfile.read(), object_pairs_hook=OrderedDict)[0]
        return jsonfile
    except FileNotFoundError:
        print("Language pack {} not found. Downloading...".format(lang))
        download_json(lang)
        openfile = open("brailler/{}_to_brl.json".format(lang), "r")
        jsonfile = json.loads(
            openfile.read(), object_pairs_hook=OrderedDict)[0]
        return jsonfile


"""
Goals:
    1. Working Buttons through a Constructor
    2. Create a Display for the File's contents
    3. Read & Write to a File

    By: Jon Martin
"""

from tkinter import *

#creating the window
root=Tk()
"""root.geometry('800x500')"""
root.title("Test GUI")

class Application(Frame): #Constructor
#Constructor for Buttons
    def __init__(self,master):
        #Initializes the Frame
        Frame.__init__(self,master)
        self.grid()
        self.create_widgets()

    def create_widgets(self): #Method
        #button that reads the file
        self.button=Button(self,
                            text="Read",
                            command=self.read_file)
        self.button.grid(row=1,
                         column=1,
                         sticky=NW)
        #description
        self.instructions=Label(self,
                                text="Enter new text here:")
        self.instructions.grid(row=0,
                               column=0,
                               sticky=W)
        #text entry box
        self.entry=Entry(self)
        self.entry.grid(row=0,
                        column=0,
                        sticky=E)
        #button that writes the file
        self.submit_button=Button(self,
                                  text="Write",
                                  command=self.write_file)
        self.submit_button.grid(row=0,
                                column=1,
                                sticky=W)
        #output
        self.text=Text(self,
                       width=35,
                       height=50,
                       wrap=WORD)
        self.text.grid(row=1,
                       column=0,
                       sticky=W)

    def read_file(self): #Method
        #reads the file
        with open("page.txt") as f:
            self.text.delete('1.0',END)#deletes what was in the text box
            message=f.read()
            """message=f.readlines()#pulls the file's contents line by line in an array"""
            self.text.insert(0.0,str(message))#puts the file's contents in the text box

    def write_file(self):
        #writes to the file
        with open("page.txt","w") as f:
            entry=self.entry.get()
            self.entry.delete(0,'end')
            f.write(entry)
            self.text.delete('1.0',END)#deletes what was in the text box
            self.text.insert(0.0,str(entry))#puts the file's contents in the text box

app=Application(root)

root.mainloop() #Needed for the window. Ends the program, commands after this won't run.


import torch
from torchvision import transforms
import torchvision.datasets as datasets
from . import info_mappings

class ImageFolderWithPaths(datasets.ImageFolder):
    """Custom dataset that includes image file paths. Extends
    torchvision.datasets.ImageFolder

    Adapted from:
    https://gist.github.com/andrewjong/6b02ff237533b3b2c554701fb53d5c4d
    """

    def __init__(self, *args, **kwargs):

        if "info_mapping" in kwargs.keys():
            self.info_mapping = kwargs["info_mapping"]
            del kwargs["info_mapping"]
        else:
            self.info_mapping = info_mappings.ImageNetInfoMapping()

        super(ImageFolderWithPaths, self).__init__(*args, **kwargs)

    def __getitem__(self, index):
        """override the __getitem__ method. This is the method that dataloader calls."""
        # this is what ImageFolder normally returns
        (sample, target) = super(ImageFolderWithPaths, self).__getitem__(index)

        # the image file path
        path = self.imgs[index][0]
        _, _, _, new_target = self.info_mapping(path)
        original_tuple = (sample, new_target)

        # make a new tuple that includes original and the path
        tuple_with_path = (original_tuple + (path,))
        return tuple_with_path

class PytorchLoader(object):
    """Pytorch Data loader"""

    def __call__(self, path, resize, batch_size, num_workers,
                 info_mapping=None):
        """
        Data loader for pytorch models
        :param path:
        :param resize:
        :param batch_size:
        :param num_workers:
        :return:
        """
        normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406],
                                         std=[0.229, 0.224, 0.225])

        if resize:
            transformations = transforms.Compose([
                transforms.Resize(256),
                transforms.CenterCrop(224),
                transforms.ToTensor(),
                normalize,
            ])
        else:
            transformations = transforms.Compose([
                transforms.ToTensor(),
                normalize,
            ])

        loader = torch.utils.data.DataLoader(
            ImageFolderWithPaths(path, transformations,
                                 info_mapping=info_mapping),
            batch_size=batch_size, shuffle=False,
            num_workers=num_workers, pin_memory=True)

        return loader


"""
@author: Magdalena Jaśkiewicz 233968
"""
import numpy as np
import random

from MinMax import MinMax
from Particle import Particle

class PSO:
    def __init__(self, adaptation_function, number_of_particles, omega, fi1, fi2, n_dim, bounds, min_or_max,
                 number_of_iterations):
        """
        Particle swarm algorithm
        :param adaptation_function: the goal function
        :param number_of_particles: int
        :param omega: float - inertia parameter
        :param fi1: float - the parameter of the molecule's confidence in its own knowledge
        :param fi2: float - the parameter of the molecule's confidence in the swarm knowledge
        :param n_dim: int - number of dimensions
        :param bounds: vector of tuples - bounds for every dimension
        :param min_or_max: MinMax enum - minimum or maximum
        :param number_of_iterations: int
        """
        self.adaptation_function = adaptation_function
        self.number_of_particles = number_of_particles
        self.omega = omega
        self.fi1 = fi1
        self.fi2 = fi2
        self.n_dim = n_dim
        self.bounds = bounds
        self.min_or_max = min_or_max
        self.number_of_iterations = number_of_iterations
        self.best_particle_position = np.zeros(n_dim)
        self.best_particle_score = adaptation_function(self.best_particle_position)
        self.swarm = []

    def __initialize_swarm(self):
        swarm = []
        for particle in range(self.number_of_particles):
            position_vec = self.__init_position_vec()
            function = self.adaptation_function
            initial_velocity_vec = self.__init_velocity_vec()
            swarm.append(Particle(position_vec, function, initial_velocity_vec))
        self.swarm = swarm

    def __init_position_vec(self):
        vec = np.zeros(self.n_dim)
        for dim in range(self.n_dim):
            vec[dim] = random.uniform(self.bounds[dim][0], self.bounds[dim][1])
        return vec

    def __init_velocity_vec(self):
        vec = np.zeros(self.n_dim)
        for dim in range(self.n_dim):
            vec[dim] = random.uniform(0.0, self.bounds[dim][1]/2.0)
        return vec

    def __move_particles(self):
        swarm = self.swarm
        for particle in swarm:
            particle.position_vec = self.__check_bounds(particle.position_vec + particle.velocity_vec, particle)
        self.swarm = swarm

    def __check_bounds(self, position_vec, particle):
        for dim in range(self.n_dim):
            if position_vec[dim] < self.bounds[dim][0] or position_vec[dim] > self.bounds[dim][1]:
                position_vec[dim] = particle.position_vec[dim] - particle.velocity_vec[dim]
        return position_vec

    def __score_particles(self):
        swarm = self.swarm
        for particle in swarm:
            particle.count_score()
            if self.min_or_max == MinMax.MAX:
                if particle.historical_best_score < particle.score:
                    particle.historical_best_score = particle.score
                    particle.historical_best_position = particle.position_vec
                if self.best_particle_score < particle.score:
                    self.best_particle_score = particle.score
                    self.best_particle_position = particle.position_vec
            elif self.min_or_max == MinMax.MIN:
                if particle.historical_best_score > particle.score:
                    particle.historical_best_score = particle.score
                    particle.historical_best_position = particle.position_vec
                if self.best_particle_score > particle.score:
                    self.best_particle_score = particle.score
                    self.best_particle_position = particle.position_vec
        self.swarm = swarm

    def __actualize_velocity_of_particles(self):
        swarm = self.swarm
        omega = self.omega
        fi1 = self.fi1
        fi2 = self.fi2
        r1 = self.__draw_r()
        r2 = self.__draw_r()

        for particle in swarm:
            new_velocity = omega * particle.velocity_vec + fi1 * r1 * \
                           (particle.position_vec - particle.historical_best_position) + fi2 * r2 * \
                           (particle.position_vec - self.best_particle_position)
            particle.velocity_vec = new_velocity
        self.swarm = swarm

    def __draw_r(self):
        vec = np.zeros(self.n_dim)
        for dim in range(self.n_dim):
            vec[dim] = random.uniform(0.0, self.bounds[dim][1] / 2.0)
        return vec

    def perform_calculations(self):
        self.__initialize_swarm()
        for iter in range(self.number_of_iterations):
            self.__move_particles()
            self.__score_particles()
            self.__actualize_velocity_of_particles()

    def get_result(self):
        return self.best_particle_position, self.best_particle_score


from airflow import DAG
from datetime import datetime, timedelta
import os
import json

def create_dag(dag_id, schedule_interval, looker_name, csv_filter, pdf_filter, files_format, bucket_name, bucket_folder, emails, email_subject):
    """
    Creates a DAG for the given attributes
    The attributes are loaded in a json file in the same folder as this script

    Attributes
    ----------
    dag_id: string
        Name of the Airflow dag
    schedule_interval: Cron schedule expressions (Ex. 30 12 * * *)
        Schedule interval for the dag execution
    looker_name : string
        Looker dashboard name to be searched in the Looker server.
    csv_filter : dictionary
        Filter for all the queries of the tiles in the Looker dashboard (this is used for CSV files)
        Value for no filters is {'none': {}}
    pdf_filter : dictionary
        Filter for all the views of the tiles in the Looker dashboard (this is used for PDF files)
        Value for no filters is {'none': {}}
    files_format : string
        Created files format, possible entries: PDF, CSV, PDF_and_CSV
    bucket_name : string
        Bucket GCP name to store the files
    bucket_folder : string
        Bucket GCP folder to store the files
    emails : comma separated email addresses (Ex: rodrigo.pizzano@pedidosya.com, alan.torre@pedidosya.com, andres.sorza@pedidosya.com)
        List of email recipients
    email_subject : string
        Email subject details
    """
    import importlib

    # Import de modulos
    looker_module = importlib.import_module(
        "dags.utils.looker_module")
    email_module = importlib.import_module(
        "dags.utils.email_module")
    slack_module = importlib.import_module(
        "dags.utils.slack_module")
    sensor_module = importlib.import_module(
        "dags.utils.sensor_module")

    # Configuracion DAG #
    config = dict(
        dag_id=dag_id,
        default_args=dict(
            owner='rodrigo_pizzano',
            depends_on_past=False,
            start_date=datetime(2022, 8, 1),
            execution_timeout=timedelta(minutes=60),
            email='rodrigo.pizzano@outlook.com',
            email_on_failure=True,
            email_on_retry=False,
            retries=3,
            retry_delay=timedelta(minutes=10),
        ),
        catchup=False,
        schedule_interval=schedule_interval,
    )

    with DAG(**config) as dag:

        # Operadores
        start = sensor_module.dummy('start')

        looker_files_to_gcp_bucket = looker_module.looker_csv_pdf_to_gcp_operator(
            task_id='looker_files_to_gcp_bucket',
            looker_name=looker_name,
            csv_filter=csv_filter,
            pdf_filter=pdf_filter,
            files_format=files_format,
            bucket_name=bucket_name,
            bucket_folder=bucket_folder
        )

        looker_gcp_bucket_files_to_email = email_module.gcp_files_to_email_operator(
            task_id='looker_gcp_bucket_files_to_email',
            bucket_name=bucket_name,
            bucket_folder=bucket_folder,
            emails=emails,
            email_subject=email_subject
        )

        end = sensor_module.dummy('end')

        slack_ok = slack_module.slack_ok(dag=dag)

        slack_fail = slack_module.slack_fail(dag=dag)

        # Orden de operadores
        start >> looker_files_to_gcp_bucket >> looker_gcp_bucket_files_to_email >> end
        end >> [slack_ok, slack_fail]

    return dag

for file in os.listdir("/dags/looker"):
    if os.path.splitext(file)[1] == '.json':

        with open(f"/dags/looker/{file}", 'r') as f:
            file_json = json.loads(f.read())

            dag_id = file_json["dagId"]
            schedule_interval = file_json["scheduleInterval"]
            looker_name = file_json["lookerName"]
            csv_filter = file_json["csvFilter"]
            pdf_filter = file_json["pdfFilter"]
            files_format = file_json["filesFormat"]
            bucket_name = file_json["bucketName"]
            bucket_folder = file_json["bucketFolder"]
            emails = file_json["emails"]
            email_subject = file_json["emailSubject"]

            globals()[dag_id] = create_dag(
                dag_id,
                schedule_interval,
                looker_name,
                csv_filter,
                pdf_filter,
                files_format,
                bucket_name,
                bucket_folder,
                emails,
                email_subject)


# -*- coding: utf-8 -*-
from math import pi

import grgsm
import osmosdr
import pmt
from gnuradio import blocks
from gnuradio import gr

class grgsm_capture(gr.top_block):
    def __init__(self, fc, gain, samp_rate, ppm, arfcn, cfile=None, burst_file=None, band=None, verbose=False,
                 gsmtap=False, rec_length=None, args=""):

        gr.top_block.__init__(self, "Gr-gsm Capture")

        ##################################################
        # Parameters
        ##################################################
        self.fc = fc
        self.gain = gain
        self.samp_rate = samp_rate
        self.ppm = ppm
        self.arfcn = arfcn
        self.cfile = cfile
        self.burst_file = burst_file
        self.band = band
        self.verbose = verbose
        self.gsmtap = gsmtap
        self.shiftoff = shiftoff = 400e3
        self.rec_length = rec_length

        ##################################################
        # Processing Blocks
        ##################################################

        self.rtlsdr_source = osmosdr.source(args="numchan=" + str(1) + " " + args)
        self.rtlsdr_source.set_sample_rate(samp_rate)
        self.rtlsdr_source.set_center_freq(fc - shiftoff, 0)
        self.rtlsdr_source.set_freq_corr(ppm, 0)
        self.rtlsdr_source.set_dc_offset_mode(2, 0)
        self.rtlsdr_source.set_iq_balance_mode(2, 0)
        self.rtlsdr_source.set_gain_mode(True, 0)
        self.rtlsdr_source.set_gain(gain, 0)
        self.rtlsdr_source.set_if_gain(20, 0)
        self.rtlsdr_source.set_bb_gain(20, 0)
        self.rtlsdr_source.set_antenna("", 0)
        self.rtlsdr_source.set_bandwidth(250e3 + abs(shiftoff), 0)
        self.blocks_rotator = blocks.rotator_cc(-2 * pi * shiftoff / samp_rate)

        if self.rec_length is not None:
            self.blocks_head_0 = blocks.head(gr.sizeof_gr_complex, int(samp_rate * rec_length))

        if self.verbose or self.burst_file:
            self.gsm_receiver = grgsm.receiver(4, ([self.arfcn]), ([]))
            self.gsm_input = grgsm.gsm_input(
                ppm=0,
                osr=4,
                fc=fc,
                samp_rate_in=samp_rate,
            )
            self.gsm_clock_offset_control = grgsm.clock_offset_control(fc - shiftoff, samp_rate, osr=4)

        if self.burst_file:
            self.gsm_burst_file_sink = grgsm.burst_file_sink(self.burst_file)

        if self.cfile:
            self.blocks_file_sink = blocks.file_sink(gr.sizeof_gr_complex * 1, self.cfile, False)
            self.blocks_file_sink.set_unbuffered(False)

        if self.verbose:
            self.gsm_bursts_printer_0 = grgsm.bursts_printer(pmt.intern(""),
                                                             False, False, False, False)
        if self.gsmtap:
            self.bcch_demapper = grgsm.gsm_bcch_ccch_demapper(0)
            self.cch_decoder = grgsm.control_channels_decoder()
            self.socket_pdu_server = blocks.socket_pdu("UDP_SERVER", "127.0.0.1", "4729", 10000)
            self.socket_pdu = blocks.socket_pdu("UDP_CLIENT", "127.0.0.1", "4729", 10000)

        ##################################################
        # Connections
        ##################################################

        if self.rec_length is not None:  # if recording length is defined connect head block after the source
            self.connect((self.rtlsdr_source, 0), (self.blocks_head_0, 0))
            self.connect((self.blocks_head_0, 0), (self.blocks_rotator, 0))
        else:
            self.connect((self.rtlsdr_source, 0), (self.blocks_rotator, 0))

        if self.cfile:
            self.connect((self.blocks_rotator, 0), (self.blocks_file_sink, 0))

        if self.verbose or self.burst_file:
            self.connect((self.gsm_input, 0), (self.gsm_receiver, 0))
            self.connect((self.blocks_rotator, 0), (self.gsm_input, 0))
            self.msg_connect(self.gsm_clock_offset_control, "ctrl", self.gsm_input, "ctrl_in")
            self.msg_connect(self.gsm_receiver, "measurements", self.gsm_clock_offset_control, "measurements")

            if self.burst_file:
                self.msg_connect(self.gsm_receiver, "C0", self.gsm_burst_file_sink, "in")
            if self.verbose:
                self.msg_connect(self.gsm_receiver, "C0", self.gsm_bursts_printer_0, "bursts")
            if self.gsmtap:
                self.msg_connect(self.gsm_receiver, "C0", self.bcch_demapper, "bursts")
                self.msg_connect(self.bcch_demapper, "bursts", self.cch_decoder, "bursts")
                self.msg_connect(self.cch_decoder, "msgs", self.socket_pdu, "pdus")


import os
import cv2
import time
import numpy as np

ListaNomes = []
ListaImages = []
ListId = []
IdNames = 0

for nome in os.listdir('./Images/'):
    # Verifica se o item é uma pasta
    if os.path.isdir(os.path.join('./Images/', nome)):
        for i in range(1, 20):
            ListaImages.append(cv2.resize(cv2.imread('./Images/' + nome + '/' + str(i) + '.jpg', cv2.IMREAD_GRAYSCALE), (100, 100)))
            ListId.append(IdNames)
        ListaNomes.append(nome)
        IdNames += 1

num_components = 80
height, width = ListaImages[0].shape

imagesFlat = np.array([image.flatten() for image in ListaImages], dtype='float32')
#mean, eigenvectors = cv2.PCACompute(imagesFlat, mean=None, maxComponents=num_components)

recognizer = cv2.face.EigenFaceRecognizer_create(num_components)
print(ListId)

ListId = np.array(ListId)
recognizer.train(imagesFlat, ListId)

cap = cv2.VideoCapture(0)

face_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_alt2.xml')

while True:
    ret, frame = cap.read()

    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    faces = face_cascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=5)

    for (x, y, w, h) in faces:
        cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 2)
        faces = gray[y:y + h, x:x + w]
        image = cv2.resize(faces, (width, height))
        Imageflat = image.flatten().astype('float32')
        #projection = cv2.pcaPOroject(Imageflat.reshape(1, -1), mean, eigenvectors)
        id, confidence = recognizer.predict(image)
        name = ListaNomes[id]
        print("Recognized Face: {}, Confidence: {:.2f}".format(name, confidence))
        break

    cv2.imshow('Face Detection', frame)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

cap.release()
cv2.destroyAllWindows()


# This script locates the files required and puts them into lists
# So we can iterate through them and read their contents
import regex
from glob import *
import os
import sys
import configparser
import __main__ as main

# BASIC PDOX SCRIPT AND HISTORY FILE READING FUNCTIONS

# Get all files from a folder
def all_files_from(folder_path):
    all_files = iglob(folder_path)
    return all_files

# Remove comments from a pdox file
def rm_comments(source_text):
    source_text = ''.join(source_text.split("#")[0].split("\t"))
    return source_text

# Make a list of values on different lines in a given piece of text
def make_list(source_text):
    new_list = source_text.strip().splitlines()
    return new_list

# Find values within a segment of a file inside curly brackets
def get_data_for(key_string, file):
    file = open(file, encoding="utf8")
    retrieved_data = re.findall(key_string + " = {(.*?)}", file.read(), re.S)
    rm_comments(retrieved_data)
    make_list(retrieved_data)
    return retrieved_data

# Get the config file for the file calling this script
# It must be called SCRIPTNAME_config.txt
config_path = main.__file__.split(".py")[0] + "_config.txt"

config = configparser.ConfigParser(allow_no_value = True)
config.read(config_path)

config_data = config._sections

def get_value(section, var, default):
    try:
        if config.get(section, var) != False:
            value = config.get(section,var)
    except:
        print("Invalid configuration '" + var + "'; set as default value: " + default)
        value = default
    print(var + " : " + value)
    return value

def list_options(section):
    try:
        options = config.options(section)
        if len(options) == 0:
            print("No folders specified")
        else:
            print(section + ": " + str(options))
    except:
        print("No "+section+" section in config")
        options = None
    return options

# A config file should have the following sections:

# [in_folders]
# Folders to be accessed and read from
# Each folder can have specific conditions to search for in its value
# If left blank, it will be left to a glob of the whole folder.
in_folders = list_options("in_folders")

# [out_folders]
# Folders into which new files are written
out_folders = list_options("out_folders")

# [important_files]
# Contains a list of important files stored in ./

important_files = list_options("important_files")

# [settings]
# Includes the following settings:

# id_from_filename_only (default = True)
# This gets only the state ID from the filename of states
get_value("settings","id_from_filename_only", "True")

# filetype (default = ".txt")
# Determines the filetypes to be searched
get_value("settings","filetype", ".txt")


#McOsuHelper
#by @yi6dev
#https://github.com/yi6dev/McOsuHelper
#Support: Windows 10
#Python ^3.9

import os
import sys
import zipfile
import threading
import glob
import time

import colorama
import keyboard
import cursor

__version__ = 1.1
__author__  = "yi6dev"

#define system clear command
if "darwin" in sys.platform or "linux" in sys.platform: clear = "clear"
else: clear = "cls"

#app dir path
config_path = os.path.dirname(os.path.abspath(sys.argv[0]))

#hide terminal cursor
try:
    cursor.hide()
except:
    pass

#app logic
class App(object):
    def __init__(self, args) -> None:
        self.colorized = False
        self.autoload = self.__read_configs()[2]

        if not "--no-ascii" in args:
            colorama.init()

            self.colorized = True

        if "--version" in args:
            print(f"version  = v{__version__}")
            print(f"author   = {__author__}")
            print(f"path     = {config_path}")
            return

        #init all
        self.keyhook()
        self.configs()
        self.render()
        self.autoloadhook()

    def keyhook(self):
        keyboard.add_hotkey("ctrl+alt+o", callback=self.__set_osu_path)
        keyboard.add_hotkey("ctrl+alt+d", callback=self.__set_download_path)
        keyboard.add_hotkey("ctrl+alt+l", callback=self.__set_autoload)
        keyboard.add_hotkey("ctrl+alt+i", callback=self.__install)
        keyboard.add_hotkey("ctrl+alt+c", callback=self.__config)
        keyboard.add_hotkey("ctrl+alt+e", callback=self.__exit)

    def autoloadhook(self):
        while 1:
            if self.autoload == "true":
                beatmaps = glob.glob(f"{self.__read_configs()[1]}\*.osz")

                if len(beatmaps):
                    self.__install()

            try:
                time.sleep(1)
            except KeyboardInterrupt:
                os.system(clear)
                return

    def configs(self):
        if not os.path.exists(f"{config_path}\.osupath"):
            osu = open(f"{config_path}\.osupath", "w")
            osu.write("none")
            osu.close()

        if not os.path.exists(f"{config_path}\.downloadpath"):
            download = open(f"{config_path}\.downloadpath", "w")
            download.write("none")
            download.close()

        if not os.path.exists(f"{config_path}\.autoload"):
            autoload = open(f"{config_path}\.autoload", "w")
            autoload.write("false")
            autoload.close()

    def render(self):
        os.system(clear)

        if self.colorized:
            print(f"{colorama.Fore.WHITE}McOsuHelper")
            print(f"{colorama.Fore.LIGHTBLACK_EX}by @yi6dev\n")
            print(f"{colorama.Fore.YELLOW}Options")
            print(f"{colorama.Fore.LIGHTBLACK_EX} - Set osu path                        {colorama.Fore.LIGHTBLUE_EX}CTRL + ALT + O")
            print(f"{colorama.Fore.LIGHTBLACK_EX} - Set download path                   {colorama.Fore.LIGHTBLUE_EX}CTRL + ALT + D")\

            if self.autoload == "false":
                print(f"{colorama.Fore.LIGHTBLACK_EX} - Autoload beatmaps                   {colorama.Fore.LIGHTBLUE_EX}CTRL + ALT + L")
            else:
                print(f"{colorama.Fore.LIGHTBLACK_EX} - {colorama.Fore.LIGHTGREEN_EX}Autoload beatmaps                   {colorama.Fore.LIGHTBLUE_EX}CTRL + ALT + L")

            print(f"{colorama.Fore.LIGHTBLACK_EX} - Install beatmaps                    {colorama.Fore.LIGHTBLUE_EX}CTRL + ALT + I")
            print(f"{colorama.Fore.LIGHTBLACK_EX} - Show config                         {colorama.Fore.LIGHTBLUE_EX}CTRL + ALT + C")
            print(f"{colorama.Fore.LIGHTBLACK_EX} - Exit                                {colorama.Fore.LIGHTBLUE_EX}CTRL + C")

        else:
            print("McOsuHelper")
            print("by @yi6dev\n")
            print("Options")
            print(" - Set osu path                        CTRL + ALT + O")
            print(" - Set download path                   CTRL + ALT + D")
            print(" - Autoload beatmaps                   CTRL + ALT + L")
            print(" - Install beatmaps                    CTRL + ALT + I")
            print(" - Show config                         CTRL + ALT + C")
            print(" - Exit                                CTRL + C")

    def __read_configs(self):
        self.configs()

        osu = open(f"{config_path}\.osupath", "r")
        osu_path = osu.read()
        osu.close()

        download = open(f"{config_path}\.downloadpath", "r")
        download_path = download.read()
        download.close()

        autoload = open(f"{config_path}\.autoload", "r")
        autoload_value = autoload.read()
        autoload.close()

        return osu_path, download_path, autoload_value

    def __set_osu_path(self):
        os.system(clear)

        if self.colorized:
            print(f"{colorama.Fore.WHITE}McOsuHelper")
            print(f"{colorama.Fore.LIGHTBLACK_EX}by @yi6dev\n")

            path = str(input(f"{colorama.Fore.LIGHTGREEN_EX}Osu path > {colorama.Fore.WHITE}"))

            if os.path.exists(path):
                osu = open(f"{config_path}\.osupath", "w")
                osu.write(path)
                osu.close()

                os.system(clear)

                print(f"{colorama.Fore.WHITE}McOsuHelper")
                print(f"{colorama.Fore.LIGHTBLACK_EX}by @yi6dev\n")
                print(f"{colorama.Fore.LIGHTGREEN_EX}Osu path setted to {path}")

            else:
                os.system(clear)

                print(f"{colorama.Fore.WHITE}McOsuHelper")
                print(f"{colorama.Fore.LIGHTBLACK_EX}by @yi6dev\n")
                print(f"{colorama.Fore.LIGHTRED_EX}Incorrect path")

            time.sleep(5)

            self.render()

        else:
            print("McOsuHelper")
            print("by @yi6dev\n")

            path = str(input("Osu path > "))

            if os.path.exists(path):
                osu = open(f"{config_path}\.osupath", "w")
                osu.write(path)
                osu.close()

                os.system(clear)

                print("McOsuHelper")
                print("by @yi6dev\n")
                print(f"Osu path setted to {path}")

            else:
                os.system(clear)

                print("McOsuHelper")
                print("by @yi6dev\n")
                print("Incorrect path")

            time.sleep(5)

            self.render()

    def __set_download_path(self):
        os.system(clear)

        if self.colorized:
            print(f"{colorama.Fore.WHITE}McOsuHelper")
            print(f"{colorama.Fore.LIGHTBLACK_EX}by @yi6dev\n")

            path = str(input(f"{colorama.Fore.LIGHTGREEN_EX}Download path > {colorama.Fore.WHITE}"))

            if os.path.exists(path):
                download = open(f"{config_path}\.downloadpath", "w")
                download.write(path)
                download.close()

                os.system(clear)

                print(f"{colorama.Fore.WHITE}McOsuHelper")
                print(f"{colorama.Fore.LIGHTBLACK_EX}by @yi6dev\n")
                print(f"{colorama.Fore.LIGHTGREEN_EX}Download path setted to {path}")

            else:
                os.system(clear)

                print(f"{colorama.Fore.WHITE}McOsuHelper")
                print(f"{colorama.Fore.LIGHTBLACK_EX}by @yi6dev\n")
                print(f"{colorama.Fore.LIGHTRED_EX}Incorrect path")

            time.sleep(5)

            self.render()

        else:
            print("McOsuHelper")
            print("by @yi6dev\n")

            path = str(input("Download path > "))

            if os.path.exists(path):
                download = open(f"{config_path}\.downloadpath", "w")
                download.write(path)
                download.close()

                os.system(clear)

                print("McOsuHelper")
                print("by @yi6dev\n")
                print(f"Download path setted to {path}")

            else:
                os.system(clear)
                print("McOsuHelper")
                print("by @yi6dev\n")
                print("Incorrect path")

            time.sleep(5)

            self.render()

    def __install(self):
        os.system(clear)

        if self.colorized:
            print(f"{colorama.Fore.WHITE}McOsuHelper")
            print(f"{colorama.Fore.LIGHTBLACK_EX}by @yi6dev\n")

            beatmaps = glob.glob(f"{self.__read_configs()[1]}\*.osz")

            if len(beatmaps):
                #print(f"{colorama.Fore.LIGHTBLACK_EX}Found {len(beatmaps)} beatmaps")
                for beatmap in beatmaps:
                    name = beatmap.split("\\")[-1].replace(".osz", "")
                    print(f"{colorama.Fore.LIGHTGREEN_EX}Installing {colorama.Fore.WHITE}- {colorama.Fore.LIGHTCYAN_EX}{name}")

                    try:
                        os.rename(beatmap, beatmap.replace(".osz", ".zip"))
                        os.mkdir(f"{self.__read_configs()[0]}\Songs\{name}")
                    except FileExistsError:
                        pass

                    with zipfile.ZipFile(beatmap.replace(".osz", ".zip"), 'r') as zip_ref:
                        zip_ref.extractall(f"{self.__read_configs()[0]}\Songs\{name}")

                    os.remove(beatmap.replace(".osz", ".zip"))

                print(f"\n{colorama.Fore.LIGHTYELLOW_EX}Success installed {colorama.Fore.LIGHTCYAN_EX}{len(beatmaps)} {colorama.Fore.LIGHTYELLOW_EX}beatmaps")
                print(f"{colorama.Fore.LIGHTRED_EX}Back to menu {colorama.Fore.WHITE}CTRL + ALT + E")

            else:
                print(f"{colorama.Fore.LIGHTRED_EX}No new beatmaps found")

                time.sleep(3)
                self.render()

        else:
            print("McOsuHelper")
            print("by @yi6dev\n")

            beatmaps = glob.glob(f"{self.__read_configs()[1]}\*.osz")

            if len(beatmaps):
                for beatmap in beatmaps:
                    name = beatmap.split("\\")[-1].replace(".osz", "")
                    print(f"Installing - {name}")

                    try:
                        os.rename(beatmap, beatmap.replace(".osz", ".zip"))
                        os.mkdir(f"{self.__read_configs()[0]}\Songs\{name}")
                    except FileExistsError:
                        pass

                    with zipfile.ZipFile(beatmap.replace(".osz", ".zip"), 'r') as zip_ref:
                        zip_ref.extractall(f"{self.__read_configs()[0]}\Songs\{name}")

                    os.remove(beatmap.replace(".osz", ".zip"))

                print(f"\nSuccess installed {len(beatmaps)} beatmaps")
                print("Back to menu CTRL + ALT + E")

            else:
                print("No new beatmaps found")

                time.sleep(3)
                self.render()

    def __config(self):
        if self.colorized:
            os.system(clear)

            config = self.__read_configs()

            print(f"{colorama.Fore.WHITE}McOsuHelper")
            print(f"{colorama.Fore.LIGHTBLACK_EX}by @yi6dev\n")
            print(f"{colorama.Fore.YELLOW}Configs")
            print(f"{colorama.Fore.LIGHTBLACK_EX} - Osu path            = {colorama.Fore.LIGHTCYAN_EX}{config[0]}")
            print(f"{colorama.Fore.LIGHTBLACK_EX} - Download path       = {colorama.Fore.LIGHTCYAN_EX}{config[1]}")
            print(f"{colorama.Fore.LIGHTBLACK_EX} - Autoload            = {colorama.Fore.LIGHTCYAN_EX}{self.autoload}")
            print(f"{colorama.Fore.LIGHTBLACK_EX} - App version         = {colorama.Fore.LIGHTCYAN_EX}{__version__}\n")
            print(f"{colorama.Fore.LIGHTRED_EX}Back to menu {colorama.Fore.WHITE}CTRL + ALT + E")

        else:
            os.system(clear)

            config = self.__read_configs()

            print("McOsuHelper")
            print("by @yi6dev\n")
            print("Configs")
            print(f" - Osu path            = {config[0]}")
            print(f" - Download path       = {config[1]}")
            print(f" - Autoload            = {self.autoload}")
            print(f" - App version         = {__version__}\n")
            print(f"Back to menu CTRL + ALT + E")

    def __set_autoload(self):
        if self.autoload == "false":
            autoload = open(f"{config_path}\.autoload", "w")
            autoload.write("true")
            autoload.close()

            self.autoload = "true"

        else:
            autoload = open(f"{config_path}\.autoload", "w")
            autoload.write("false")
            autoload.close()

            self.autoload = "false"

        self.render()

    def __exit(self):
        self.render()

#run app
if __name__ == "__main__":
    app = App(sys.argv)


from collections import defaultdict
from subprocess import Popen, PIPE
from GoogleDriveHandler import GoogleDriveHandler
from os import environ
from csv import DictWriter
import re
import socket

def get_gpu_usage():
    CUDA_VISIBLE_DEVICES = environ.get('CUDA_VISIBLE_DEVICES')
    if CUDA_VISIBLE_DEVICES:
        del environ['CUDA_VISIBLE_DEVICES']
    gpu_pid_dict = defaultdict(list)
    gpu_output = Popen(["nvidia-smi", "-q", "-d", "PIDS"], stdout=PIPE, encoding="utf-8")
    gpu_output = gpu_output.communicate()[0].strip().split("\n")
    gpu_num = -1
    for line in gpu_output:
        line = line.strip()
        if line.startswith("GPU "):
            gpu_num += 1
        if line.startswith("Processes"):
            if "None" in line:
                gpu_pid_dict[gpu_num] = []
        if line.startswith("Process ID"):
            pid = re.search("\d+", line).group(0)
            gpu_pid_dict[gpu_num].append(pid)
    user_gpu_dict = defaultdict(set)
    for gpu, pid_list in gpu_pid_dict.items():
        for pid in pid_list:
            pid_output = Popen(["ps", "-u", "-p", pid], stdout=PIPE, encoding="utf-8")
            pid_output = pid_output.communicate()[0].strip().split("\n")
            if len(pid_output) > 1:
                user = pid_output[1].split(" ")[0]
                user_gpu_dict[user].add(gpu)
    return gpu_pid_dict, user_gpu_dict

def write_and_upload_csv(user_gpu_dict):
    drive_handler = GoogleDriveHandler()
    upload_dir = f"{drive_handler.local_root}/Technion/NLP Lab GPU Resources/Usage"
    csv_file = f"{upload_dir}/{socket.gethostname()}.csv"
    with open(csv_file, 'w', newline='') as f:
        fieldnames = ['user', 'num_gpus']
        writer = DictWriter(f, fieldnames=fieldnames)
        writer.writeheader()
        for key, val in user_gpu_dict.items():
            writer.writerow({"user": key, "num_gpus": len(val)})
    print(drive_handler.push_files(csv_file, ["-force"]))

def main():
    _, user_gpu_dict = get_gpu_usage()
    write_and_upload_csv(user_gpu_dict)

if __name__ == "__main__":
    main()


import numpy as np

# file_name = './jump_drop_water_new.txt'
# save_name = './time_span.npy'
# time = np.loadtxt(file_name, delimiter=',',dtype='int')

def to_vector(mat):
	"""Convert categorical data into vector.
	Args:
		mat: onr-hot categorical data.
	Returns:
		out2: vectorized data."""
	out = np.zeros((mat.shape[0],mat.shape[1]))
	out2 = np.zeros((mat.shape[0]))
	for i in range(mat.shape[0]):
		for n, j in enumerate(mat[i]):
			if np.any(j == (np.amax(mat[i]))):
				out[i][n] = 1
				out2[i] = n

	return out2

# all_range = []
# for i in range(len(time)):
# 	time_range = []
# 	for j in range(time[i][0]):
# 		time_range.append(0)
# 	for j in range(time[i][0], time[i][1]):
# 		time_range.append(1)
# 	for j in range(time[i][1], time[i][2]):
# 		time_range.append(2)
# 	for j in range(time[i][2], time[i][3]):
# 		time_range.append(3)
# 	for j in range(time[i][3],160):
# 		time_range.append(4)
# 	print (i, len(time_range))
# 	all_range.append(time_range)

# all_range = np.array(all_range)
# print (all_range.shape)
# print (all_range[3])

# np.save(save_name, all_range)

# data = np.load('tcn_output.npy')

# vec_data = []
# for i in data:
# 	vec_data.append(to_vector(i))

# np.save('./data_files/tcn_time_range.npy', vec_data)

vec_data = np.load('./data_files/tcn_time_range.npy')

note_all = []
for idx, video in enumerate(vec_data):
	note = []
	for i in range(len(video)-1):
		if video[i] != video[i+1]:
			note.append(i)
	print (idx+1, note)
	note_all.append(note)
print (len(note_all))
np.save('./data_files/tcn_time_point.npy', note_all)


from flask import Flask, render_template, render_template_string, request, send_from_directory, url_for
import mysql.connector
from jinja2 import Environment
import plotly.graph_objects as go
import datetime

app = Flask(__name__)
mydb = mysql.connector.connect(
  host="localhost",
  user="root",
  password="",
  database="tiempo"
)

# routes
@app.route('/', methods=['GET', 'POST'])
def bar():
    #diaDefault = (2023, 5, 15)
    #diaBuscar = datetime.date(*diaDefault)
    horaInicio = "00:00:00"
    horaFin = "23:59:59"
    diaBuscar = datetime.date.today()
    if request.method == 'POST':
        diaIntroducido = request.form['dia']
        mesIntroducido = request.form['mes']
        anoIntroducido = request.form['ano']
        horax = request.form['horax']
        horay = request.form['horay']

        if not diaIntroducido or not mesIntroducido or not anoIntroducido:
            return 'Por favor, introduce una fecha.'
        if horax or horay:
            try:
                datetime.datetime.strptime(horax, "%H:%M")
                horaInicio = horax + ":00"
            except ValueError:
                return("Formato de hora inicio incorrecto. Debe ser en formato HH:MM.")
            try:
                datetime.datetime.strptime(horay, "%H:%M")
                horaFin = horay + ":59"
            except ValueError:
                return("Formato de hora fin incorrecto. Debe ser en formato HH:MM.")

        try:
            diaOBJ = datetime.datetime.strptime(diaIntroducido, '%d')
            diaSaneado = diaOBJ.strftime('%d')
            diaProcesar = int(diaSaneado)
            mesOBJ = datetime.datetime.strptime(mesIntroducido, '%M')
            mesSaneado = mesOBJ.strftime('%M')
            mesProcesar = int(mesSaneado)
            anoOBJ = datetime.datetime.strptime(anoIntroducido, '%Y')
            anoSaneado = anoOBJ.strftime('%Y')
            anoProcesar = int(anoSaneado)
            diaBuscar = datetime.date(anoProcesar, mesProcesar, diaProcesar)

        except ValueError:
            return 'La fecha introducida no es válida.'

    mycursor = mydb.cursor()
    consulta = """
    SELECT fecha, temperatura, humedad, presion, precipitaciones, velocidad, direccion, uvi, lux, ppm
    FROM mediciones
    WHERE DATE(fecha) = %s
    AND TIME(`fecha`) >= %s
    AND TIME(`fecha`) <= %s
    ORDER BY fecha DESC
    """
    mycursor.execute(consulta, (diaBuscar, horaInicio, horaFin))
    resultado = mycursor.fetchall()
    mydb.commit()
    # Procesamiento de los datos
    fecha = [] # Fecha y hora 9999-99-99 99:99:99
    temperatura = [] # Temperatura en grados Celsius
    humedad = [] # Humedad relativa en porcentaje
    presion = [] # Presión atmosférica en milibares
    precipitaciones = [] # Precipitaciones en milímetros
    velocidad = [] # Velocidad del viento en kilómetros por hora
    direccion = [] # Dirección del viento en grados
    uv = [] # Índice UV
    lux = [] # Intensidad de la luz en lux
    ppm = [] # Concentración de CO2 en ppm

    for i in resultado:
        fecha.append(i[0])
        temperatura.append(i[1])
        humedad.append(i[2])
        presion.append(i[3])
        precipitaciones.append(i[4])
        velocidad.append(i[5])
        direccion.append(i[6])
        uv.append(i[7])
        lux.append(i[8])
        ppm.append(i[9])

    # Quitarle los segundos a la fecha
    fechaFormateada = []
    for i in fecha:
        fechaFormateada.append(i.strftime('%d-%m-%Y %H:%M'))

    # Quitarle los segundos a horaInicio y horaFin
    horaInicio = horaInicio[:-3]
    horaFin = horaFin[:-3]
    diaBuscarFormateado = diaBuscar.strftime("%d-%m-%Y")

    # Calcular maximos y minimos
    if temperatura:
        tempMax = max(temperatura)
        tempMin = min(temperatura)
        humMax = max(humedad)
        humMin = min(humedad)
        presMax = max(presion)
        presMin = min(presion)
        velMax = max(velocidad)
        velMin = min(velocidad)
        velMedia = round(sum(velocidad)/len(velocidad), 2)
        uvMax = max(uv)
        uvMin = min(uv)
        mmTotal = round(sum(precipitaciones), 2)
    else:
        tempMax = 0
        tempMin = 0
        humMax = 0
        humMin = 0
        presMax = 0
        presMin = 0
        valMax = 0
        velMin = 0
        velMedia = 0
        uvMax = 0
        uvMin = 0
        mmTotal = 0

    env = Environment()
    env.globals.update(zip=zip)
    return render_template("index.html", tempMax=tempMax, tempMin=tempMin, humMax=humMax, humMin=humMin, presMax=presMax, uvMax=uvMax, velMedia=velMedia,
                           presMin=presMin, mmTotal=mmTotal, temperaturas=temperatura,uvs=uv,luxes=lux,ppms=ppm,direcciones=direccion,
                           humedades=humedad, presiones=presion, precipitaciones=precipitaciones, velocidades=velocidad,fechas=fechaFormateada,
                           dia=diaBuscarFormateado,horax=horaInicio,horay=horaFin, zip=zip)

@app.route('/graficos', methods=['GET', 'POST'])
def graficos():
    diaDefault = (2023, 5, 15)
    diaBuscar = datetime.date(*diaDefault)
    horaInicio = "00:00:00"
    horaFin = "23:59:59"
    diaMax = diaBuscar
    diaMin = diaBuscar
    # diaBuscar = datetime.date.today()
    if request.method == 'POST':
        diaMax = request.form['desdeDia']
        mesMax = request.form['desdeMes']
        anoMax = request.form['desdeAno']
        diaMin = request.form['hastaDia']
        mesMin = request.form['hastaMes']
        anoMin = request.form['hastaAno']

        try:
            diaOBJ = datetime.datetime.strptime(diaMax, '%d')
            diaSaneado = diaOBJ.strftime('%d')
            diaProcesar = int(diaSaneado)

            mesOBJ = datetime.datetime.strptime(mesMax, '%M')
            mesSaneado = mesOBJ.strftime('%M')
            mesProcesar = int(mesSaneado)

            anoOBJ = datetime.datetime.strptime(anoMax, '%Y')
            anoSaneado = anoOBJ.strftime('%Y')
            anoProcesar = int(anoSaneado)

            diaMax = datetime.date(anoProcesar, mesProcesar, diaProcesar)

            diaOBJ = datetime.datetime.strptime(diaMin, '%d')
            diaSaneado = diaOBJ.strftime('%d')
            diaProcesar = int(diaSaneado)

            mesOBJ = datetime.datetime.strptime(mesMin, '%M')
            mesSaneado = mesOBJ.strftime('%M')
            mesProcesar = int(mesSaneado)

            anoOBJ = datetime.datetime.strptime(anoMin, '%Y')
            anoSaneado = anoOBJ.strftime('%Y')
            anoProcesar = int(anoSaneado)

            diaMin = datetime.date(anoProcesar, mesProcesar, diaProcesar)

        except ValueError:
            return 'La fecha introducida no es válida.'

    mycursor = mydb.cursor()
    consulta = """
    SELECT fecha, temperatura, humedad, presion, precipitaciones, velocidad, direccion, uvi, lux, ppm
    FROM mediciones
    WHERE DATE(fecha) >= %s
    AND DATE(fecha) <= %s
    AND TIME(`fecha`) >= %s
    AND TIME(`fecha`) <= %s
    ORDER BY fecha DESC
    """
    mycursor.execute(consulta, (diaMax, diaMin, horaInicio, horaFin))
    resultado = mycursor.fetchall()
    mydb.commit()
    # Procesamiento de los datos
    fecha = [] # Fecha y hora 9999-99-99 99:99:99
    temperatura = [] # Temperatura en grados Celsius
    humedad = [] # Humedad relativa en porcentaje
    presion = [] # Presión atmosférica en milibares
    precipitaciones = [] # Precipitaciones en milímetros
    velocidad = [] # Velocidad del viento en kilómetros por hora
    direccion = [] # Dirección del viento en grados
    uv = [] # Índice UV
    lux = [] # Intensidad de la luz en lux
    ppm = [] # Concentración de CO2 en ppm

    for i in resultado:
        fecha.append(i[0])
        temperatura.append(i[1])
        humedad.append(i[2])
        presion.append(i[3])
        precipitaciones.append(i[4])
        velocidad.append(i[5])
        direccion.append(i[6])
        uv.append(i[7])
        lux.append(i[8])
        ppm.append(i[9])

    # Quitarle los segundos a la fecha
    fechaFormateada = []
    for i in fecha:
        fechaFormateada.append(i.strftime('%d-%m-%Y %H:%M'))

    # Quitarle los segundos a horaInicio y horaFin
    horaInicio = horaInicio[:-3]
    horaFin = horaFin[:-3]
    diaBuscarFormateado = diaBuscar.strftime("%d-%m-%Y")

    # --------------------------- Graficos -------------------------------

    # Crear los objetos
    tablaTemperaturas = go.Scatter(x=fecha, y=temperatura, mode='lines', marker=dict(color='red'))
    tablaHumedades = go.Scatter(x=fecha, y=humedad, mode='lines', marker=dict(color='blue'))
    tablaPresiones = go.Scatter(x=fecha, y=presion, mode='lines', marker=dict(color='green'))
    tablaVelocidades = go.Bar(x=fecha, y=velocidad, marker=dict(color='orange'))
    tablaDirecciones = go.Bar(x=fecha, y=direccion, marker=dict(color='gray'))
    tablaPrecipitaciones = go.Bar(x=fecha, y=precipitaciones, marker=dict(color='blue'))
    tablaUVS = go.Scatter(x=fecha, y=uv, mode='lines', marker=dict(color='violet'))
    tablaPPM = go.Scatter(x=fecha, y=ppm, mode='lines', marker=dict(color='black'))
    tablaLuxes = go.Scatter(x=fecha, y=lux, mode='lines', marker=dict(color='green'))

    # Crear las figuras
    figTemperaturas = go.Figure(data=[tablaTemperaturas], layout=go.Layout(title="Gráfico de temperaturas (ºC)"))
    figHumedades = go.Figure(data=[tablaHumedades], layout=go.Layout(title="Gráfico de humedades (%)"))
    figPresiones = go.Figure(data=[tablaPresiones], layout=go.Layout(title="Gráfico de presiones (hPa)"))
    figVelocidades = go.Figure(data=[tablaVelocidades], layout=go.Layout(title="Gráfico de velocidades (km/h)"))
    figDirecciones = go.Figure(data=[tablaDirecciones], layout=go.Layout(title="Gráfico de direcciónes del viento (º)"))
    figPrecipitaciones = go.Figure(data=[tablaPrecipitaciones], layout=go.Layout(title="Gráfico de precipitaciones (mm)"))
    figUVS = go.Figure(data=[tablaUVS], layout=go.Layout(title="Gráfico de índice UV (Índice de UV)"))
    figPPM = go.Figure(data=[tablaPPM], layout=go.Layout(title="Gráfico de calidad del aire (ppm)"))
    figLuxes = go.Figure(data=[tablaLuxes], layout=go.Layout(title="Gráfico de luxes (lux)"))

    # Obtener el HTML para ambos gráficos
    graficoTemperaturas = figTemperaturas.to_html(full_html=False)
    graficoHumedades = figHumedades.to_html(full_html=False)
    graficoPresiones = figPresiones.to_html(full_html=False)
    graficoVelocidades = figVelocidades.to_html(full_html=False)
    graficoDirecciones = figDirecciones.to_html(full_html=False)
    graficoPrecipitaciones = figPrecipitaciones.to_html(full_html=False)
    graficoUVS = figUVS.to_html(full_html=False)
    graficoPPM = figPPM.to_html(full_html=False)
    graficoLuxes = figLuxes.to_html(full_html=False)

    # Renderizar los gráficos en la plantilla
    return render_template('graficos.html', temperaturas=graficoTemperaturas, humedades=graficoHumedades, presiones=graficoPresiones, velocidades=graficoVelocidades, direcciones=graficoDirecciones, precipitaciones=graficoPrecipitaciones, uvs=graficoUVS, ppms=graficoPPM, luxes=graficoLuxes, diaMax=diaMax,diaMin=diaMin)

if __name__ == "__main__":
    # Development
    # app.run(port=8080, debug=True, host='192.168.1.40')
    # Production
    from waitress import serve
    serve(app, host="0.0.0.0", port=8080)


# python
import math

from django.contrib.contenttypes.models import ContentType

# django rest
from rest_framework.response import Response
from rest_framework import status
from rest_framework.authentication import SessionAuthentication
from rest_framework.permissions import IsAuthenticated
from rest_framework.views import APIView

# django
from django.core.paginator import Paginator

# serializer
from rest_framework import serializers

class APIGenericGenerator(APIView):

	def __init__(self,**kwargs):
		self.queryset = kwargs['queryset']
		self.serializer = kwargs['serializer']

	def list(self,**kwargs):
		serializer_class = self.serializer
		serialized_objects = self.serializer(self.queryset,many=True)
		return serialized_objects.data

	def list_paginated_results(self,request,**kwargs):
		try:
			page_num = int(request.GET['page'])
			if page_num < 1: page_num = 1
		except:
			page_num = 1

		try:
			results_per_page = int(request.GET['results'])
			if results_per_page < 1: results_per_page = 1
		except:
			results_per_page = 10

		paginator = Paginator(self.queryset, results_per_page)

		try:
			page = paginator.page(page_num)
		except:
			page = paginator.page(1)

		max_pages = int(math.ceil(float(paginator.object_list.count())/float(results_per_page)))

		pagination = {
			'description' : str(page),
			'pages' : str(results_per_page),
			'current_page' : str(page.number),
			'start_index' : str(page.start_index()),
			'end_index' : str(page.end_index()),
			'total_records' : str(paginator.object_list.count()),
			'has_next' : str(page.has_next()),
			'max_pages' : str(max_pages)
		}

		serializer_class = self.serializer
		serialized_objects = self.serializer(page,many=True).data

		return {'results':serialized_objects,'pagination': pagination}


#!/usr/bin/python

import os, sys

### IMPORTANT TO BE MOVED TO SOME GLOBALS!!!
production = 'TTDIFFXS_62'

mambodir=os.environ['MAMBODIR']
user=os.environ['USER']
baseoutdir='/raid7_atlas2/%s/mambo_out/' % (user,)
os.system('mkdir -p %s' % (baseoutdir,))