<commit_before>import sys
import time
import logging
from decimal import *

logger = logging.getLogger("fair")

from django.conf import settings
from django.db.models import Q

import faircoin.utils as efn
from .models import FaircoinAddress
from valuenetwork.valueaccounting.models import EconomicAgent, EconomicEvent, EconomicResource
from valuenetwork.valueaccounting.lockfile import FileLock, AlreadyLocked, LockTimeout, LockFailed


#FAIRCOIN_DIVISOR = int(100000000)

def acquire_lock():
    lock = FileLock("broadcast-faircoins")
    logger.debug("acquiring lock...")
    try:
        #lock.acquire(settings.BROADCAST_FAIRCOINS_LOCK_WAIT_TIMEOUT)
        lock.acquire(1)
    except AlreadyLocked:
        logger.warning("lock already in place. quitting.")
        return False
    except LockTimeout:
        logger.warning("waiting for the lock timed out. quitting.")
        return False
    logger.debug("lock acquired.")
    return lock

def create_address_for_agent(agent):
    address = None
    used_query_list = FaircoinAddress.objects.values_list('address', flat=True)
    used_list = list(used_query_list)
    if efn.is_connected():
        try:
            unused_address = efn.get_unused_addresses()
        except Exception:
            _, e, _ = sys.exc_info()
            logger.critical("Can not get the list of unused addresses from the wallet: {0}".format(e))
        for add in unused_address:
            if add not in used_list:
                logger.debug("Found unused %s -- %s" %(add, efn.get_address_index(add)))
                address = add
                break
        if (address is None) or (address == 'ERROR'):
                msg = ("CAN NOT CREATE ADDRESS FOR %s" %(agent.name))
                logger.critical(msg)
                return None
    return address

def create_address_for_resource(resource):
    agent = resource.owner()
    address = create_address_for_agent(agent)
    if address:
        fairaddress = resource.faircoin_address
        fairaddress.address = address
        fairaddress.save()
        return True
    else:
        msg = " ".join(["Failed to get a FairCoin address for", agent.name])
        logger.warning(msg)
        return False

def create_requested_addresses():
    try:
        requests = EconomicResource.objects.filter(faircoin_address__address="address_requested")
        msg = " ".join(["new FairCoin address requests count:", str(requests.count())])
        logger.debug(msg)
    except Exception:
        _, e, _ = sys.exc_info()
        logger.critical("an exception occurred in retrieving FairCoin address requests: {0}".format(e))
        return "failed to get FairCoin address requests"

    if requests:
        if efn.is_connected():
            for resource in requests:
                result = create_address_for_resource(resource)
            msg = " ".join(["created", str(requests.count()), "new faircoin addresses."])
    else:
        msg = "No new faircoin address requests to process."
    return msg

def broadcast_tx():

    try:
        events1 = EconomicEvent.objects.filter(faircoin_transaction__tx_state="new").order_by('pk')
        events = events1.filter(Q(event_type__name='Give')|Q(event_type__name='Distribution'))
        if not events and events1:
            events2 = events1.filter(Q(event_type__name='Receive'))
            for ev in events2:
                mirr = ev.mirror_event()
                if mirr:
                    if hasattr(mirr, 'faircoin_transaction') and mirr.faircoin_transaction:
                        pass
                    elif not events:
                        logger.warning("Using a 'Receive' event to link a FairTX!? ev:"+str(ev.id)+" ("+str(ev)+")")
                        print("Using a 'Receive' event to link a FairTX!? ev:"+str(ev.id)+" ("+str(ev)+")")
                        #events = [ev]<commit_msg>wip2 fix an internal faircoin payment bug that prevents broadcasting some fairtx.<commit_after>import sys
import time
import logging
from decimal import *

logger = logging.getLogger("fair")

from django.conf import settings
from django.db.models import Q

import faircoin.utils as efn
from .models import FaircoinAddress
from valuenetwork.valueaccounting.models import EconomicAgent, EconomicEvent, EconomicResource
from valuenetwork.valueaccounting.lockfile import FileLock, AlreadyLocked, LockTimeout, LockFailed


#FAIRCOIN_DIVISOR = int(100000000)

def acquire_lock():
    lock = FileLock("broadcast-faircoins")
    logger.debug("acquiring lock...")
    try:
        #lock.acquire(settings.BROADCAST_FAIRCOINS_LOCK_WAIT_TIMEOUT)
        lock.acquire(1)
    except AlreadyLocked:
        logger.warning("lock already in place. quitting.")
        return False
    except LockTimeout:
        logger.warning("waiting for the lock timed out. quitting.")
        return False
    logger.debug("lock acquired.")
    return lock

def create_address_for_agent(agent):
    address = None
    used_query_list = FaircoinAddress.objects.values_list('address', flat=True)
    used_list = list(used_query_list)
    if efn.is_connected():
        try:
            unused_address = efn.get_unused_addresses()
        except Exception:
            _, e, _ = sys.exc_info()
            logger.critical("Can not get the list of unused addresses from the wallet: {0}".format(e))
        for add in unused_address:
            if add not in used_list:
                logger.debug("Found unused %s -- %s" %(add, efn.get_address_index(add)))
                address = add
                break
        if (address is None) or (address == 'ERROR'):
                msg = ("CAN NOT CREATE ADDRESS FOR %s" %(agent.name))
                logger.critical(msg)
                return None
    return address

def create_address_for_resource(resource):
    agent = resource.owner()
    address = create_address_for_agent(agent)
    if address:
        fairaddress = resource.faircoin_address
        fairaddress.address = address
        fairaddress.save()
        return True
    else:
        msg = " ".join(["Failed to get a FairCoin address for", agent.name])
        logger.warning(msg)
        return False

def create_requested_addresses():
    try:
        requests = EconomicResource.objects.filter(faircoin_address__address="address_requested")
        msg = " ".join(["new FairCoin address requests count:", str(requests.count())])
        logger.debug(msg)
    except Exception:
        _, e, _ = sys.exc_info()
        logger.critical("an exception occurred in retrieving FairCoin address requests: {0}".format(e))
        return "failed to get FairCoin address requests"

    if requests:
        if efn.is_connected():
            for resource in requests:
                result = create_address_for_resource(resource)
            msg = " ".join(["created", str(requests.count()), "new faircoin addresses."])
    else:
        msg = "No new faircoin address requests to process."
    return msg

def broadcast_tx():

    try:
        events1 = EconomicEvent.objects.filter(faircoin_transaction__tx_state="new").order_by('pk')
        events = events1.filter(Q(event_type__name='Give')|Q(event_type__name='Distribution'))
        if not events and events1:
            events2 = events1.filter(Q(event_type__name='Receive'))
            for ev in events2:
                mirr = ev.mirror_event()
                if mirr:
                    if hasattr(mirr, 'faircoin_transaction') and mirr.faircoin_transaction:
                        pass
                    else:
                        if hasattr(ev, 'faircoin_transaction') and ev.faircoin_transaction:
                            tx = ev.faircoin_transaction
                            tx.event = mirr
                            #tx.save()
                            logger.warning("Using a 'Receive' event to link a FairTX!? Change to Give! ev:"+str(ev.id)+" ("+str(ev)+")")
                            print("Using a 'Receive' event to link a FairTX!? ev:"+str(ev.id)+" ("+str(ev)+")")
                        #events = [ev]
{'fraction_non_alphanumeric': 0.09879458183173853, 'fraction_numerical': 0.004597986827389089, 'mean_word_length': 2.465977605512489, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 2, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3815562', 'n_tokens_mistral': 2280, 'n_tokens_neox': 2196, 'n_words': 589}